Skip to content

perf(source-control): stop gh rate-limit storms and idle git-status spawn churn - #7595

Merged
Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/macos-repeated-main-thread-performance-diagnosti
Jul 6, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/macos-repeated-main-thread-performance-diagnosti

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes two field-reported main-process freeze/jank mechanisms — the macOS main-thread Performance Diagnostics report (#7576) and a Discord report from a 90-repo remote-server user whose GitHub account got rate-limited by the Tasks page — and adds a benchmark + probe so these regressions are measurable going forward.

gh rate-limit storm (Discord, 90 repos):

  • New runner-level circuit breaker (src/main/git/gh-rate-limit-breaker.ts): after one primary 403, same-bucket gh calls fail fast without spawning until GitHub's reset time. The exempt gh api rate_limit probe (single-flight) refines the fallback block into the real reset. One spawn instead of ~90 per refresh, and the user's quota stops being burned.
  • The search bucket (30 req/min) is now guarded in countWorkItems (MIN_REMAINING_SEARCH previously had zero call sites), with per-call spend accounting; counts degrade to 0 instead of converting remaining repos into 403 spawns.
  • Renderer countWorkItemsAcrossRepos now shares the same 8-slot concurrency cap the item-fetch paths already used (was an unbounded Promise.all across all selected repos).
  • Repos where gh's cwd resolution deterministically fails ("no git remotes found") are negative-cached keyed by the repo's git-config signature, so git remote add invalidates immediately; previously two failing gh spawns per repo per refresh.
  • Bug fix: primary rate-limit 403s were classified as permission_denied ("check your token scopes") because http 403 matched before rate limit.

Idle status-poll spawn churn (#7576):

  • The effective-upstream probe (the spawn-heaviest status path, hit every 3s for pushed-but-untracked branches — the common Orca worktree shape) now caches the resolved upstream name for 60s and revalidates with a single rev-list. Ahead/behind stays exact every tick (it is a pure function of the rev-list endpoints); ref deletion, Orca-driven mutations, branch changes, and TTL all force a full re-resolve.

Measurement harness (new):

  • ORCA_MAIN_THREAD_DIAGNOSTICS=1 probe: event-loop stall gaps + per-command subprocess spawn counters (hooked into all five spawn paths in git/runner.ts), reported as parseable stderr lines.
  • pnpm bench:main-thread-jank: launches the built app against a fixture reproducing the reported workload (active worktree, Source Control sidebar open, pushed-but-untracked branch), aggregates probe reports, and on macOS tails the unified log for the exact Performance Diagnostics warnings from macOS: repeated main-thread Performance Diagnostics while Orca.app is running #7576.

Measured (same fixture, 60s idle window, two runs each):

Metric Before After
Main-process spawns/min 131 61 (−53%)
Upstream resolution chain (symbolic-ref / config / rev-parse per min) 19 / 19 / 44 1 / 1 / 8
Worst event-loop stall 212ms 143–199ms

Screenshots

No visual change.

Testing

  • pnpm lint — oxlint + all gates pass; lint:switch-exhaustiveness fails on source-control-manual-review-url.ts:164, which fails identically on the clean base commit (pre-existing, untouched by this PR)
  • pnpm typecheck
  • pnpm test — 24,802 passed; the 18 failures (pr-comments-list-selection, pr-comment-presentation, LinearAgentSkillSetupPrompt.reminder-toast, SidebarToolbar) reproduce identically on the clean base commit d8ed41f (verified in a detached worktree)
  • pnpm build (build:electron-vite, used for the benchmark runs)
  • New tests: breaker unit + runner integration (blocked-bucket short-circuit, exempt probe, secondary-limit exclusion), search-guard short-circuit, negative-cache signature invalidation, cross-repo/runtime key separation, single-rev-list revalidation + TTL re-resolve + rev-list-failure fallback (extends status-upstream-probe-churn.test.ts), spawn-classifier unit tests

AI Review Report

Investigated with code-mapping agents before writing changes; verified every load-bearing claim in source (poll cadences, guard call sites, fan-out concurrency, cache invalidation hooks). Main risks checked:

  • Rate-limit semantics: breaker only trips on primary 403s (secondary limits keep Retry-After retry handling); gh api rate_limit is exempt so the refinement probe can never deadlock; rateLimitGuard fails open with no snapshot and past a stale snapshot's reset time.
  • Behavior preservation: first failures still classify/propagate identically (renderer still counts failed repos; partial-failure banners unchanged) — only repeat work is eliminated. Existing negative-cache/coalescing/churn suites pass unchanged.
  • Staleness bounds: upstream-name cache ≤60s and cleared on mutation/branch change/rev-list failure; no-remote cache invalidates on git-config signature change (TTL-only fallback for WSL/SSH where no local signature exists).
  • Cross-platform: no shortcuts/labels/paths touched. Spawn classifier handles wsl.exe -d <distro> -- wrapping, .exe suffixes, and Windows path separators (unit-tested on posix). Breaker matching is stderr-string based, platform-neutral. Bench script guards log stream behind darwin and uses taskkill on win32. SSH repos: cwd-fallback is local-only by construction (requiresExplicitRepo guard preserved); serve-mode runs the same runner code and benefits equally.
  • Import cycles: breaker lives in git/ with zero imports so both the runner and the github rate-limit prober can use it.

Known trade-offs (accepted, documented): breaker is per-process, not per-account/host (a multi-account setup exhausting one account pauses gh for others until reset; refinement self-corrects toward unblocking); during a block window gh's own 120s disk cache can no longer serve reads; count totals on huge repo selections complete progressively under the slot cap.

Security Audit

  • All subprocess invocations use arg arrays (no shell interpolation); the new code adds no user-controlled strings to argv.
  • The negative cache stores gh error-message strings in memory only, keyed by repo path + runtime — no secrets, no persistence.
  • Breaker state is in-memory per process; the synthetic blocked error contains only bucket name and countdown.
  • No changes to IPC surface, auth, token handling, or dependency set. getRateLimit single-flight prevents a probe stampede from concurrent IPC calls.

Notes

  • Remaining known main-thread levers, out of scope here: hourly updater-retry code-signature checks (AUTO_UPDATE_RETRY_INTERVAL_MS), mtime-gating git status itself, daemon 5s checkpoint serialization (STA-1278 territory).
  • Cheap follow-up that closes the main staleness window: clear the upstream-name cache on the existing terminal-command-finished push signal.
  • Refs macOS: repeated main-thread Performance Diagnostics while Orca.app is running #7576; Discord thread 1523308935795441806 (user "prefix", 90-repo remote server).

Made with Orca 🐋

…pawn churn

Fixes two field-reported main-process freeze mechanisms (issue #7576 +
Discord report from a 90-repo remote-server user):

- gh rate-limit circuit breaker at the runner level: one primary 403
  blocks further same-bucket gh spawns until GitHub's reset time
  (refined by the exempt rate_limit probe, single-flight). The search
  bucket (30/min) is now guarded in countWorkItems, the renderer count
  fan-out shares the 8-slot cap, and rate-limit 403s classify as
  rate_limited instead of permission_denied.
- Negative cache for gh cwd repo-resolution failures ("no git remotes
  found"), keyed by git-config signature so `git remote add` invalidates
  immediately — remote-less repos stop re-spawning gh every refresh.
- Effective-upstream resolved-name cache (60s TTL) in getStatus: the
  3s status poll revalidates with a single rev-list instead of re-running
  the 4-5-spawn resolution chain; falls back to a full re-resolve on
  rev-list failure, TTL, mutation, or branch change.
- New ORCA_MAIN_THREAD_DIAGNOSTICS probe (event-loop stall gaps +
  per-command spawn counters in git/runner) and a main-thread jank
  benchmark (pnpm bench:main-thread-jank) that reproduces the reported
  workload and tails macOS Performance Diagnostics warnings.

Measured on the bench fixture (pushed-but-untracked branch, Source
Control sidebar open, 60s idle): 131 -> 61 main-process spawns/min,
worst event-loop stall 212ms -> 143-199ms.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

This PR adds main-thread churn diagnostics with subprocess spawn tracking, startup/update markers, and a benchmark harness. It introduces a gh primary-rate-limit breaker wired into runner and rate-limit handling, plus a negative cache for gh cwd→repo resolution failures in the GitHub client. It also adds resolved-upstream-name revalidation in git status probing and throttles renderer cross-repo work-item counts.

Sequence Diagram(s)

Diagrams are included in the hidden review stack artifact for the churn probe, startup/update wiring, gh rate-limit breaker, gh cwd-resolution negative cache, and upstream revalidation flow.

Related Issues: Unable to determine from provided information.

Related PRs: Unable to determine from provided information.

Suggested labels: diagnostics, performance, github, git

Suggested reviewers: Unable to determine from provided information.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main source-control performance changes and matches the PR scope.
Description check ✅ Passed The description includes all required sections and covers the summary, testing, review, security, notes, and screenshots requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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: 2

🧹 Nitpick comments (4)
src/main/diagnostics/main-thread-churn-probe.ts (1)

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

No test coverage for the interval/report loop itself.

classifySubprocessCommand/recordSubprocessSpawn/drainSubprocessSpawnStats are well covered, but startMainThreadChurnProbe (the setInterval-driven gap detection and 5s report emission) has no tests. Given this is the core measurement loop the PR's benchmark results depend on, consider adding a fake-timers test (vi.useFakeTimers()) asserting maxGapMs/gapsOver50Ms/gapsOver250Ms reset correctly per window and that reports only emit every REPORT_EVERY_MS.

src/main/git/status.ts (2)

700-711: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reused constant name is misleading for this cache.

resolvedUpstreamNameCache holds positive (resolved) entries, but its size cap reuses MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES, which is named/intended for the negative-result cache. Tuning one budget later will silently affect the other.

♻️ Suggested fix
-const resolvedUpstreamNameCache = new Map<string, ResolvedUpstreamNameCacheEntry>()
+const resolvedUpstreamNameCache = new Map<string, ResolvedUpstreamNameCacheEntry>()
+const MAX_RESOLVED_UPSTREAM_NAME_CACHE_ENTRIES = MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES

Then use MAX_RESOLVED_UPSTREAM_NAME_CACHE_ENTRIES in the trim loop at line 705.


705-711: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicated trim-to-max-size loop.

The same eviction pattern (delete oldest Map key while over max size) now exists both here and in rememberEffectiveUpstreamStatus (lines 614-621). Consider extracting a small trimToMaxSize(map, max) helper.

src/main/github/rate-limit.ts (1)

164-211: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Forced refinement probe bypasses the new single-flight dedup.

getRateLimit({ force: true }) skips the probeInFlight reuse check entirely (only gated by !options?.force), so if an ordinary (non-forced) probe is already in flight when the breaker trips and calls refineBreakerFromSnapshot, two concurrent gh api rate_limit subprocesses will run instead of one — the exact "single-flight" guarantee the comment above probeInFlight claims. It's a narrow window and still bounded (2 spawns, not 90), but worth a note given the PR's whole premise is minimizing spawn storms.

This may be an acceptable, intentional tradeoff (the ambient in-flight probe could be stale relative to the just-tripped limit, so reusing it wouldn't be correct) — flagging for awareness rather than as a blocking issue.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1d2e25d0-0fc8-4101-8d46-f38622c412ab

📥 Commits

Reviewing files that changed from the base of the PR and between 47feae3 and b563d25.

📒 Files selected for processing (21)
  • .gitignore
  • package.json
  • src/main/diagnostics/main-thread-churn-probe.test.ts
  • src/main/diagnostics/main-thread-churn-probe.ts
  • src/main/git/gh-rate-limit-breaker.test.ts
  • src/main/git/gh-rate-limit-breaker.ts
  • src/main/git/runner-gh-rate-limit-breaker.test.ts
  • src/main/git/runner.ts
  • src/main/git/status-upstream-probe-churn.test.ts
  • src/main/git/status.ts
  • src/main/github/client-issue-source.test.ts
  • src/main/github/client-work-items.test.ts
  • src/main/github/client.ts
  • src/main/github/gh-cwd-repo-negative-cache.test.ts
  • src/main/github/gh-cwd-repo-negative-cache.ts
  • src/main/github/gh-error-classification.ts
  • src/main/github/rate-limit.ts
  • src/main/index.ts
  • src/renderer/src/store/slices/github.ts
  • src/shared/git-effective-upstream.ts
  • tools/benchmarks/main-thread-jank-bench.mjs

…ranch; add updater retry backoff

CodeRabbit findings: the spawn classifier consumed git-style flag values for
any binary (rg -C 3 misclassified) — subcommand buckets are now limited to
git/gh/glab; the reordered rate-limit check left the original branch as dead
code — removed.

Remaining issue #7576 lever: consecutive failing background update-check
retries backed off 1h -> 2h -> 4h -> 6h cap (reset on any completed check)
instead of re-running the main-thread-heavy check at an exact hourly cadence
forever, and each check attempt now emits an ORCA_MAIN_THREAD_DIAGNOSTICS
marker line so field captures can attribute (or rule out) the updater as the
source of the hourly macOS Performance Diagnostics warnings.

Co-authored-by: Orca <[email protected]>
@Jinwoo-H

Jinwoo-H commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Update (2166d1f): both CodeRabbit findings fixed (classifier subcommand buckets limited to git/gh/glab; dead duplicate rate-limit branch removed), plus the remaining #7576 lever we could address without the reporter's machine:

  • Update-check retry backoff — a persistently-failing feed used to re-arm checkForUpdates at an exact 1h cadence forever, which matches the issue's exactly-hourly warning timestamps (22:36:52 → 23:36:52). Consecutive failing background retries now back off 1h → 2h → 4h → 6h (cap), resetting on any completed check. The first retry keeps the fast 1h cadence so release-publishing windows are unaffected. Covered by a fake-timer test alongside the existing retry-cadence test.
  • Field attribution — every update-check attempt now emits a timestamped ORCA_MAIN_THREAD_DIAGNOSTICS marker line, so a capture from an affected machine can definitively confirm or rule out the updater as the source of the remaining Performance Diagnostics warnings (we could not reproduce them on macOS 26.2 locally; the reporter is on 26.5.2).

With this, the PR covers every #7576 signal we can act on without the reporter's environment: the posix_spawn churn (fixed, −53% measured), the hourly cadence (frequency now bounded + attributable), and diagnostics to verify in the field. Out of scope and tracked separately: daemon-side 5s checkpoint serialization (STA-1278 workstream).

@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

🧹 Nitpick comments (1)
src/main/updater.check-failure.test.ts (1)

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

Add a case exercising the 6h cap.

The test covers 1h→2h→4h and the post-success reset, but never exercises MAX_AUTO_UPDATE_RETRY_INTERVAL_MS itself (the 4th consecutive failure, which would otherwise schedule at 8h and should be clamped to 6h).

✅ Suggested additional assertion (append before the reset block)
     // Third retry doubles to 4h.
     await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS)
     expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3)
     await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS)
     expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(4)
+
+    // Fourth retry would be 8h uncapped; MAX_AUTO_UPDATE_RETRY_INTERVAL_MS clamps it to 6h.
+    makeBenignCheckFailure('Unable to find latest version on GitHub')
+    await vi.advanceTimersByTimeAsync(6 * ONE_HOUR_MS)
+    expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(5)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0927eb33-0f19-4930-be22-f178e7c787fc

📥 Commits

Reviewing files that changed from the base of the PR and between b563d25 and 2166d1f.

📒 Files selected for processing (6)
  • src/main/diagnostics/main-thread-churn-probe.test.ts
  • src/main/diagnostics/main-thread-churn-probe.ts
  • src/main/github/gh-error-classification.ts
  • src/main/updater.check-failure.test.ts
  • src/main/updater.ts
  • tools/benchmarks/main-thread-jank-bench.mjs
💤 Files with no reviewable changes (1)
  • src/main/github/gh-error-classification.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/diagnostics/main-thread-churn-probe.test.ts
  • tools/benchmarks/main-thread-jank-bench.mjs

Comment thread src/main/updater.ts
Comment on lines 705 to +716
function scheduleAutomaticUpdateCheck(delayMs: number): void {
let effectiveDelayMs = delayMs
// All retry-cadence callers (here and updater-events) pass exactly this
// constant, so keying the backoff on it keeps one choke point instead of
// threading a flag through seven schedule sites.
if (delayMs === AUTO_UPDATE_RETRY_INTERVAL_MS) {
effectiveDelayMs = Math.min(
AUTO_UPDATE_RETRY_INTERVAL_MS * 2 ** consecutiveAutomaticRetrySchedules,
MAX_AUTO_UPDATE_RETRY_INTERVAL_MS
)
consecutiveAutomaticRetrySchedules += 1
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm AUTO_UPDATE_CHECK_INTERVAL_MS and AUTO_UPDATE_RETRY_INTERVAL_MS values/definitions,
# and enumerate all call sites of scheduleAutomaticUpdateCheck.
rg -n 'AUTO_UPDATE_CHECK_INTERVAL_MS\s*=' src/main/updater.ts src/main/updater-events.ts
rg -n 'AUTO_UPDATE_RETRY_INTERVAL_MS\s*=' src/main/updater.ts src/main/updater-events.ts
rg -n 'scheduleAutomaticUpdateCheck\(' -A1 src/main/updater.ts src/main/updater-events.ts

Repository: stablyai/orca

Length of output: 2616


🏁 Script executed:

#!/bin/bash
sed -n '1340,1378p' src/main/updater.ts
sed -n '145,240p' src/main/updater-events.ts

Repository: stablyai/orca

Length of output: 5933


🏁 Script executed:

#!/bin/bash
sed -n '705,740p' src/main/updater.ts
rg -n 'consecutiveAutomaticRetrySchedules|reset.*AutomaticRetry|recordCompletedUpdateCheck|clear.*Retry' src/main/updater.ts src/main/updater-events.ts

Repository: stablyai/orca

Length of output: 2382


Don’t infer retry state from delayMs alone. The startup catch-up path can also schedule a 1h delay (AUTO_UPDATE_CHECK_INTERVAL_MS - msSinceLastCheck), which will be treated as a retry and incorrectly bump consecutiveAutomaticRetrySchedules. Pass an explicit retry flag instead.

@Jinwoo-H
Jinwoo-H merged commit 4177234 into main Jul 6, 2026
3 checks passed
@Jinwoo-H
Jinwoo-H deleted the Jinwoo-H/macos-repeated-main-thread-performance-diagnosti branch July 6, 2026 22:12
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
Brings in 9 commits: deferred remote catalogs at startup (#7087),
owner-aware pane title decision gating the Gemini GPU fallback (#7458),
incremental transcript parsing for JSONL agents (#7593), gh rate-limit and
git-status spawn-churn fixes (#7595), WSL Codex session bridging (#7477),
jump-palette subscription gating (#7558), and the IDE font dropdown fix.

Conflict resolutions (our structure, main's semantics):
- pty-connection.ts onTitleChange: kept this branch's third parameter and
  stale-derived-title guard (staleWorkingTitleClear must never feed
  completion tracking), grafted main's resolvePaneTitleDecision so the
  display label, GPU policy, and observeTitle all ride the owner-aware
  decision (#7428/#7447).
- App.tsx startup: kept this branch's publishTerminalViewAttributesAtAppStart
  (hidden-at-launch OSC 10/11 replies) ahead of main's restructured
  local-first startup; dropped this branch's early ui.get() overlap — main's
  #7087 now awaits ui.get at effectively the same point, making it redundant.

Gates: typecheck clean; 4298 tests across src/main/ipc, src/main/daemon,
terminal-pane, pane-manager. The delivery path (ipc/pty.ts, dispatcher,
scheduler, snapshots) had no conflicts and no incoming changes.

Co-authored-by: Orca <[email protected]>
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