Repository navigation
Let worktree creation proceed during stale preparation reclamation - #18967
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the four commits in this PR, which split stale-preparation reclamation from the shared host scan so a new checkout no longer waits for old file removal, and switch discard to a single locked-removal command.
- Stale reclamation no longer blocks checkout —
startStalePreparationCleanupnow returns after the sharedlistWorktreeGraphscan while the 4-worker discard loop runs in the background; the in-flight entry is cleared only once reclamation settles, sohasPendingStalePreparationCleanup(and idle repo maintenance gating) stays true through reclamation — unchanged duration, just the create no longer awaits it. - Single locked-worktree removal —
performDiscardPreparedWorktreereplaces unlock-then-remove withgit worktree remove --force --force, preserving the ownership lock when removal cannot start. Double-force locked removal is documented at the Git 2.25.0 baseline, matching the existingmove -f -fassumption. - Test coverage — adds a stalled-removal regression (unit + real-Git) proving creation proceeds and the scan is shared per host key, a real-Git removal-launch-failure test proving lock/content survive, and a Git binary-compatibility case for double-force removal; also fixes expired artifact share fixtures (
expiresAt→Date.now() + 30d).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Resolves #18951 squash-merge conflicts by keeping the backgrounded stale cleanup alongside main's discard-retry review fix. Moves the checkout cancellation tests into worktree-create-preparation-cancellation.test.ts to keep the registry suite under the test-file line limit.
📝 WalkthroughWalkthroughThe changes update prepared worktree discard to use Merge Risk: 🟡 Moderate · up to Repository maintenance may overlap an active worktree removal, risking conflicting Git operations. Track retry completion before merging. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 1b48f03e-423b-48f3-a34c-05d8225d9229
📒 Files selected for processing (7)
src/main/git/worktree-create-preparation-real-git.test.tssrc/main/git/worktree-create-preparation.tssrc/main/worktree-create-preparation-cancellation.test.tssrc/main/worktree-create-preparation-pool.tssrc/main/worktree-create-preparation-stale-cleanup.tssrc/main/worktree-create-preparation.test.tssrc/shared/git-binary-compatibility.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| ...options, | ||
| includeCreatePreparations: true | ||
| }) | ||
| void retryPendingPreparationDiscards(cleanupKey) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Track pending discard retries in settled.
retryPendingPreparationDiscards(cleanupKey) starts discardPreparedWorktree() through discardPreparationWithRetry(). Its promise is tracked by the test-only inFlightDiscards registry, but not by entry.settled. After scanned resolves, another preparation can start. The cleanup finally block can then remove staleCleanupInFlight while the retry is still running, so hasPendingStalePreparationCleanup() releases maintenance gating early. resetStalePreparationCleanupForTests() also waits only for scan cleanup.
Include the retry promise in settled. Add a gated-retry test that keeps the stale-cleanup reset pending until the retry settles.
Proposed fix
- void retryPendingPreparationDiscards(cleanupKey)
+ const retries = retryPendingPreparationDiscards(cleanupKey)
const scan = listWorktreeGraph(repoPath, {
...options,
includeCreatePreparations: true
})
@@
- const entry = { scanned, settled: cleanup }
+ const settled = Promise.allSettled([retries, cleanup]).then(() => {})
+ const entry = { scanned, settled }
staleCleanupInFlight.set(cleanupKey, entry)
- void cleanup
+ void settled
.catch(() => {})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| void retryPendingPreparationDiscards(cleanupKey) | |
| const retries = retryPendingPreparationDiscards(cleanupKey) | |
| const scan = listWorktreeGraph(repoPath, { | |
| ...options, | |
| includeCreatePreparations: true | |
| }) | |
| const settled = Promise.allSettled([retries, cleanup]).then(() => {}) | |
| const entry = { scanned, settled } | |
| staleCleanupInFlight.set(cleanupKey, entry) | |
| void settled | |
| .catch(() => {}) |
…tablyai#18967) * Stop obsolete worktree preparations when evicted or expired * Let worktree preparation proceed during stale reclamation * Verify creation during stalled stale worktree reclamation * Preserve preparation ownership until Git removal starts * test: keep artifact share fixtures unexpired across calendar dates (stablyai#18955)

Stale preparations left by a crashed process could delay a new checkout until old files were removed. Preparation now proceeds after the shared host scan while bounded reclamation continues in the background. Cleanup stays tracked until it settles, so subsequent requests share the scan and repo maintenance remains gated.
Removal also uses one locked-worktree removal command instead of unlocking first. If the removal command cannot start, the ownership lock survives so the preparation remains identifiable; each discard uses one fewer Git subprocess. This does not guarantee ownership or registration survives arbitrary failures inside Git.
Stacked on #18951. Ownership selection, preservation of branch-attached workspaces, the four-worker cleanup limit, and native/WSL routing remain intact. SSH and folder workspaces remain excluded by the existing preparation-pool guard. No wire, mobile-facing schema, dependency, or UI change. Double-force locked removal is documented and implemented in Git 2.25.5; the real-binary CI contract now tests it explicitly.
Validation:
Assessed risk: low. New materialization can overlap stale cleanup in disk usage and I/O; nearly full or slower drives and live Windows/WSL concurrent removal remain unverified. No stronger eventual-cleanup guarantee is introduced. A separate paired-order real-Git scheduling probe exercised simultaneous removal/reset on this Mac, but substantial load variability makes it supporting evidence only; this PR does not claim a universal latency improvement.
This follow-up is included in the combined trial below and remains unmerged.
CI follow-up: the previous run reproduced expired fixed-date artifact fixtures (unrelated to worktree changes) after 2026-09-06 UTC. Reused upstream main commit 71f2c5d (#18955), test-only, rather than introducing a separate fix; all 34 affected artifact tests pass locally. One native-chat waitFor timeout from that run did not reproduce locally. Current-head full CI result is recorded below.
Full current-head CI passed at
986ebfe7248, including all eight test shards, Linux/Windows packaging, typecheck, static analysis, and Git compatibility.Current composer-free trial: v1.4.198-adhoc.20260906024508, source
6d989819c5ef5d85b8253d763450de9df4c88d57, includes current main681119dc05b(including A), cancellation #18951, background stale cleanup #18967, and fetch/checkout overlap #18998. Parked draft composer #18876 is excluded.Combined full typecheck, 60 focused tests, and background Electron existing Create flow passed. Downloaded ARM64 DMG passed SHA512/size, extraction identity, exact source/version, code signature and notarization. The actual background packaged app passed immediate Create, prepared Create, cancellation without additional workspaces/terminals, and real shell input/output. No draft editor appeared. Owned workspaces were clean and removed, terminal inventory returned to zero, the owned app stopped, and its remaining owned detached preparation was removed.
On the 23,608-file fixture: immediate Create took 7.317 s to observed selection; a second Create after nine seconds of composer dwell took 683 ms. Backend spans were 6.644 s and 515 ms. These are individual potentially warm-cache samples, with a blank terminal and no setup hook. They demonstrate the prepared path, not a universal cold speedup or agent readiness. Screenshots inspected. Windows release packaging is still running; no live Windows/WSL UI validation.
Post-review measurement (readiness review, 2026-09-05)
The original scheduling probe (20.51 s → 17.02 s, ~17%) was a single sample under variable machine load. Re-measured with noise control: an interleaved ABABAB design, 3 rounds × 5 iterations, n = 15 per cell, on a 10,000-file repo with N dead-owner stale preparations seeded. Baseline = the three touched source files swapped to
origin/maincontent; branch = HEAD. Git 2.55.0, macOS, load average 15–40 throughout (the interleaving cancels it).startPreparation→ readyfinalizePreparedWorktreeThe win is conditional on stale checkouts existing and scales with their size and count; it should not be quoted as a universal number. The original 17% figure is directionally consistent but under-measured.
Background-deletion vs concurrent-adopt: audited, no data-loss race found
The top risk for this change is the background reclaimer deleting a directory a concurrent Create just adopted. It cannot:
lockOwnerPidparsed from the Git lock reason and!isProcessAlive(lockOwnerPid)(worktree-create-preparation-stale-cleanup.ts:48-52). Live preparations embedprocess.pid, so the current process's own entries always fail the dead-pid check.pathOwnerPid === lockOwnerPid(:57) — the directory must still sit at.orca-preparing/<pid>-<uuid>. An adopted worktree has already been moved out byfinalizePreparedWorktree, sopathOwnerPidisnulland only theunlockbranch can apply. Never a delete.isWorktreeCreatePreparationfilters it out ofstaleWorktreesentirely. The scan is also taken before the new checkout starts.Exercised by the real-Git test that holds a dead-owner removal mid-flight while a new preparation is created and finalized (
worktree-create-preparation-real-git.test.ts:91-155).Verification
oxlintandoxfmt --checkclean on all 6 touched files; 42/42 on the two preparation suites, 369/369 across a 39-file sweep; real-binary Git compat suite 18/18 on Git 2.55.0.Counsel validation
Four-seat multi-model counsel ran in findings-severity mode; three seats reported (one aborted on context length). All three independently rated the three candidate findings false-positives and dropped them, so nothing is release-blocking:
pathOwnerPid === lockOwnerPid; live preparations stampprocess.pidon both path and lock; the scan snapshot is taken beforemkdir/worktree add, so it cannot contain the current create's path; an adopted worktree sits outside.orca-preparing, makingpathOwnerPidnull so onlyunlockcan apply. PID reuse skips reclaim (a leak, never a delete).cleanup.catch(() => {}).finally(...)with an identity guard,await scanned.catch, per-discard.catch, boundedWORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, and a map single-flighted per host key.remove --force --forcecompat) — dropped. Double-force locked removal is the documented form on the Git 2.25 baseline, matching the existingmove -f -fcontract;windowsLongPathGitArgsonly prepends-c core.longpaths=trueand does not rewrite subcommand flags. Compat CI covers 2.25.5 / 2.38.1 / 2.49.1.Additional P2 observations raised during counsel, none blocking:
removebefore the underlying call, so add/finalize complete first; a genuinely concurrentworktree add/moveversusremove --force --forceis still untested. A lock clash would fall back to a normal add, and that fallback path is unproven.30s x ceil(n/4).retryPendingPreparationDiscardsruns only on a new cleanup, not on joiners; after three attempts, failed discards leak until process exit and are then reclaimed by dead-pid cleanup.listWorktreeGraphsoftens a failed listing to[](worktree-listing.ts:41-42), so a failed enumeration is indistinguishable from "no stale checkouts". Rescanned on the next prepare.