Repository navigation
perf(worktrees): gate worktree metadata hygiene on evidence, not on every listing - #18034
Conversation
There was a problem hiding this comment.
ℹ️ No critical issues — two minor observations worth considering.
Reviewed changes
- Hygiene gate (
local-worktree-metadata-prune-gate.ts) — a module-level gate that parks the metadata + lineage prune until evidence re-arms it (a worktree lifecycle event, an ownership-releasing mutation, or a changed git listing), so steady state is zero passes. - Probe selection (
missing-local-worktree-metadata-pruning.ts,local-worktree-metadata-scan-expectation.ts) — an advisory pre-statfilter (selectProbeableLocalWorktreeMetadataCandidatesplus the extractedisLocallyRemovableWorktreeMetadataRow) that shrinks the fan-out to rows a delete could still accept. - Signal wiring —
invalidateLocalWorktreeMetadataPruneInputs/requireLocalWorktreeMetadataPrune/forgetLocalWorktreeMetadataPruneGatecalls across session, SSH-lease, automation, and repo-lifecycle write paths. - Listing path (
detected-worktree-scan-cache.ts+ handlers) — gates expectation capture and lineage pruning onhygieneDue, leaving callers with no gate on the prior eager behavior. - Tests — four new suites including a Store-driven signal test and a 20-poll / one-capture convergence assertion.
The isLocallyRemovableWorktreeMetadataRow extraction is faithful to the old inline check, and the selector is a superset of what the authoritative prune removes (identical predicates on the same state), so it can only shrink the fan-out, never widen a delete. Gating lineage off hygieneDue is required for coupling — when the metadata prune is skipped, preservedMetadataCandidateIds is unavailable and lineage must share the cadence.
ℹ️ Disabling or re-targeting an automation releases a pin without signaling the gate
collectPersistedWorkspaceOwners pins a workspace only while automation.enabled && automation.workspaceMode === 'existing', but among the automation write paths only deleteAutomation and a non-final → final updateAutomationRun transition signal the gate. updateAutomation (toggling enabled off, switching workspaceMode away from 'existing', or changing workspaceId) releases that pin with no invalidateLocalWorktreeMetadataPruneInputs(), so a dangling row it un-pins now lingers until some unrelated signal shows up. This is the one-way failure direction the PR leans on and the leak itself is #17776's deferral, so it is not blocking — flagging for completeness against the PR's own enumerated signal set.
Technical details
# Unsignaled pin release in updateAutomation
## Affected sites
- src/main/persistence/scheduling-automations/automation-definition-operations.ts:121 — `updateAutomation` mutates `enabled`/`workspaceMode`/`workspaceId` but never calls `invalidateLocalWorktreeMetadataPruneInputs()`.
- src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts:48 — `collectPersistedWorkspaceOwners` pins `automation.workspaceId` only while `enabled && workspaceMode === 'existing'`.
## Required outcome
- When `updateAutomation` drops an existing-workspace pin (enabled flips false, workspaceMode leaves 'existing', or workspaceId changes away from a value), signal the prune gate exactly as `deleteAutomation` does.
## Suggested approach (optional)
- In `updateAutomation`, after computing `updated`, call `invalidateLocalWorktreeMetadataPruneInputs()` when `current` pinned a workspace and `updated` no longer pins that same workspace.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| // Why not on the first listing: a repo we have never scanned is already due by default, and the | ||
| // scan that produced this listing is the pass that covers it. Re-arming here would double it. | ||
| if (previous !== undefined) { | ||
| requireLocalWorktreeMetadataPrune(repoId) |
There was a problem hiding this comment.
An event that arrives through invalidateDetectedWorktreeScanCache already re-arms this repo (via requireLocalWorktreeMetadataPrune), and the next fresh listing then differs from the stored fingerprint, so requireLocalWorktreeMetadataPrune here fires a second time and the following poll runs another full capture + stat fan-out. Every lifecycle event thus costs two hygiene passes — bounded, but needless on the ~1.4k-row store this PR targets.
Technical details
requireLocalWorktreeMetadataPrune (and invalidateDetectedWorktreeScanCache) do not clear listingFingerprintByRepo, so the re-armed repo still compares against its pre-event fingerprint and re-arms on the first fresh listing. Clearing that repo's fingerprint when the event re-arms it makes the post-event listing a first observation and collapses the double pass.
…very listing Dangling `worktreeMeta` pruning rode the detected-worktree listing, a polled read path. Each pass captured a prune expectation over the repo's whole metadata table (a JSON.stringify per row) and then stat'd every path-missing candidate. Both are O(all rows), and most rows are refused anyway — pinned by a persisted session, or structurally unremovable on this host — so the work repeated forever without converging, pinning the main process in fs completion callbacks (#17775). Three changes, no behavior lost: - Probe only rows a delete could still accept. Session ownership and structural removability are pure functions of persisted state, so deciding them before the filesystem inverts the cheap and expensive halves. The filter is advisory; the authoritative checks are unchanged, so it can only shrink the stat fan-out. - Extract `isLocallyRemovableWorktreeMetadataRow` so probe-avoidance and the delete share one definition of removability. - Gate the metadata + lineage prune on evidence instead of the listing: a worktree lifecycle event, a mutation that can make a row more removable (session-owner release, metadata removal, SSH lease release, automation run finishing or deletion, repo deregistration), or a git listing that differs from the one the last pass ran against. With none of those the pass is a provable repeat and is skipped, so a quiescent app does no hygiene work at all. The gate deliberately ignores metadata writes that only add or update a claim: the listing path itself stamps metadata, so re-arming on those would restore the storm. A missed signal leaves a row in place until the next one; nothing is deleted that would not have been deleted anyway.
f977ce6 to
3590406
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe change adds an evidence-based gate for local worktree metadata pruning. Detected-worktree scans claim hygiene only when required by generation changes, lifecycle events, or listing changes. Metadata probes now use advisory candidate filtering before the authoritative removal check. Scan results propagate hygiene ownership to IPC handlers and side effects. Persistence operations invalidate the gate when ownership constraints are released. Tests cover gate behavior, candidate filtering, scan side effects, and persistence signals. Merge Risk: 🟡 Moderate · up to The PR substantially reduces repeated worktree metadata scanning, but cleanup eligibility is consumed before asynchronous cleanup finishes, so an interrupted or superseded pass can leave stale metadata or lineage until a later invalidation; no-op automation deletions can also cause unnecessary repository-wide rescans. Merge should require explicit owner acceptance or a retry/rollback path for these bounded reliability and performance risks. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides a detailed explanation of the bug, implementation, rationale, linked issue, scope, exclusions, and test results. It does not follow all template headings and omits an explicit visual-proof N/A statement and checklist completion, but the required information is mostly present. Full details: Linked Issues checkExplanation The PR addresses the CPU and heat portion of [ Resolution Either implement the remaining [
✨ 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: 39064638-b77d-452e-b84e-a1bc3f974f11
📒 Files selected for processing (17)
src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.tssrc/main/ipc/worktrees/listing/detected-provider-listing.tssrc/main/ipc/worktrees/listing/detected-worktree-scan-cache.tssrc/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.tssrc/main/ipc/worktrees/listing/register-worktree-catalog-handlers.tssrc/main/local-worktree-metadata-prune-gate.test.tssrc/main/local-worktree-metadata-prune-gate.tssrc/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.tssrc/main/persistence/loading-store/metadata-lineage-operations.tssrc/main/persistence/loading-store/repo-lifecycle-operations.tssrc/main/persistence/loading-store/session-host-partitions.tssrc/main/persistence/loading-store/store-prune-gate-signals.test.tssrc/main/persistence/scheduling-automations/automation-definition-operations.tssrc/main/persistence/scheduling-automations/automation-run-operations.tssrc/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.tssrc/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.tssrc/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| (entry) => entry.automationId !== id | ||
| ) | ||
| // Why: the automation and its unfinished runs were pinning their workspace; both are gone (#17775). | ||
| invalidateLocalWorktreeMetadataPruneInputs() |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Avoid rearming the gate for a no-op delete.
If id matches neither an automation nor an automation run, deleteAutomation releases no workspace claim. This call still increments the global prune generation. Each local repository then performs another metadata scan and filesystem probe pass. Track whether either filter removed a row, and invalidate only when state changed.
Merging both import blocks during the rebase pushed the file past the 300-line budget. The two calls are one intention -- retire this repo's gate state on a full removal, and re-arm the shared inputs either way -- so name that in the module that owns the gate.
…very listing (stablyai#18034) * perf(worktrees): gate worktree metadata hygiene on evidence, not on every listing Dangling `worktreeMeta` pruning rode the detected-worktree listing, a polled read path. Each pass captured a prune expectation over the repo's whole metadata table (a JSON.stringify per row) and then stat'd every path-missing candidate. Both are O(all rows), and most rows are refused anyway — pinned by a persisted session, or structurally unremovable on this host — so the work repeated forever without converging, pinning the main process in fs completion callbacks (stablyai#17775). Three changes, no behavior lost: - Probe only rows a delete could still accept. Session ownership and structural removability are pure functions of persisted state, so deciding them before the filesystem inverts the cheap and expensive halves. The filter is advisory; the authoritative checks are unchanged, so it can only shrink the stat fan-out. - Extract `isLocallyRemovableWorktreeMetadataRow` so probe-avoidance and the delete share one definition of removability. - Gate the metadata + lineage prune on evidence instead of the listing: a worktree lifecycle event, a mutation that can make a row more removable (session-owner release, metadata removal, SSH lease release, automation run finishing or deletion, repo deregistration), or a git listing that differs from the one the last pass ran against. With none of those the pass is a provable repeat and is skipped, so a quiescent app does no hygiene work at all. The gate deliberately ignores metadata writes that only add or update a claim: the listing path itself stamps metadata, so re-arming on those would restore the storm. A missed signal leaves a row in place until the next one; nothing is deleted that would not have been deleted anyway. * refactor(worktrees): fold repo prune-gate teardown behind one call Merging both import blocks during the rebase pushed the file past the 300-line budget. The two calls are one intention -- retire this repo's gate state on a full removal, and re-arm the shared inputs either way -- so name that in the module that owns the gate. Mirror-Of: f9db653
…very listing (stablyai#18034) * perf(worktrees): gate worktree metadata hygiene on evidence, not on every listing Dangling `worktreeMeta` pruning rode the detected-worktree listing, a polled read path. Each pass captured a prune expectation over the repo's whole metadata table (a JSON.stringify per row) and then stat'd every path-missing candidate. Both are O(all rows), and most rows are refused anyway — pinned by a persisted session, or structurally unremovable on this host — so the work repeated forever without converging, pinning the main process in fs completion callbacks (stablyai#17775). Three changes, no behavior lost: - Probe only rows a delete could still accept. Session ownership and structural removability are pure functions of persisted state, so deciding them before the filesystem inverts the cheap and expensive halves. The filter is advisory; the authoritative checks are unchanged, so it can only shrink the stat fan-out. - Extract `isLocallyRemovableWorktreeMetadataRow` so probe-avoidance and the delete share one definition of removability. - Gate the metadata + lineage prune on evidence instead of the listing: a worktree lifecycle event, a mutation that can make a row more removable (session-owner release, metadata removal, SSH lease release, automation run finishing or deletion, repo deregistration), or a git listing that differs from the one the last pass ran against. With none of those the pass is a provable repeat and is skipped, so a quiescent app does no hygiene work at all. The gate deliberately ignores metadata writes that only add or update a claim: the listing path itself stamps metadata, so re-arming on those would restore the storm. A missed signal leaves a row in place until the next one; nothing is deleted that would not have been deleted anyway. * refactor(worktrees): fold repo prune-gate teardown behind one call Merging both import blocks during the rebase pushed the file past the 300-line budget. The two calls are one intention -- retire this repo's gate state on a full removal, and re-arm the shared inputs either way -- so name that in the module that owns the gate.

Fixes #17775 (the CPU/heat half).
The bug
Dangling
worktreeMetapruning rode the detected-worktree listing — a polled read path. Every pass did two things that are O(all metadata rows for the repo):JSON.stringifyper row.stated every path-missing candidate....and then discovered most rows are refused anyway. That's the inversion: the cheap half of the decision ran after the expensive half.
Worse, a large class of rows is permanently refused, so the work repeated forever without converging. The reporter's store (1,458 meta rows, 98.7% path-missing, 13 repos, 5s listing TTL) turns that into a sustained ~288
stat/s plus megabytes ofJSON.stringifyper minute in the main process — matching the reporteduv__work_done→node::fs::AfterIntegersample.The permanently-refused rows are rejected by predicates that are pure functions of persisted state — chiefly a locator also known on a remote host (which leaves a second identity alias that vetoes removal,
local-worktree-metadata-scan-expectation.ts:219) and a legacy row pinned to another execution host (:229). Neither needs the disk, and neither changes on its own.The fix
1. Probe only rows a delete could accept. New
selectProbeableLocalWorktreeMetadataCandidatesapplies session-ownership and structural-removability filters before the filesystem. Advisory by construction —pruneSessionlessMissingLocalWorktreeMetadataForRepostill re-checks authoritatively — so it can only shrink thestatfan-out, never widen a delete.2. One definition of removability. Extracted
isLocallyRemovableWorktreeMetadataRowso probe-avoidance and the delete cannot drift apart.3. Gate hygiene on evidence, not on a clock. The metadata + lineage prune now runs only on:
With none of those, the pass is a provable repeat and is skipped. Steady state is zero hygiene passes.
The constraint that shaped this
The listing path itself writes worktree metadata (
worktree-discovery-metadata.ts:61, discovery backfill and host-ownership stamping). A gate that re-armed on any metadata write would re-arm from the very scan it gates and restore the storm. So the gate deliberately ignores writes that only add or update a claim — those can only preserve more rows. There is an explicit negative test for this.Failure direction
One-way by design: a signal we miss leaves a dangling row in place until the next one arrives. Hygiene lags; nothing is deleted that would not have been deleted anyway.
Testing
pnpm tcclean;pnpm run check:code-quality:changed→ 0 findings.src/main/persistence src/main/ipc: 4335 passed.src/main: 29652 passed, 4 failed — all verified unrelated.run-electron-vite-dev×2 fail identically on the baseline commit;codex-session-index-heal-stateandterminal-history-tombstone-retryare main-thread timing tests that pass 3/3 in isolation on this branch and fail only under parallel suite load.New tests:
local-worktree-metadata-prune-gate.test.ts— gate semantics (8).detected-worktree-scan-hygiene-gate.test.ts— gated scan path, including a 20-poll/one-capture convergence assertion (8).probeable-local-worktree-metadata-candidates.test.ts— selector, including an equivalence check that it selects exactly what the authoritative prune removes (5).store-prune-gate-signals.test.ts— drives the realStore(3), because a mutation unwiring a call site would survive any test that pokes the gate module directly.Scope — deliberately not covered
git worktree listvolume (5133 of 11318 trace spans). The 5s listing TTL is still a floor of ~1 exec per repo per 5s while the renderer polls. Removing it means change-gating the scan cache off the existing base-directory poller — same root cause as open [Bug][Linux/WSL2]: IDE freezes after long session — renderer ~52% CPU from continuous git.exec polling; runtime becomes unreachable #15882.diagnostics memoryCPU contradictingps(expectation 3 in the issue) — untouched.Adjacent bug found, not fixed here
repoStillMatches/routingStillMatchescompare repo, project and settings by object identity, across a window that spans the git subprocess and the FS probe. Any replacement of those objects during that window rejects every row for the repo. Under write churn that presents as non-convergence. It belongs to #17776, flagging rather than fixing.