Repository navigation
fix(bench): stabilize list-bench fixture and record thread-count findings - #2683
Merged
Merged
Conversation
…ings `cargo bench --bench list` was failing ~30% of runs partway through fixture setup with "fatal: unable to read tree", "invalid object ... for 'src/file_N.rs'", "unable to create temporary file", or "failed to insert into database". Root cause: git's auto-maintenance (`gc.auto` + `maintenance.auto`) was firing during the 500-commit fixture-build loop. A detached `git gc` packed and pruned loose objects in parallel with the foreground `git add` / `git commit`, occasionally racing to produce corrupt state. Partial-failure repos contained 5-6 pack files plus a `tmp_pack_*` artifact — the smoking gun. Fix: in `create_repo_at`, set `gc.auto=0`, `gc.autoPackLimit=0`, and `maintenance.auto=false` on the fresh repo right after `git init`. 10/10 sequential `wt-perf setup typical-8` builds now pass after the fix. That fix alone leaves fixtures in a loose-object cold-clone shape that doesn't match what mature user repos look like — packed, with a commit-graph. On the divergent fixture the loose-vs-packed gap is ~2.3× wall (587ms vs ~250ms with all packed). So `create_repo_at` also runs an explicit `git gc` at the end, after all commits, branches, and worktrees are in place. The result is one packfile + one commit-graph + zero loose objects, matching day-N user repos. Using the stabilized benches to answer the question in PR #2662's follow-up: should `rayon_thread_count` bump from 2x CPU now that we have one pool instead of two? Swept `RAYON_NUM_THREADS` across {0.5x, 1x, 1.5x, 2x, 3x, 4x, 6x} on an 18-CPU machine, against `divergent_branches/warm` (branch-heavy) and `worktree_scaling/warm/8` (worktree-heavy). 3x CPU was at or within noise of the per-workload optimum on both; 2x trailed by 0-5% (divergent 259ms vs 257ms with overlapping CIs; worktree 86.6ms vs 82.4ms, ~5% gap). 4x regressed on branch-heavy workloads. We stay at 2x — the win is small in absolute terms (≤5ms) and 2x has been validated in production on hardware we haven't benchmarked. Docstring on `rayon_thread_count` updated to record the test and the reasoning. No behavior change to wt itself. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
worktrunk-bot
approved these changes
May 11, 2026
This was referenced May 11, 2026
Closed
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]>
6 tasks done
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
cargo bench --bench listwas failing ~30% of runs partway through fixture setup with errors like "fatal: unable to read tree", "invalid object ... for 'src/file_N.rs'", "unable to create temporary file", or "failed to insert into database". Root cause: git's auto-maintenance (gc.auto+maintenance.auto) fires during the 500-commit fixture-build loop and races the foregroundgit add/git commit. Partial-failure repos contained 5-6 pack files plus atmp_pack_*— smoking gun for a detached pack/prune in flight.create_repo_atnow silences both auto-maintenance knobs aftergit init, and runs one explicitgit gcat the end after all commits, branches, and worktrees are in place. The result: 10/10 sequentialwt-perf setup typical-8builds pass, and fixtures land in a packed shape (one packfile + commit-graph, zero loose objects) that matches day-N user repos rather than the loose-object cold-clone shape they had before.Thread-count follow-up to #2662
Using the stabilized benches to answer the question in #2662's "Follow-ups": should
rayon_thread_countbump from 2× CPU now that we have one pool instead of two? SweptRAYON_NUM_THREADSacross {0.5×, 1×, 1.5×, 2×, 3×, 4×, 6×} on an 18-CPU machine againstdivergent_branches/warm(branch-heavy) andworktree_scaling/warm/8(worktree-heavy). 3× CPU was at or within noise of the per-workload optimum on both; 2× trailed by 0–5% (divergent 259ms vs 257ms with overlapping CIs; worktree 86.6ms vs 82.4ms, ~5% gap). 4× regressed on branch-heavy workloads.Stayed at 2×: the win is small in absolute terms (≤ 5ms) and 2× has been validated in production on hardware we haven't benchmarked. Docstring on
rayon_thread_countrecords the test and the reasoning so the next person who asks doesn't have to redo the experiment.Test plan
cargo run -- hook pre-merge --yes— 3547 tests passwt-perf setup typical-8 --persist× 10 sequential — no failures (pre-fix: ~30% failure rate)cargo bench --bench list divergent_branches/warm— completes, packed shape (1 pack, 0 loose)cargo bench --bench list worktree_scaling/warm/8— completes🤖 Generated with Claude Code