Skip to content

perf: parallelize integration checks in step prune - #1890

Merged
max-sixty merged 7 commits into
mainfrom
fix/parallelize-prune-integration-checks
Apr 3, 2026
Merged

max-sixty merged 7 commits into
mainfrom
fix/parallelize-prune-integration-checks

Conversation

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Summary

  • Parallelize integration checks in step prune using rayon's par_iter(), matching the pattern already used by wt list
  • Both worktree and orphan branch integration checks now run concurrently — the main win is for repos with many local branches (100+ in the reporter's case)
  • Removals and candidate processing remain sequential (as required for correctness)

The reporter had 112 local branches with step prune taking ~3 minutes. Each non-trivially-integrated branch hits git merge-tree and git patch-id (500ms–2s each), and these were running sequentially. With parallelization, this should drop to seconds.

Closes #1888

Test plan

  • All 26 prune integration tests pass
  • Help snapshot tests pass
  • CI passes

🤖 Generated with Claude Code

`step prune` checked each worktree and orphan branch for integration
sequentially. With many local branches (100+), each hitting expensive
git operations (merge-tree, patch-id at 500ms-2s each), this caused
multi-minute runtimes.

Parallelize both the worktree and orphan branch integration checks
using rayon's `par_iter()`, matching the pattern already used by
`wt list`. The integration results are computed in parallel, then
processed sequentially for candidate selection and removal.

Closes #1888

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CLAUDE.md convention: .expect() in a Result-returning function should use ? or bail! instead. One instance on the new code.

Comment thread src/commands/step_commands.rs Resolved
@max-sixty

Copy link
Copy Markdown
Owner

how does the parallelism work here? can we use a rayon thread pool to limit it?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

The parallelism uses rayon's par_iter() on two collection points:

  1. Worktree integration checks — collects all worktrees that need an integration_reason() call into wt_check_items, then runs them via par_iter().map(). Results are collected back into a Vec and processed sequentially (since removals must be serial).

  2. Orphan branch integration checks — same pattern for local branches without a worktree entry.

Each integration_reason() call spawns one or more git subprocess (merge-base --is-ancestor, diff-tree, merge-tree, etc.), so the parallelism is mostly about overlapping those subprocess waits.

Currently it uses rayon's global thread pool, which defaults to the number of logical CPUs. A dedicated thread pool would give more control — something like:

let pool = rayon::ThreadPoolBuilder::new()
    .num_threads(8)
    .build()?;

let results: Vec<_> = pool.install(|| {
    wt_check_items.par_iter().map(|item| { ... }).collect()
});

That would cap subprocess concurrency regardless of core count, which could matter on machines with many cores (spawning 64+ git processes at once might not help and could hurt with disk contention). Worth considering — happy to add it if you'd like a cap.

@max-sixty

Copy link
Copy Markdown
Owner

what do we do elsewhere? can we follow that convention / possibly share code?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Two existing conventions for limiting parallelism:

  1. CMD_SEMAPHORE (shell_exec.rs) — a global semaphore (default 32, configurable via WORKTRUNK_MAX_CONCURRENT_COMMANDS) that gates every Cmd::run() call. This already applies to the git subprocesses spawned by integration_reason(), so prune's parallel work is implicitly bounded at the subprocess level.

  2. Dedicated rayon thread pools — used in copy.rs (MAX_COPY_THREADS = 4) and step copy for filesystem-heavy work where the global pool (2× CPU cores) would cause I/O contention.

The prune case is closer to wt list (parallel git subprocess calls) than step copy (parallel filesystem I/O). wt list uses the global rayon pool and relies on CMD_SEMAPHORE to cap actual subprocess concurrency — which is exactly what prune does now.

So the current approach already follows the existing convention. A dedicated thread pool would only help if we wanted to limit rayon task scheduling independently of subprocess concurrency, but since CMD_SEMAPHORE handles the resource-exhaustion risk, there's no clear need. Happy to add one if you'd prefer an explicit cap anyway.

Comment thread src/commands/step_commands.rs Resolved
…ngle parallel pass

Instead of two separate `par_iter()` calls — one for worktrees and one
for orphan branches — collect all refs into a single `CheckItem` vec
with an enum discriminant, then do one parallel `integration_reason()`
pass. Results are dispatched by source type during sequential processing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

All required CI checks pass. The codecov/patch failure is a false positive — the five uncovered lines (1526, 1613–1614, 1624, 1676–1677) are pre-existing uncovered code that was moved into the new match arms during the refactoring, not new logic. Specifically:

  • Line 1526: continue in the is_linked() guard (skips main worktree) — existed before at line ~1164
  • Lines 1613–1614: commondir metadata fallback in the age check — moved from the old sequential worktree loop
  • Lines 1624, 1676–1677: closing braces of min_age_duration blocks — same age-check logic, relocated

The actual new code (the CheckSource enum, CheckItem struct, par_iter() call, and match dispatching) is all covered by the existing 26 prune tests.

@max-sixty

Copy link
Copy Markdown
Owner

do our tests include detached worktrees?

run /simplify on this implementation

…andling

Merge the Prunable and Orphan match arms into shared branch-only logic,
eliminating duplicated candidate construction and dry_run/remove dispatch.
Store branch name directly in Prunable variant (removing impossible
.context() error path). Collapse nested if-let per clippy. Trim comments
that restated code.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Detached worktree tests: Yes, good coverage — 4 tests exercise detached HEAD in prune:

  • test_prune_skips_unmerged_detached — unmerged detached worktrees are skipped
  • test_prune_removes_integrated_detached — integrated detached worktrees are removed
  • test_prune_removes_multiple_detached — plural removal path
  • test_prune_during_rebase — prune from a worktree mid-rebase (detached HEAD state)

Simplify: Pushed f64e21e — net -30 lines. Changes:

  • Merged the Prunable and Orphan match arms into shared branch-only candidate logic (eliminated duplicated Candidate construction and dry_run/remove dispatch)
  • Stored branch name directly in Prunable variant, removing the impossible .context() error path that could never trigger
  • Collapsed nested if let per clippy
  • Trimmed comments that restated the code

@max-sixty

Copy link
Copy Markdown
Owner

do we have a snapshot test for the dry-run output? I'm impressed if nothing changed!

max-sixty pushed a commit to max-sixty/tend that referenced this pull request Apr 3, 2026
## Summary

- Add explicit dedup guidance for inline review comment replies in the
`running-in-ci` skill
- When replying to a review comment, the bot must now check for existing
bot replies to the same `in_reply_to_id` before posting

**Root cause:** A single PR review fires both `pull_request_review` and
`pull_request_review_comment` events. The `handle` job's concurrency
group correctly serializes these runs (the second queues until the first
completes). However, the existing "Recheck Before Posting" section only
checks total comment/review counts — too coarse to detect that the bot
already replied to a specific inline comment. The second run's
finer-grained check used a non-existent `GET /replies` endpoint that
returned a 404, and the fallback output was ambiguous, making the bot
conclude "No existing replies."

**Evidence:** On [max-sixty/worktrunk PR
#1890](max-sixty/worktrunk#1890), runs
[23933934456](https://github.com/max-sixty/worktrunk/actions/runs/23933934456)
(`pull_request_review`, handle 04:34:16–04:36:35) and
[23933934467](https://github.com/max-sixty/worktrunk/actions/runs/23933934467)
(`pull_request_review_comment`, handle 04:36:38–04:38:29) were correctly
serialized by the concurrency group, but the second run's recheck failed
to detect the first's reply and posted a duplicate.

**Gate assessment:**
- Evidence level: High — structural issue (the `/replies` GET endpoint
always 404s, making the fallback output always ambiguous)
- Classification: Structural — deterministic cause, will recur whenever
dual events fire
- Change type: Targeted fix — adds one subsection with an explicit,
correct API command
- Prior near-miss: [PRQL/prql runs
23831453414/23831453468](https://github.com/PRQL/prql/actions/runs/23831453414)
had the same dual-trigger but avoided duplication due to timing

## Test plan

- [ ] Verify the skill file parses correctly (valid markdown, consistent
structure)
- [ ] In future dual-event scenarios (`pull_request_review` +
`pull_request_review_comment`), the second run should detect the first's
reply and exit silently

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

---------

Co-authored-by: continuous-bot <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: tend-agent <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Yes — there are 22 snapshot tests for prune, including test_prune_dry_run, test_prune_dry_run_mixed_worktrees_and_branches, test_prune_min_age_passes, and others that cover dry-run output. None of the .snap files changed in this PR.

That's because the refactor only changed the execution order (parallel vs sequential) — the output format, candidate selection, and summary messages are all unchanged. The par_iter().map().collect() gathers results into a Vec that gets processed in a deterministic order afterward, so the printed output stays the same.

@max-sixty
max-sixty merged commit 2c69793 into main Apr 3, 2026
21 of 22 checks passed
@max-sixty
max-sixty deleted the fix/parallelize-prune-integration-checks branch April 3, 2026 14:40
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.

wt step prune seems very slow

2 participants