Repository navigation
fix(worktree): reclaim a prepared checkout whose discard failed in-process - #17899
Conversation
…ocess Speculative create-preparation evicts entries past the 3-entry limit and the 5-minute TTL, and both paths swallowed a failed `discardPreparedWorktree`. The only other reclaim path, `cleanupStalePreparations`, skips any preparation whose lock-reason pid is still alive, so a discard that failed inside the running app stranded its scratch checkout and its locked worktree registration until restart. Record the failed discard keyed by host (repo path + WSL distro) and prepared path, and retry it the next time a fresh preparation starts for that host. The retry is kicked off before `listWorktreeGraph` but never awaited, so it runs alongside the stale scan and the `worktree add` instead of sitting in front of the user's create. It is capped at 3 attempts and warns when it gives up. Enrolment is unconditional: `prepareWorktreeCreateCheckout` self-discards on failure, but only best-effort, so a checkout that failed on a busy handle can strand the same registration.
|
Warning Review limit reachedNext included review available in 3 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (3)
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.
✅ No new issues found.
Reviewed changes
- Retry registry — new
src/main/worktree-preparation-discard-retry.tsrecords a discard that failed in-process, keyed by host (repo path+ WSL distro) and prepared path, and retries it on the next fresh preparation for that host, bounded at 3 attempts with aconsole.warngive-up. - Discard wiring —
discardEntrynow routes throughdiscardPreparationWithRetry(enrolling unconditionally, including a failed checkout whose own self-discard also failed), and eviction/expiry discards are fire-and-forget viatrackPreparationDiscardso the test reset can settle them. - Retry trigger —
retryPendingPreparationDiscardsisvoid-called at the top ofcleanupStalePreparations, so reclaim work never adds latency to the awaited create path; the claim (delete-before-discard) prevents overlapping retry passes from double-running a path. - Tests — 7 new platform-agnostic tests cover live-pid retry, per-host scoping, WSL distro scoping, the 3-attempt bound + warn, failed-checkout enrollment, and the reset-settle semantics. 18/18 pass; typecheck clean.
The trade-offs the description names (fire-and-forget background Git work, unconditional enrolment chasing already-gone paths, bounded-in-practice registry) are all accurate reads of the code, and the fail-safe direction — only retry paths this process created and already tried to discard, never widening stale cleanup to live-pid preparations — is preserved.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…ocess (stablyai#17899) Speculative create-preparation evicts entries past the 3-entry limit and the 5-minute TTL, and both paths swallowed a failed `discardPreparedWorktree`. The only other reclaim path, `cleanupStalePreparations`, skips any preparation whose lock-reason pid is still alive, so a discard that failed inside the running app stranded its scratch checkout and its locked worktree registration until restart. Record the failed discard keyed by host (repo path + WSL distro) and prepared path, and retry it the next time a fresh preparation starts for that host. The retry is kicked off before `listWorktreeGraph` but never awaited, so it runs alongside the stale scan and the `worktree add` instead of sitting in front of the user's create. It is capped at 3 attempts and warns when it gives up. Enrolment is unconditional: `prepareWorktreeCreateCheckout` self-discards on failure, but only best-effort, so a checkout that failed on a busy handle can strand the same registration.

Problem
Pre-existing leak, found while investigating #17792. The speculative-preparation feature itself is unchanged.
src/main/worktree-create-preparation.tskeeps at mostWORKTREE_CREATE_PREPARATION_LIMIT = 3prepared checkouts, evicting the oldest and expiring each after a 5-minute TTL. Both paths funnel intodiscardEntry, which was:The failure was swallowed with nothing recorded. The only other reclaim path is
cleanupStalePreparations, which skips every preparation still owned by a live process:So a discard that failed inside the running app — a held file handle, a slow AV scanner, a busy directory — stranded both the scratch directory under
.orca-preparing/and its locked Git worktree registration until the app was restarted. Every later composer open walked past it, because the pid in the lock reason was its own and still alive. The 3-entry limit does not bound this: evicted entries leave the in-memory map whether or not their discard succeeded, so leaked directories accumulate across a session.What this does
New
src/main/worktree-preparation-discard-retry.tsrecords a discard that failed, keyed by host (repo path + WSL distro) and prepared path, and retries it later. A record is dropped as soon as its discard succeeds, and after 3 attempts.When the retry actually runs.
retryPendingPreparationDiscardshas exactly one caller: the first statement insidecleanupStalePreparations. That function runs only whenprepareWorktreeCreateForRepostarts a fresh preparation — it is skipped entirely by theif (existing) return existing.readyshort-circuit. So the trigger is not "the next composer open"; it is the next composer open that starts a new preparation for that host, i.e. one whose repo / workspace root / base branch / distro key is not already covered by a live cached preparation. Re-opening the composer on the same repo and base inside the 5-minute TTL will not fire a retry. In the leak's own scenario this is close to immediate, because the leak is produced by eviction or TTL expiry, both of which free the key.Where it sits relative to
listWorktreeGraph. It isvoid-called beforelistWorktreeGraph, and not awaited, so it starts concurrently with the stale-preparation scan and may still be running during themkdirandworktree addthat follow. It is deliberately not sequenced ahead of the scan:claimPreparedWorktreeawaitsentry.ready, which awaitscleanupStalePreparations, so awaiting the retry would put aworktree unlock+worktree remove --forcepair — each bounded byWORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS(30 s) — directly in front of the user's Create click, in exactly the Windows busy-handle failure mode this change targets, on the one code path whose purpose is latency. The retry never rejects and nothing downstream reads its result.Two other properties are worth stating, because each was a defect in an earlier draft:
discardPreparationWithRetryremoves the key from the registry on entry. Two composer opens for the same host can overlap now that the retry is non-blocking, and without the claim both would run the sameworktree removeconcurrently.prepareWorktreeCreateCheckoutdoes self-discard in its failure path, but throughperformDiscardPreparedWorktree(...).catch(() => {})— best-effort, exactly as fallible as the discard this change is fixing. Aworktree addthat succeeded and areset --hardthat then failed on a busy handle leaves a registered, locked worktree whose self-discard also failed; skipping enrolment there would carve the marquee Windows case out of the fix. The cost of enrolling a path that is genuinely already gone is 2 backgroundunlock+remove --forcepairs that fail with "is not a working tree" — acceptable precisely because the retry no longer blocks anything.Cleanup is not made more aggressive. It still refuses to touch a live-pid preparation it discovers via
listWorktreeGraph; only paths this process created and already tried to discard are retried. That preserves the fail-safe direction — a preparation directory is speculative scratch, so leaving one is wasted disk, while deleting the wrong thing destroys user work.The give-up branch is no longer silent: after the third failed attempt it logs
[worktree-create] prepared checkout could not be discarded in 3 attempts; <path> stays registered until this process exits.What changes for users
retryPendingPreparationDiscardsis a no-op over an empty map. If a discard fails, the stranded preparation is reclaimed when the next fresh preparation for that repo starts, instead of at app restart. No change to the awaited create path.git worktree remove --forcefails, and it is also the wayprepareWorktreeCreateCheckout's own self-discard fails.repo path + wslDistro) and each record carries its ownAddWorktreeOptions, so a failure in one distro never triggers work against another. Pinned by a test; deleting the distro from the key fails it.prepareWorktreeCreateForReporeturns early whenrepo.connectionIdis set, so no preparation is ever created on an SSH host and no record can exist.isFolderRepo(repo)returns early on the same line as the SSH check.What this does NOT do
cleanupStalePreparationsto reclaim live-pid preparations it finds on disk. That would race destructively withfinalizePreparedWorktree:claimPreparedWorktreeremoves the entry from the live map beforeworktree moveruns, so a concurrent scan would see a locked, live-pid, unmapped preparation mid-create and delete it.consumePreparedWorktreeCreatefallback discard.finalizePreparedWorktreeself-cleans throughremoveFailedFinalization, so that path usually discards an already-removed worktree.console.warn; there is no toast, badge, or notification.discardPreparedWorktree(worktree unlock+worktree remove --force), well inside the Git 2.25 baseline.resolveGitMetadataPathor any resolver nullability.discardPreparationWithRetryreturnsPromise<void>and never rejects, so theentry.readychain gains no new rejection path.Costs and residual risk
Things this makes worse, named:
worktree unlock+worktree remove --forcepair per stranded path for that host, running concurrently with the stale scan, themkdir, and theworktree add.discardPreparedWorktreewraps itself inrunWithGitReadCacheInvalidation, which clears in-flight Git read caches around the call, so a status read racing that window is re-taken. This is CPU/IO contention, not blocking, and it occurs only in the already-degraded case — but it is work main did not do at all in this scenario.entry.readyrejected beforeworktree addever ran (amkdiror base-ref failure), the recorded path does not exist; its 2 retries fail with "is not a working tree" and cost 2 background Git pairs plus 2 cache-invalidation rounds. Deliberate trade against carving out the busy-handle case where the checkout's own self-discard failed.git worktree list— until the process exits. That is today's behavior; this change makes it the floor rather than the default, and adds the diagnostic line that was missing.pendingDiscardsis bounded only by how many discards can fail, at 3 attempts each. In practice the source is capped by the 3-entry preparation limit plus the TTL, and each record is 4 strings; there is no explicit size cap.worktree-preparation-discard-retry.ts(71 lines) rather than inlining, which also keepsworktree-create-preparation.tsunder the 300-linemax-linescap. Nomax-linesdisable was added.Verification
Diff: 3 files, +310/-4.
src/main/worktree-create-preparation.test.ts: 18 passed — 11 pre-existing, 7 new. All 7 are platform-agnostic and run everywhere (the WSL scoping test driveswslDistrothrough the mocked git options, so it needs no WSL host).worktree-create-preparation-wsl-root,git/worktree-create-preparation-real-git,shared/worktree/create-preparation,git/worktree-mutation-route-invalidation,runtime/orca-runtime-create-base-prefetch— 6 files / 42 tests passed.npx oxfmt --writethennpx oxlintclean (exit 0) on all three changed files.Mutation verification — 10 mutations, each applied alone and reverted, every one killed.
void retryPendingPreparationDiscards(cleanupKey)PREPARATION_DISCARD_ATTEMPT_LIMIT→Number.POSITIVE_INFINITYstops retrying…).filter((target) => target.hostKey === hostKey)retries only the leaked paths…,scopes retries to the WSL distro…)${options.wslDistro ?? ''}frompreparationHostKeyscopes retries to the WSL distro…)pendingDiscards.clear()from the resetdrops recorded discards…,settles an evicted preparation's discard…)console.warnstops retrying…)pendingDiscards.delete(pendingKey(target))retries a discard that failed…,stops retrying…)discardEntryto skip enrolment whenentry.readyrejectedretries a failed checkout whose own self-discard…)trackPreparationDiscard(discardEntry(entry))→ barevoid discardEntry(entry)settles an evicted preparation's discard…)Every one of the 7 new tests is killed by at least one mutation of the production hunk it claims to cover, so none is vacuous. Notably:
stops retrying a preparation that never becomes removableis an exact call-count plus warn-message assertion rather than the bare negative it started as;scopes retries to the WSL distro whose preparation leaked(mutation 4) was added because the distro component of the host key was previously unpinned; andsettles an evicted preparation's discard before the reset drops the registry(mutation 10) pins that_resetWorktreeCreatePreparationsForTestswaits for a background eviction discard that is still parked on an unfinished checkout, instead of clearing the registry and letting the failure repopulate it into the next test.With all production code restored: 18/18 pass, working tree clean.