Skip to content

perf(worktrees): gate worktree metadata hygiene on evidence, not on every listing - #18034

Merged
nwparker merged 2 commits into
mainfrom
nwparker/bug-macos-main-100-cpu-fan-heat-persists-on-1.4
Sep 2, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/bug-macos-main-100-cpu-fan-heat-persists-on-1.4

Conversation

@nwparker

@nwparker nwparker commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​474 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​474
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​268 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​240

Fixes #17775 (the CPU/heat half).

The bug

Dangling worktreeMeta pruning rode the detected-worktree listing — a polled read path. Every pass did two things that are O(all metadata rows for the repo):

  1. Captured a prune expectation over the whole table — a JSON.stringify per row.
  2. 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 of JSON.stringify per minute in the main process — matching the reported uv__work_done → node::fs::AfterInteger sample.

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 selectProbeableLocalWorktreeMetadataCandidates applies session-ownership and structural-removability filters before the filesystem. Advisory by construction — pruneSessionlessMissingLocalWorktreeMetadataForRepo still re-checks authoritatively — so it can only shrink the stat fan-out, never widen a delete.

2. One definition of removability. Extracted isLocallyRemovableWorktreeMetadataRow so 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:

  • a worktree lifecycle event for the repo (existing worktree-change invalidator hub),
  • a mutation that can make a row more removable — session-owner release, metadata removal, SSH lease release, automation run finishing or being deleted, repo deregistration,
  • a git listing differing from the one the last pass ran against (backstop for changes no event reported).

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 tc clean; pnpm run check:code-quality:changed → 0 findings.
  • src/main/persistence src/main/ipc: 4335 passed.
  • Full src/main: 29652 passed, 4 failed — all verified unrelated. run-electron-vite-dev ×2 fail identically on the baseline commit; codex-session-index-heal-state and terminal-history-tombstone-retry are 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 real Store (3), because a mutation unwiring a call site would survive any test that pokes the gate module directly.

Scope — deliberately not covered

Adjacent bug found, not fixed here

repoStillMatches / routingStillMatches compare 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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-stat filter (selectProbeableLocalWorktreeMetadataCandidates plus the extracted isLocallyRemovableWorktreeMetadataRow) that shrinks the fan-out to rows a delete could still accept.
  • Signal wiring — invalidateLocalWorktreeMetadataPruneInputs / requireLocalWorktreeMetadataPrune / forgetLocalWorktreeMetadataPruneGate calls across session, SSH-lease, automation, and repo-lifecycle write paths.
  • Listing path (detected-worktree-scan-cache.ts + handlers) — gates expectation capture and lineage pruning on hygieneDue, 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@nwparker
nwparker force-pushed the nwparker/bug-macos-main-100-cpu-fan-heat-persists-on-1.4 branch from f977ce6 to 3590406 Compare September 2, 2026 04:41
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: cbe6ad4c-09f7-4e5c-8459-0c9e35f807f8

📥 Commits

Reviewing files that changed from the base of the PR and between 3590406 and 726872f.

📒 Files selected for processing (2)
  • src/main/local-worktree-metadata-prune-gate.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The 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 72687

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)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR addresses the CPU and heat portion of [#17775] through hygiene gating and reduced filesystem probing. It does not address the issue's other explicit expectations: preventing metadata accumulati… Either implement the remaining [#17775] requirements or link this PR to a scoped child issue that covers only the CPU and heat mitigation. Document the intentional split between this PR, the metadata-store leak work, and the diagnostics iss…
Docstring Coverage ⚠️ Warning Docstring coverage is 29.73% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the primary change: gating worktree metadata hygiene based on evidence instead of every listing.
Description check ✅ Passed 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…
Out of Scope Changes check ✅ Passed The production changes and tests remain related to worktree metadata hygiene, pruning safety, invalidation signals, and scan performance. No unrelated code changes are evident.
Full details: Description check

Explanation

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 check

Explanation

The PR addresses the CPU and heat portion of [#17775] through hygiene gating and reduced filesystem probing. It does not address the issue's other explicit expectations: preventing metadata accumulation, correcting diagnostics CPU reporting, and avoiding manual persisted-data cleanup.

Resolution

Either implement the remaining [#17775] requirements or link this PR to a scoped child issue that covers only the CPU and heat mitigation. Document the intentional split between this PR, the metadata-store leak work, and the diagnostics issue if the scope remains divided.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 39064638-b77d-452e-b84e-a1bc3f974f11

📥 Commits

Reviewing files that changed from the base of the PR and between ededec0 and 3590406.

📒 Files selected for processing (17)
  • src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts
  • src/main/ipc/worktrees/listing/detected-provider-listing.ts
  • src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts
  • src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts
  • src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts
  • src/main/local-worktree-metadata-prune-gate.test.ts
  • src/main/local-worktree-metadata-prune-gate.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.ts
  • src/main/persistence/loading-store/metadata-lineage-operations.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts
  • src/main/persistence/loading-store/session-host-partitions.ts
  • src/main/persistence/loading-store/store-prune-gate-signals.test.ts
  • src/main/persistence/scheduling-automations/automation-definition-operations.ts
  • src/main/persistence/scheduling-automations/automation-run-operations.ts
  • src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts
  • src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts
  • src/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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🚀 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.
@nwparker
nwparker merged commit f9db653 into main Sep 2, 2026
28 checks passed
@nwparker
nwparker deleted the nwparker/bug-macos-main-100-cpu-fan-heat-persists-on-1.4 branch September 2, 2026 05:47
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

[Bug][macOS]: Main ~100% CPU / fan heat persists on 1.4.193 — git.exec + FS storm with 98.7% path-missing worktreeMeta (#15412/#17278 incomplete)

1 participant