Skip to content

Reduce repeated git probes during worktree refresh - #6153

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-git-upstream-probe-memory-crash
Jun 23, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-git-upstream-probe-memory-crash

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reduces repeated git subprocess churn seen in crash report a219317b-4f81-42cb-89dd-872657f4ae21 by:

  • caching successful local worktrees:listDetected raw GitWorktreeInfo[] scans for 5 seconds with in-flight coalescing
  • rebuilding detected worktree payloads from current metadata/settings on cache hits
  • invalidating detected-scan caches before worktree change notifications from both IPC and runtime notifier paths
  • adding a null-only, in-flight coalesced 30-second cache for missing tracked-upstream branch probes keyed by local/WSL/SSH runtime, repo path, and branch

The cache intentionally skips SSH/folder worktree listing for safety; SSH-relevant tracked-upstream behavior remains on the existing provider path and is covered by focused tests.

Crash Evidence / Classification

Crash classification: likely renderer OOM pressure from git polling/subprocess churn with retained trace/error payloads.

Evidence from the downloaded diagnostics:

  • renderer heap rose from about 2222MB / 2995MB to the 3586MB V8 limit before renderer exit code 5
  • 10,369 git.exec spans
  • 9,934 git worktree probes
  • 112 failed git remote get-url upstream probes
  • 141 no-upstream branch failures

This change removes the dominant measured repeated worktree-list probe pattern and the smaller stable-negative tracked-upstream fallback probes.

Design Review

  • Scratch design doc: tmp/git-upstream-probe-memory-crash-design.md (not committed)
  • Initial design review flagged that the original upstream-only mitigation overclaimed because the trace was dominated by git worktree churn.
  • Revised design targeted local detected-worktree scan caching plus tracked-upstream null caching.
  • Follow-up design review was clean enough for implementation.

Implementation / Deviations

  • Initial implementation subagent was blocked by account limits, so the main agent implemented the reviewed design.
  • A later implementation completion subagent reviewed and patched one race: if a detected scan is invalidated while in flight, it no longer runs fresh-scan side effects like lineage pruning.
  • CodeRabbit follow-up fixed invalidator resilience, added why-comments for the non-obvious cache/notification ordering, and moved the detected-scan TTL start to scan completion with a regression test.
  • Added regression tests for cache hits, concurrent coalescing, TTL expiry, slow-scan TTL start, metadata rebuild, create-flow invalidation, in-flight invalidation, host/WSL cache separation, and tracked-upstream TTL/coalescing.

Completeness Verification

  • First completeness pass found the need for a real worktrees:create flow invalidation test and a direct host/WSL cache identity regression.
  • Both gaps were fixed.
  • Final completeness pass: complete; no actionable omissions/blockers.

Code Review

Two independent reviewers in the same round returned clean.

Reviewer A:

  • no issues found
  • reviewed diff against origin/main
  • ran worktree, GitHub client, status-upstream churn, window service tests plus diff check

Reviewer B:

  • no issues found
  • reviewed invalidation paths, cache keying, SSH/WSL handling, concurrency behavior, and accidental instruction text
  • ran relevant focused tests plus diff check

Brennan Test Changes

Verdict: land

Validation matrix covered:

  • worktrees:listDetected local cache: repeated calls, concurrent calls, TTL expiry, metadata rebuild during cache hit, mutation invalidation, stale in-flight scan side effects
  • worktree change notifications: invalidator runs before worktrees:changed
  • GitHub tracked-upstream null cache: repeated/concurrent no-upstream misses, TTL recheck, WSL/local cache separation, existing positive/SSH tracked-upstream behavior
  • no screenshot evidence: non-UI main-process cache/performance fix; no Electron UI surface changed

Accepted gap:

  • Full pnpm run lint was reported by the validation subagent as failing in repo-global localization verification for unrelated TerminalInteractionSection.tsx keys outside this diff. Changed-file lint passed.

Tests

  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees.test.ts -t "detected"
  • pnpm exec vitest run --config config/vitest.config.ts src/main/github/client.test.ts -t "tracked[- ]upstream"
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees.test.ts src/main/window/attach-main-window-services.test.ts src/main/github/client.test.ts src/main/git/status-upstream-probe-churn.test.ts (248 passed after CodeRabbit fixes)
  • pnpm run typecheck:node
  • pnpm exec oxlint src/main/ipc/worktree-change-invalidators.ts src/main/ipc/worktrees.ts src/main/ipc/worktree-remote.ts src/main/ipc/worktrees.test.ts src/main/window/attach-main-window-services.ts src/main/window/attach-main-window-services.test.ts src/main/github/client.ts src/main/github/client.test.ts
  • git diff --check
  • GitHub PR Checks / verify passed

Post-PR Stabilization

Complete.

  • Waited 8 minutes after opening the PR.
  • Fixed CodeRabbit's first round comments: added cache rationale comments and isolated invalidator failures.
  • Waited 8 minutes after pushing that fix.
  • Fixed CodeRabbit's second round comments: documented invalidation-before-notify ordering and started the detected-scan TTL after slow scans complete, with a regression test.
  • Waited 8 minutes after the second fix.
  • Latest CodeRabbit review reported no actionable comments.
  • GitHub verify check passed.

Non-actionable note: CodeRabbit's pre-merge summary still shows a generic docstring-coverage warning; it did not produce actionable review comments after the final commit.

Residual Risk

  • External worktree changes outside Orca can lag up to 5 seconds.
  • Newly configured differently named upstream branches can lag up to 30 seconds after a cached null.
  • This removes the measured subprocess/error-trace churn but does not prove the exact renderer heap retention mechanism.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Two independent caching and invalidation improvements are added. First, getTrackedUpstreamBranch in client.ts gains a 30 s TTL null-result cache and an in-flight promise map so that failed upstream probe lookups are not repeated on every poll or concurrent call, with distinct cache keys for host vs. WSL runtimes. Second, a new worktree-change-invalidators.ts pub/sub registry is introduced; worktrees.ts uses it to register a callback that invalidates a new per-repo TTL scan cache (with in-flight deduplication and generation-based stale-result suppression) for listDetectedGitWorktrees; both worktree-remote.ts and attach-main-window-services.ts are updated to call runWorktreeChangeInvalidators before dispatching renderer IPC notifications. Comprehensive test coverage is added for all new caching, coalescing, TTL, and invalidation behaviors.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: reducing repeated git probes during worktree refresh, which directly corresponds to the caching and de-duplication mechanisms throughout the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description is comprehensive, covering all required template sections including summary, testing verification, AI review report with cross-platform checks, security audit, and detailed notes on implementation and residual risks.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 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: 3

🧹 Nitpick comments (3)
src/main/github/client.ts (1)

2306-2344: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a short comment explaining why this null-only TTL cache exists.

The caching and in-flight dedup here are driven by a non-obvious constraint (the renderer OOM crash from repeated git.exec upstream probes during PR polling), and why only null results are cached. A one-line note prevents a future reader from "simplifying" this away.

📝 Suggested comment
+  // Cache only missing-upstream (null) results: PR polling repeatedly probes branches
+  // without an upstream, and that subprocess churn drove a renderer OOM. Coalesce
+  // concurrent probes and suppress repeats for the TTL window.
   const cacheKey = getTrackedUpstreamBranchCacheKey(
     repoPath,
     branchName,
     connectionId,
     localGitOptions
   )

As per coding guidelines: "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

src/main/ipc/worktree-change-invalidators.ts (1)

12-15: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Isolate invalidator failures before sending notifications.

This runner is called before worktrees:changed is sent; one throwing subscriber would skip later invalidators and suppress the renderer notification. Snapshot the set and catch per callback.

🛡️ Proposed resilience fix
 export function runWorktreeChangeInvalidators(repoId: string): void {
-  for (const invalidator of worktreeChangeInvalidators) {
-    invalidator(repoId)
+  for (const invalidator of [...worktreeChangeInvalidators]) {
+    try {
+      invalidator(repoId)
+    } catch (error) {
+      console.warn('[worktrees] worktree change invalidator failed:', error)
+    }
   }
 }
src/main/ipc/worktrees.ts (1)

391-391: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the 5-second cache tradeoff.

The TTL is a non-obvious balance between subprocess churn and external-worktree-change lag; add a short Why: comment so future edits preserve the intent.

As per coding guidelines, “When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does.”

💬 Proposed comment
+// Why: absorb renderer polling bursts while keeping external worktree-change
+// lag bounded to one short refresh window.
 const DETECTED_WORKTREE_SCAN_CACHE_TTL_MS = 5_000

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 57b0ff82-3715-43b9-bd2a-89388550f14a

📥 Commits

Reviewing files that changed from the base of the PR and between 5311ab3 and 18e56f7.

📒 Files selected for processing (8)
  • src/main/github/client.test.ts
  • src/main/github/client.ts
  • src/main/ipc/worktree-change-invalidators.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/window/attach-main-window-services.test.ts
  • src/main/window/attach-main-window-services.ts

Comment thread src/main/ipc/worktree-remote.ts Resolved
Comment thread src/main/ipc/worktrees.ts Resolved
@brennanb2025
brennanb2025 merged commit 8c4f57e into main Jun 23, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

1 participant