Repository navigation
perf(worktrees): delete worktree directories after the removal returns - #12416
Conversation
`git worktree remove` deleted the whole checkout inline, so the remove IPC held the watcher/PTY gate for the entire recursive delete (prod traces: worktree.remove.git_remove p50 8-14s, p90 29s, max 34.7s). Local removals now rename the checkout into a hidden sibling trash root, clear Git's registration for the missing path, and delete the moved tree in the background. Renames that cannot run (WSL, other volume, Windows open handles) fall back to the previous in-place removal unchanged.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughWorktree removal now stages clean checkouts in a sibling trash directory, deregisters them from Git, and deletes staged directories asynchronously. It falls back to inline removal for unsupported or failed staging cases and restores staged paths when deregistration fails. Startup sweeps stale trash entries from eligible workspace roots. Tests cover mocked flows, real Git behavior, Git compatibility, cleanup, and large-tree performance. 🚥 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: 2
🧹 Nitpick comments (6)
src/main/worktree-trash.ts (2)
126-144: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider the effect of the container cap on repeated sweeps.
collectExistingTrashRootscaps containers at 200 using thereaddirorder. If a workspace root holds more than 200 container directories, and the order is stable, the trash roots beyond the cap are never swept. Leftovers there stay on disk permanently.Two options keep the sweep cheap and still make progress:
- Skip the cap and only
jointhe candidate names, because building paths is cheap and the cost is dominated by the per-rootreaddirinsweepStaleWorktreeTrash.- Rotate the starting offset per run so later containers are eventually reached.
The name also states existence, but the function does not check it.
collectCandidateTrashRootsdescribes the behavior more exactly.
152-155: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winKeep runtime-host repos out of the local trash sweep.
Runtime repos are distinguished by
executionHostId; a runtime repo withconnectionId: nullcurrently passes this filter and computes a localrepo.pathworkspace root, despite the comment saying sweep roots are only local git repos. Add the same runtime-host/host-qualification exclusion and reuse a shared local-repo predicate.src/main/git/worktree.ts (1)
1239-1246: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚖️ Poor tradeoff
git worktree pruneacts on the whole repository.The comment at line 1226 correctly notes that
worktree remove --forcetouches one entry. The fallback at line 1239 does not.git worktree prunederegisters every worktree whose directory Git cannot find. If another worktree of the same repo sits on a volume that is temporarily unmounted, and it is not locked, this fallback silently deletes its registration too.Consider scoping the recovery, for example by running
git worktree pruneonly after confirming that no other registered worktree path is missing, or by preferringgit worktree remove --forceretries before pruning.src/main/git/remove-worktree.test.ts (1)
425-474: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a forced-removal case to this group.
The suite covers the clean, dirty, WSL, prune-fallback, and restore paths. It does not cover
force === true. On that pathtryRemoveWorktreeWithDeferredDirectoryDeletionskips the cleanliness probe and still renames the checkout aside. A test would pin that behavior, because a future guard that requires a clean probe would silently disable deferred removal for forced deletes.💚 Suggested additional test
it('renames a dirty checkout aside when removal is forced', async () => { mockGitCommands({ 'git worktree list --porcelain': { stdout: `worktree /repo HEAD abc123 branch refs/heads/main worktree /repo-feature HEAD def456 branch refs/heads/feature/test ` }, 'git worktree list --porcelain#2': { stdout: `worktree /repo HEAD abc123 branch refs/heads/main ` } }) moveWorktreeDirectoryToTrashMock.mockResolvedValue('/trash/wt-4-abcdef04') await removeWorktree('/repo', '/repo-feature', true) expect(getGitCalls()).not.toContain('git status --porcelain --untracked-files=all') expect(scheduleWorktreeTrashDeletionMock).toHaveBeenCalledWith('/trash/wt-4-abcdef04') })src/main/git/worktree.test.ts (1)
26-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSet the default resolved value outside the mock factory.
Line 27 configures
mockResolvedValueinside the factory expression. It works becausemockResolvedValuereturns the mock, but it hides the default from readers and it is lost if any suite-widevi.resetAllMocks()runs. Declare the export plainly and set the default inbeforeEach.♻️ Proposed change
-// Default: the checkout cannot be renamed aside, so removal deletes it in place. vi.mock('../worktree-trash', () => ({ - moveWorktreeDirectoryToTrash: moveWorktreeDirectoryToTrashMock.mockResolvedValue(undefined), + moveWorktreeDirectoryToTrash: moveWorktreeDirectoryToTrashMock, restoreWorktreeDirectoryFromTrash: vi.fn().mockResolvedValue(true), scheduleWorktreeTrashDeletion: vi.fn() }))Then in the existing
beforeEach:// Default: the checkout cannot be renamed aside, so removal deletes it in place. moveWorktreeDirectoryToTrashMock.mockResolvedValue(undefined)src/main/git/worktree-removal-large-tree.bench.test.ts (1)
44-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLimit the concurrent
writeFilecalls in the fixture build.Line 47 starts 500 concurrent
writeFileoperations per directory. Each one holds a file descriptor, and Node does not throttle them. On a machine with a low softulimit -nthis fails withEMFILEbefore the benchmark runs. Write the batch in smaller chunks.♻️ Proposed change
for (let dirIndex = 0; dirIndex < FIXTURE_DIRECTORIES; dirIndex += 1) { const dir = join(worktreePath, 'node_modules', `pkg-${dirIndex}`) await mkdir(dir, { recursive: true }) - await Promise.all( - Array.from({ length: FIXTURE_FILES_PER_DIRECTORY }, (_unused, fileIndex) => - writeFile(join(dir, `file-${fileIndex}.js`), `module.exports = ${fileIndex}\n`) - ) - ) + for (let start = 0; start < FIXTURE_FILES_PER_DIRECTORY; start += WRITE_BATCH_SIZE) { + const size = Math.min(WRITE_BATCH_SIZE, FIXTURE_FILES_PER_DIRECTORY - start) + await Promise.all( + Array.from({ length: size }, (_unused, offset) => { + const fileIndex = start + offset + return writeFile(join(dir, `file-${fileIndex}.js`), `module.exports = ${fileIndex}\n`) + }) + ) + } }Add the constant beside the existing fixture constants:
const WRITE_BATCH_SIZE = 64
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 02c6f997-9645-4c14-a810-2bbf2974f3b0
📒 Files selected for processing (10)
src/main/git/remove-worktree.test.tssrc/main/git/worktree-deferred-removal-real-git.test.tssrc/main/git/worktree-removal-large-tree.bench.test.tssrc/main/git/worktree.test.tssrc/main/git/worktree.tssrc/main/index.tssrc/main/observability/instrumentation.tssrc/main/worktree-trash.test.tssrc/main/worktree-trash.tssrc/shared/git-binary-compatibility.test.ts
| // Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout. | ||
| // Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \ | ||
| // --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the stage name in the header comment.
The comment names worktree.remove.git_remove. This PR adds the worktree.remove.trash_rename stage, and the benchmark at line 66 measures the whole removeWorktree call rather than one stage.
📝 Proposed change
-// Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout.
+// Manual benchmark for user-visible `removeWorktree` latency on a large checkout.📝 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.
| // Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout. | |
| // Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \ | |
| // --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts | |
| // Manual benchmark for user-visible `removeWorktree` latency on a large checkout. | |
| // Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \ | |
| // --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts |
🧰 Tools
🪛 ast-grep (0.45.0)
[warning] 3-3: Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
| void sweepStaleWorktreeTrash( | ||
| collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings()) | ||
| ).catch((error) => { | ||
| console.warn('[worktrees] Failed to sweep leftover worktree directories:', error) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect the enclosing function and any narrowing of `store` before the sweep call.
fd -t f 'index.ts' src/main --max-depth 1 | while IFS= read -r file; do
sed -n '2520,2610p' "$file"
done
rg -nP '"strict(NullChecks)?"\s*:' -g 'tsconfig*.json'Repository: stablyai/orca
Length of output: 4280
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"
sed -n '2450,2545p' "$file"
sed -n '300,325p' "$file"
printf '\n--- tsconfig strict settings ---\n'
for f in $(git ls-files 'tsconfig*.json'); do
echo "# $f"
rg -n '"strict(NullChecks)?"\s*:' "$f" || true
done
printf '\n--- direct store null checks before call ---\n'
python3 - <<'PY'
from pathlib import Path
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
for i,l in enumerate(lines,1):
if 'let store:' in l:
print(f"{i}: {l}")
if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())' in l:
for n in range(max(1,i-180), i+1):
print(f"{n}: {lines[n-1]}")
print(f"CALL_LINE={i}")
PYRepository: stablyai/orca
Length of output: 15248
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"
ast-grep outline "$file" --match 'app.isPackaged|function |const |export' --view compact | sed -n '1,220p'
printf '\n--- relevant enclosing declarations around store ---\n'
sed -n '2450,2615p' "$file"
printf '\n--- tsconfig strict settings ---\n'
while IFS= read -r f; do
echo "# $f"
rg -n '"strict(NullChecks)?"\s*:' "$f" || true
done < <(git ls-files 'tsconfig*.json')Repository: stablyai/orca
Length of output: 302
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"
printf '%s\n' '# tsconfig files'
git ls-files 'tsconfig*.json'
printf '%s\n' '# each tsconfig top-level non-auto-extracted strict flags'
python3 - <<'PY'
import json, glob
for f in sorted(glob.glob('tsconfig*.json')):
print(f"## {f}")
txt=open(f).read().splitlines()
for i,l in enumerate(txt,1):
s=l.strip()
if s.startswith('"strict'):
print(f"{i}: {s}")
PY
printf '%s\n' '# enclosing scopes and control-flow between store declaration and sweep call'
python3 - <<'PY'
from pathlib import Path
import re
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
store_line=None
sweep_line=None
for i,l in enumerate(lines,1):
if 'let store:' in l: store_line=i
if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())' in l: sweep_line=i
print(f"store_line={store_line}, sweep_line={sweep_line}")
if store_line and sweep_line:
block=[]
for n in range(store_line, sweep_line+1):
tag=[]
if 'function ' in lines[n-1] or '=> ' in lines[n-1] or '{' in lines[n-1] or '}' in lines[n-1] or 'if ' in lines[n-1] or 'while ' in lines[n-1] or 'store' in lines[n-1]:
tag='#'
print(f"{n:4} {tag} {lines[n-1]}")
PY
printf '%s\n' '# explicit Store-null checks between declaration and sweep call'
python3 - <<'PY'
from pathlib import Path
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
store_line=None
sweep_line=None
for i,l in enumerate(lines,1):
if 'let store:' in l: store_line=i
if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())' in l: sweep_line=i
query=[]
for n in range(store_line or 1, sweep_line or len(lines)+1):
if re.search(r'\bstore\b', lines[n-1]) and re.search(r'(==|!==|=|getRepos\(|getSettings\(|onSettingsChanged\()', lines[n-1]):
query.append((n, lines[n-1]))
print(query)
PYRepository: stablyai/orca
Length of output: 50370
Add a null guard before the first direct store property access.
store is only declared as Store | null; the subsequent direct call on line 2600 is no longer controlled by the null-check. Use store!.getSettings(...) consistently with the other asserted accesses in this function, or add an explicit guard before this code path.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 92905db2-b7d5-4540-9624-d27bf4c27d9a
📒 Files selected for processing (4)
src/main/git/remove-worktree.test.tssrc/main/git/worktree.tssrc/main/worktree-trash.test.tssrc/main/worktree-trash.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/git/remove-worktree.test.ts
- src/main/worktree-trash.ts
- src/main/worktree-trash.test.ts
|
Electron QA evidence — macOS, CDP,
Before deletion Confirmation After deletion |
stablyai#12416) * perf(worktrees): delete worktree directories after the removal returns `git worktree remove` deleted the whole checkout inline, so the remove IPC held the watcher/PTY gate for the entire recursive delete (prod traces: worktree.remove.git_remove p50 8-14s, p90 29s, max 34.7s). Local removals now rename the checkout into a hidden sibling trash root, clear Git's registration for the missing path, and delete the moved tree in the background. Renames that cannot run (WSL, other volume, Windows open handles) fall back to the previous in-place removal unchanged. * test(worktrees): keep no empty trash root when the rename cannot run * fix(worktrees): harden deferred trash cleanup * fix(worktrees): keep WSL trash on its owning host



Summary
Deleting a workspace froze on "Deleting…" for 8–35 s.
git worktree removedeletes the whole checkout — usually a multi-GBnode_modules— synchronously inside the remove IPC, and Orca holds the file-watcher removal gate and PTY teardown for that entire window (prod traces:worktree.remove.git_removep50 8–14 s, p90 29 s, max 34.7 s over 21 removals; the worst singlegit.execwas 31.6 s).Local worktree removal now does the standard two-phase delete:
<worktree parent>/.orca-worktree-trash/wt-<epoch>-<nonce>) — a metadata operation on the same volume.git worktree remove --force <path>(falls back togit worktree prune+ a strict registration re-check if that ever fails).wt-<digits>-<8 hex>name.Anything that cannot be renamed falls back to the previous in-place removal with no behavior change: WSL-hosted checkouts (deleted inside the distro), cross-volume paths (
EXDEV), Windows open handles (EPERM/EBUSY), and dirty checkouts.recoverLocalWindowsWorktreeRemovalis untouched and still covers the Windows partial-removal path. The SSH/remote provider path and folder workspaces are untouched.Return payloads, branch deletion (
worktree.remove.branch_delete), and all error messages are unchanged. One new span stage,worktree.remove.trash_rename, was added toWorktreeRemoveStage.Measured before/after
Fixture: scratch repo + worktree holding a committed 100 000-file tree (200 dirs × 500 files), generated programmatically by
src/main/git/worktree-removal-large-tree.bench.test.ts(opt-in viaORCA_WORKTREE_REMOVAL_BENCH=1). Baseline measured on the parent commit with the same fixture and harness. macOS/APFS.removeWorktree~25–40× faster for the user; the recursive delete demonstrably completes afterwards (the bench asserts the trash root is empty once the queue settles). Startup sweep:
sweepStaleWorktreeTrashis verified against a simulated leftover trash directory in bothsrc/main/worktree-trash.test.tsand the real-Git suite.The ~160–270 ms that remains is the cleanliness probe:
git worktree removere-checks the worktree at removal time, so the rename path re-proves the same thing withgit status --porcelain --untracked-files=allbefore moving anything. That check is what Git itself was already running, so it is not new work on the fast path — but on a fallback removal (WSL excepted, which returns before the probe) it is now run twice. That was the deliberate trade: dropping it would let a file written between the IPC preflight and the removal be trashed silently.Screenshots
No visual change.
Testing
npx oxlinton all changed files (clean), plus the pre-commit oxlint + react-doctor + oxfmt gatespnpm run tcpnpm exec vitest run --config config/vitest.config.ts src/main/git/ src/main/worktree-trash.test.ts src/main/ipc/worktrees.test.ts src/main/local-worktree-removal-recovery.test.ts src/main/local-worktree-filesystem.test.ts— 964 passedsrc/shared/git-binary-compatibility.test.tsrun against Git 2.38.1 and 2.49.1 images locally (CI also runs 2.25.5); the new case provesworktree remove --forcederegisters a renamed-away worktree. Manually verified the same on 2.24.4 and 2.26.3 containers, which bracket the 2.25 baseline.ORCA_WORKTREE_REMOVAL_BENCH=1benchmark, before and after (numbers above)pnpm build— not run (no bundling-relevant change)New/updated coverage:
src/main/git/worktree-deferred-removal-real-git.test.ts(real Git binary): registration cleared andgit worktree listno longer shows the path; sibling worktrees stay registered; branch deletion identical; a dirty checkout is never renamed aside; startup sweep removes leftover trash. The first case fails on the parent commit (no trash root is ever created there) — verified by stashing the source change and re-running.src/main/git/remove-worktree.test.ts: rename-then-deregister taken on success;prunefallback when deregistration fails; restore + in-place removal when the registration survives pruning; in-place removal when the rename is unavailable (the WindowsEPERM/ cross-volume shape); dirty checkout never renamed; WSL never renamed.src/main/worktree-trash.test.ts: rename/restore semantics, background deletion, sweep removes only generated entry names (a stray directory, a stray file, live worktrees and deeper trash roots all survive), and sweep-root derivation skips SSH repos and folder workspaces.src/mainsuite: the only failures are 13 pre-existing local false reds inpty.test.ts/updater.test.ts/worktree-base-directory-poller.test.ts— confirmed identical onorigin/mainwith the same command.src/main/ipc/worktrees.test.tsmocksremoveWorktreewholesale, so it needed no new cases: the change lives entirely below that seam, and its existing 200+ cases (including the removal span-stage assertions) pass unchanged.AI Review Report
Self-review focused on: safety-gate preservation, Git-version compatibility, cross-platform path/rename semantics, and blast radius of the sweep.
git worktree removeexactly as before, and the IPC'sisOrphanedWorktreeErrorrecovery still fires.git worktree remove --forceon a missing directory was verified to succeed and to touch only the targeted entry on 2.24.4, 2.26.3, 2.38.1 and 2.49.1 — it works at and below the 2.25 baseline, so noGitCapabilityCachecapability was added; a plain try/prunefallback with a strict registration re-check covers any binary that behaves differently. The boundary is now asserted in the real-binary CI contract.path.join/dirname; the trash root is always the worktree's own parent, so the rename never crosses a volume by construction. WindowsEPERM/EBUSYfrom open handles andEXDEVboth resolve to "deferral unavailable" → previous behavior; background deletion reusesremoveHostTree, which already carries the Windows transient-retry contract. WSL returns before the probe so nothing renames a distro-owned path from the Windows side. No shortcuts, labels, or UI touched.<worktree>/.gitcreation and<worktree>deletion, so the trash root (kept in place, never deleted) produces no structural rescans, and the background deletion happens under a name no watcher or PTY can be spawned into.Security Audit
wt-<Date.now()>-<4 random bytes hex>. Nothing is interpolated into a shell — Git is invoked through the existingexecFile-based runner with argument arrays.^wt-\d+-[0-9a-f]{8}$; at most 200 repo containers per root. Stray files/directories inside a trash root are left alone (asserted in tests).fs.rmdoes not traverse symlinks, so a planted symlink inside a trash root cannot redirect the delete.Notes
.orca-worktree-trashdirectory now persists (empty) beside worktrees after the first deletion in a repo. Removing it on drain would fire a spurious structural rescan in the workspace-root poller, which is exactly the churn this PR reduces, so it is deliberately left in place.ORCA_WORKTREE_REMOVAL_BENCH=1) and skipped in CI; it exists so the before/after numbers are reproducible.