Skip to content

perf(bench): cheaper cargo bench --bench list (lazy fixtures + lighter real-repo sampling) - #2685

Merged
max-sixty merged 2 commits into
mainfrom
picker-thread-count-bench
May 11, 2026
Merged

max-sixty merged 2 commits into
mainfrom
picker-thread-count-bench

Conversation

@max-sixty

@max-sixty max-sixty commented May 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two changes that make cargo bench --bench list cheaper to run, especially when filtered. No production code, no change to what the benches measure on a full run.

1. Lazy fixture creation. The synthetic wt list bench groups built their fixture repos eagerly at group-registration time: bench_skeleton, bench_full, bench_worktree_scaling, bench_many_branches, and bench_divergent_branches looped over their (worktrees, cold) variants and called create_repo for every one — before Criterion applied its positional FILTER. So cargo bench --bench list skeleton/warm/8 still paid to build all 6 skeleton fixtures plus all 6 full, all 6 worktree_scaling, both many_branches (100 branches each), and both divergent_branches (200 branches × 20 commits each) before measuring one benchmark.

This moves create_repo (and the setup_fake_remote / git status prep) inside the bench_with_input / bench_function closure — exactly how bench_real_repo and bench_real_repo_many_branches already work. Criterion invokes that closure once per benchmark and only for benchmarks the filter selects, so an excluded variant now creates no fixture at all.

Hermeticity is unchanged: each benchmark still gets its own fresh TempDir + repo via create_repo, created exactly once, before b.iter (so never inside the measured region), alive for the whole measurement loop, dropped right after. Marginally cleaner if anything — a filtered-out benchmark now produces zero state instead of a stray TempDir.

2. Trim real_repo_many_branches sampling. That group ran 10 samples against a 60s measurement_time — but at ~3.7s per wt list --branches iteration on rust-lang/rust, Criterion filled the budget with ~2 iterations per sample (~74s of measured time per bench_function). The warm-path variance is dominated by the slowest single subprocess (a deep git merge-base walking history), not measurement noise, so 5 samples already pins the signal. Cut to sample_size(5) + measurement_time(20s) — ≈ one iteration per sample (~18s), so the group's two bench_functions drop from ~3.6min to ~1.7min of measured time. (Cutting sample_size alone would have saved nothing — Criterion sizes iterations-per-sample to fill measurement_time.)

Effect

  • cargo bench --bench list <non-matching-filter> → ~0.2s (measured), down from minutes of fixture churn
  • cargo bench --bench list skeleton/warm/1 → 1 fixture built, was 6
  • real_repo_many_branches group → ~1.7min measured, was ~3.6min
  • Full unfiltered cargo bench --bench list → fixture count unchanged; real-repo group ~2min faster

Test plan

  • cargo check --benches
  • cargo bench --bench list -- --test skeleton — all 6 variants pass
  • cargo bench --bench list -- --test <non-matching> — 0.23s, no fixtures created
  • cargo run -- hook pre-merge --yes — 3585 tests pass, lints pass

🤖 Generated with Claude Code

`bench_skeleton`, `bench_full`, `bench_worktree_scaling`, `bench_many_branches`,
and `bench_divergent_branches` built their fixture repos eagerly at
group-registration time — every `(worktrees, cold)` variant got a fresh
`create_repo` call regardless of whether criterion's positional FILTER selected
it. So `cargo bench --bench list skeleton/warm/8` still paid for all 6 skeleton
fixtures (plus all 6 full, all 6 worktree_scaling, both many_branches, both
divergent) before measuring one.

Move `create_repo` (and the `setup_fake_remote` / `git status` prep) inside the
`bench_with_input` / `bench_function` closure — matching how `bench_real_repo`
and `bench_real_repo_many_branches` already work. Criterion invokes the closure
exactly once per benchmark and only for benchmarks the filter selects, so an
excluded variant now creates no fixture at all.

Hermeticity is unchanged: still one fresh TempDir + repo per benchmark, created
once before `b.iter` (so never in the measured region), alive for the whole
measurement loop, dropped right after.

Effect: `cargo bench --bench list <non-matching-filter>` drops from minutes of
fixture churn to ~0.2s (measured); `cargo bench --bench list skeleton/warm/1`
builds 1 fixture instead of 6. Full unfiltered runs are unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`bench_real_repo_many_branches` ran 10 samples against a 60s measurement
budget — but at ~3.7s per `wt list --branches` iteration on rust-lang/rust,
criterion filled the budget with ~2 iterations per sample (~74s of measured
time). The warm-path run-to-run variance comes from the slowest individual
subprocess (a deep `git merge-base`), not measurement noise, so a handful of
samples already pins the signal.

Drop to 5 samples and a 20s budget — ≈ one iteration per sample (~18s), so
the group's two bench_functions go from ~3.6min to ~1.7min of measured time
(setup unchanged). Cutting `sample_size` without also cutting
`measurement_time` would have saved nothing, since criterion sizes
iterations-per-sample to fill the budget.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@max-sixty max-sixty changed the title perf(bench): build list-bench fixtures lazily, gated by criterion filter perf(bench): cheaper cargo bench --bench list (lazy fixtures + lighter real-repo sampling) May 11, 2026
@max-sixty
max-sixty merged commit df35af9 into main May 11, 2026
31 checks passed
@max-sixty
max-sixty deleted the picker-thread-count-bench branch May 11, 2026 05:51
max-sixty added a commit that referenced this pull request May 11, 2026
…n floor (#2695)

## Summary

Two changes to `benches/list.rs`, no production code.

**1. Trim `bench_real_repo` sampling.** It inherited the
`criterion_group` default `sample_size(30)` / `measurement_time(15s)`.
On rust-lang/rust `wt list` runs ~2s warm (dominated by one deep `git
for-each-ref %(ahead-behind:main)` walk) and several times that for
`cold/8`, where every iteration also rebuilds eight 59k-entry git
indexes via `git status`. At >1s/iter Criterion can't fit 30 samples in
15s, so it just runs 30 single-iteration samples per variant — the group
as a whole runs ~15–20 min, dominated by `real_repo/cold/{4,8}`. Set
`sample_size(10)` (criterion 0.8's hard minimum) +
`measurement_time(20s)`, mirroring what #2685 did for
`bench_real_repo_many_branches`. The expensive cold variants drop from
30 to 10 iterations → group's measured time roughly thirds (~6–8 min).
No change to what `wt list` runs or measures.

**2. Fix a latent panic in `bench_real_repo_many_branches`.** #2685 set
it to `sample_size(5)`, but criterion 0.8's `sample_size` does
`assert!(n >= 10)` (`benchmark_group.rs:97`), so `cargo bench --bench
list` currently **panics on `main` during group registration** — for any
filter, before any benchmark runs. Restored to `sample_size(10)`. (This
was also a prerequisite for running `bench_real_repo` to validate change
#1.)

## Why not sparse-checkout the rust clone

A sparse checkout would make the per-variant setup near-instant and `git
status` / `git diff --shortstat HEAD` on the rust worktrees ~10ms
instead of ~1.8s / ~0.8s — but those costs are exactly what the `cold`
(cold 59k-entry index rebuild) and `warm` (working-tree scan over 59k
files) variants exist to measure. Sparse-checkout would turn "cold index
on a huge repo" into "cold index on ~20 files", erasing the documented
`cold ~4×` insight. The mechanism works; it's the wrong tradeoff.
Sharing one rust workspace across the warm/cold pair was also considered
and dropped — after the sampling trim, setup is a small slice (~1.5–2
min of ~7 min), and sharing would require up to ~10 GB of simultaneous
rust checkouts (CI disk risk) for a marginal gain.

## Before / after

`real_repo/warm/1` (rust-lang/rust clone, one worktree): median
**1.809s** (30 samples) → **1.794s** (10 samples). Criterion's
regression check on the after run: `change: [−23.1% −7.0% +10.8%] (p =
0.59)` → "No change in performance detected." The cold variants — the
bulk of the group — drop 3× by arithmetic (30→10 single iterations of
the same operation).

## Test plan

- [x] `cargo run -- hook pre-merge --yes` — 3645 tests pass, clippy +
fmt + pre-commit hooks pass
- [x] `cargo bench --bench list -- 'real_repo/warm/1'` — runs cleanly,
`sample_size(10)` accepted ("Collecting 10 samples"), result above
- [x] `cargo clippy --benches -- -D warnings`, `cargo check --benches`,
`cargo fmt --check`

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 11, 2026
…f walk on warm runs (#2704)

## Summary

`wt list --branches` computed branch ahead/behind counts with one `git
for-each-ref --format='%(ahead-behind:BASE)'` walk, on every invocation,
in the post-skeleton setup scope. That walk is O(commits) — ~1.5s on
rust-lang/rust — and it runs *serially before the parallel task pool
opens*, because the per-branch tasks consume its result. So on a large
real repo roughly 40% of `wt list`'s wall time was a single-threaded git
graph walk that thread count couldn't help with (a follow-up from the
picker thread-count investigation in #2683/#2685).

Ahead/behind for `(base, branch)` is a pure function of the two commit
SHAs — content-addressed, never stale — exactly the shape of the
existing `.git/wt/cache/` SHA-keyed caches. This adds an `ahead-behind/`
cache kind and rewires the population path:

- New `ahead-behind/{base_sha}-{head_sha}.json` kind in `sha_cache.rs`,
identical machinery to `is-ancestor` / `diff-stats` (LRU-bounded,
cleared by `wt config state clear`, wiped by the bench
cache-invalidator).
- `Repository::ahead_behind_by_sha` is now cache-backed: check →
`compute_ahead_behind` → write.
- `RefSnapshot::capture_refs_with_ahead_behind` builds the snapshot's
ahead/behind map from the cache and only walks the graph for the
branches the cache doesn't cover:
- **a few misses** → left out of the snapshot map; the per-branch
`AheadBehindTask` recomputes (and caches) them by SHA in the parallel
pool. (That task already runs `merge_base_by_sha` for its orphan check,
so the merge-base `compute_ahead_behind` needs is already primed — the
fallback is just two cheap `rev-list --count` calls.)
- **everything cold** (fresh repo / after `wt config state clear`) → one
unscoped `for-each-ref %(ahead-behind:BASE_SHA) refs/heads/` walk — a
single shared traversal finds every merge-base — then results written to
the cache.
- **many cold but not all** → one `for-each-ref
%(ahead-behind:BASE_SHA)` *scoped to just the missed refnames* (`git
for-each-ref` takes a ref list, so it's still one shared traversal, only
over the cold subset), results written to the cache.

The few-vs-many threshold (`AHEAD_BEHIND_SCOPED_BATCH_MIN_MISSES`)
trades the per-pair path's parallelism (it runs in the pool) against the
batch's lower total work (one shared base-history traversal); a batch
here is serial, so it's only worth it once "many" misses make the
amortization clear.

### Cache-correctness details (Codex-prompted)

A few sharp edges, surfaced by `/review-codex`, that the seeding path
now handles explicitly:

- **`%(ahead-behind)` computed against the *resolved SHA*, not the
refname.** A tag named `main` shadows the branch in git's ref
resolution; passing `base_sha` to the batch makes it inert to that. The
fallback path (default branch isn't a local/remote-tracking ref) still
passes the refname and caches nothing.
- **Cache key from the batch's `%(objectname)`, not a separately-scanned
value.** If a `refs/heads/X` moved between `scan_locals` and the batch
(a sub-ms window, but possible), the counts are for the *new* SHA — and
the cache now stores them under that SHA, not under the staler
`b.commit_sha`.
- **Orphan branches normalized to `(0, 0)` before writing.** Git's
`%(ahead-behind:BASE)` for an orphan (no common ancestor) prints the two
disjoint history sizes; `compute_ahead_behind` returns `(0, 0)` and
signals orphan-ness separately. An orphan's `behind` count equals base's
total commit count, so one `git rev-list --count base_sha` on the
seeding path detects them. The cache invariant — cache hit equals what a
miss would recompute — holds for orphans now.
- **Bulk-write avoids O(N · dir_size) on the seeding path.**
`write_with_lru` scans the cache directory on every call to enforce the
LRU bound; the serial setup-scope seeding loop calls it N times.
`put_ahead_behind_bulk` writes all N entries first and sweeps once at
the end.

### Net effect

| | before | after |
|---|---|---|
| warm `wt list` on a large repo | ~1.5s serial `for-each-ref
%(ahead-behind)` in the setup scope | N small cache reads; no graph
walk; no serial blocker |
| `wt list` after committing on one branch | full ~1.5s walk again
(batch op — any change re-walks all) | only that branch recomputed (two
cheap `rev-list --count`, in the pool); the rest stay cached |
| many branches moved since last list | full walk | one `for-each-ref
%(ahead-behind)` scoped to just the moved ones |
| cold (fresh repo / after `state clear`) | one combined walk |
unchanged — one combined walk + one bulk cache seed |
| skeleton time (`WORKTRUNK_SKELETON_ONLY`) | — | unaffected (returns
before the scope this touches) |

No user-facing behavior change — same numbers, same columns. The picker
(`wt switch`) shares this path, so its preview pre-compute benefits
identically.

### Follow-ups left as TODOs in the code

- `TODO(ahead-behind-pool)` (`src/commands/list/collect/mod.rs`): the
cold-cache `%(ahead-behind)` walk still runs serially in the setup
scope, blocking the task pool from opening. Nothing downstream of
work-item generation needs the *counts* (only the per-row
`AheadBehindTask`, which has a per-SHA fallback) — only the cheap ref
scan does. So the walk could become a single work item in the pool,
overlapping the other ~N workers. Needs an inter-task dependency the
work-item model doesn't have today.
- `TODO(remote-ahead-behind-batch)`
(`src/commands/list/collect/tasks.rs`): the `Remote⇅` column's
per-branch `ahead_behind_by_sha(upstream, branch)` is already
cache-backed by this change, but has no cold-start batch primer. One
`for-each-ref --format='%(refname) %(upstream:track,nobracket)'
refs/heads/` would fill the `ahead-behind/` cache for it in a single
walk, mirroring what `%(ahead-behind:main)` does for `main↕`.

## Testing

- `sha_cache.rs`: round-trip + cache-read tests for the new kind;
`test_clear_all_covers_all_kinds` extended.
- `ref_snapshot.rs`: all-cold→unscoped-batch + cold→warm second-capture
reads the persistent cache; partial-warm (few misses) omits the moved
branch; many-misses uses the scoped batch; **orphan normalizes to
`(0,0)` in both the snapshot and the cache file**; remote-tracking base
resolves; unresolvable base degrades cleanly.
- Smoke-tested manually: `wt list --branches` populates
`.git/wt/cache/ahead-behind/`; tampering an entry → the next run shows
the tampered counts (proves the read path).
- Two passes of `/review-codex` — second pass clean.
- `cargo run -- hook pre-merge --yes` — full suite + lints + doc-sync
(3595 tests).

## Out of scope (flagged, not done here)

`docs/dev/cache-staleness.md` still references the in-memory
`RepoCache.ahead_behind` field and `batch_ahead_behind` — both removed
when `RefSnapshot` landed. Pre-existing staleness; rewriting that doc is
a separate cleanup. (The pre-skeleton `git log --no-walk` commit-details
batch is also content-addressed by SHA and could in principle be
cache-first, but it's already O(refs) and fast — not worth a TODO.)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 11, 2026
## Summary

- Adds `picker_preview` benchmark group measuring "process spawn → all
preview tasks drained" for `wt switch`'s interactive picker.
- Introduces `WORKTRUNK_PREVIEW_BENCH=1`, an early-exit gate inside
`handle_picker` that runs the full prelude (collect, speculative spawn,
skeleton, initial + deferred precompute, `orchestrator.wait_for_idle()`)
and returns before skim launches or any JSON / stderr I/O. Shares the
dry-run path; behavior with the env var unset is unchanged.
- Closes the coverage gap behind #2662 / #2683 / #2685 / #2704, which
were tuned against `wt list` as a proxy because no direct picker
measurement existed.

## Why this measurement

Picker submits one preview-compute task per row to the global rayon
pool. The user-visible quantity to optimize is the responsiveness window
between picker launch and "all previews ready" (j/k navigation hits
cached content). Option 1 from the task — headless wall clock to drain —
is the cleanest measurable proxy and avoids the PTY route, which hits
the documented nextest/SIGTTOU pain on `shell-integration-tests`.
PTY-driven first-interactive-ready can be a follow-up.

## Variants

- `picker_preview/warm/typical-8`
- `picker_preview/cold/typical-8`

Cold uses `BatchSize::PerIteration` (not `SmallInput`): `SmallInput`
calls `setup` for an entire batch up front and then runs timed routines
back-to-back, so only the first iter in each batch is genuinely cold —
the rest hit a freshly populated `.git/wt/cache/`. `PerIteration`
invalidates immediately before every measured iteration; setup is far
cheaper than `wt switch`, so per-iter `Instant::now` doesn't dominate.

`sample_size(10)` + `measurement_time(35s)` per #2685's lead — slow
benches don't benefit from the default 30 samples.

`cfg(unix)`-gated with a no-op `main` on Windows; the picker is
Unix-only and `wt switch` (no args) hits the unavailable path before the
env var is consulted.

## Sample run

```
picker_preview/warm/typical-8   time:   [185.62 ms 191.72 ms 200.77 ms]
picker_preview/cold/typical-8   time:   [209.34 ms 226.23 ms 239.29 ms]
```

## Test plan

- [x] `cargo bench --bench picker_preview` runs cleanly on both variants
- [x] `cargo run -- hook pre-merge --yes` — 3667 tests pass
- [x] New `test_picker_preview_bench_produces_no_output` asserts
`WORKTRUNK_PREVIEW_BENCH=1` keeps stdout/stderr empty (covers the
env-gated branch, locks the no-I/O contract)
- [x] Smoke test: `wt switch` with `WORKTRUNK_PREVIEW_BENCH` unset still
hits the TTY error path (user-visible behavior unchanged)
- [x] Smoke test: `WORKTRUNK_PICKER_DRY_RUN=1` still emits the cache
JSON dump (regression check)
- [x] `/review-codex` pass clean after iterating on three findings
(packed-refs fix already on `main` via #2697 once branch was rebased;
`BatchSize::PerIteration` for true per-iter invalidation; `cfg(unix)`
gate for Windows)

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants