Repository navigation
perf(source-control): stop gh rate-limit storms and idle git-status spawn churn - #7595
Conversation
…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]>
📝 WalkthroughWalkthroughChangesThis 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)
✨ Finishing Touches📝 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 (4)
src/main/diagnostics/main-thread-churn-probe.ts (1)
119-160: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo test coverage for the interval/report loop itself.
classifySubprocessCommand/recordSubprocessSpawn/drainSubprocessSpawnStatsare well covered, butstartMainThreadChurnProbe(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()) assertingmaxGapMs/gapsOver50Ms/gapsOver250Msreset correctly per window and that reports only emit everyREPORT_EVERY_MS.src/main/git/status.ts (2)
700-711: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReused constant name is misleading for this cache.
resolvedUpstreamNameCacheholds positive (resolved) entries, but its size cap reusesMAX_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_ENTRIESThen use
MAX_RESOLVED_UPSTREAM_NAME_CACHE_ENTRIESin the trim loop at line 705.
705-711: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicated 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 smalltrimToMaxSize(map, max)helper.src/main/github/rate-limit.ts (1)
164-211: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueForced refinement probe bypasses the new single-flight dedup.
getRateLimit({ force: true })skips theprobeInFlightreuse check entirely (only gated by!options?.force), so if an ordinary (non-forced) probe is already in flight when the breaker trips and callsrefineBreakerFromSnapshot, two concurrentgh api rate_limitsubprocesses will run instead of one — the exact "single-flight" guarantee the comment aboveprobeInFlightclaims. 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
📒 Files selected for processing (21)
.gitignorepackage.jsonsrc/main/diagnostics/main-thread-churn-probe.test.tssrc/main/diagnostics/main-thread-churn-probe.tssrc/main/git/gh-rate-limit-breaker.test.tssrc/main/git/gh-rate-limit-breaker.tssrc/main/git/runner-gh-rate-limit-breaker.test.tssrc/main/git/runner.tssrc/main/git/status-upstream-probe-churn.test.tssrc/main/git/status.tssrc/main/github/client-issue-source.test.tssrc/main/github/client-work-items.test.tssrc/main/github/client.tssrc/main/github/gh-cwd-repo-negative-cache.test.tssrc/main/github/gh-cwd-repo-negative-cache.tssrc/main/github/gh-error-classification.tssrc/main/github/rate-limit.tssrc/main/index.tssrc/renderer/src/store/slices/github.tssrc/shared/git-effective-upstream.tstools/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]>
|
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:
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). |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/updater.check-failure.test.ts (1)
220-269: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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_MSitself (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
📒 Files selected for processing (6)
src/main/diagnostics/main-thread-churn-probe.test.tssrc/main/diagnostics/main-thread-churn-probe.tssrc/main/github/gh-error-classification.tssrc/main/updater.check-failure.test.tssrc/main/updater.tstools/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
| 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 | ||
| } |
There was a problem hiding this comment.
🎯 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.tsRepository: 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.tsRepository: 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.tsRepository: 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.
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]>
…pawn churn (stablyai#7595) Co-authored-by: Orca <[email protected]>
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):
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 exemptgh api rate_limitprobe (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.searchbucket (30 req/min) is now guarded incountWorkItems(MIN_REMAINING_SEARCHpreviously had zero call sites), with per-call spend accounting; counts degrade to 0 instead of converting remaining repos into 403 spawns.countWorkItemsAcrossReposnow shares the same 8-slot concurrency cap the item-fetch paths already used (was an unboundedPromise.allacross all selected repos).git remote addinvalidates immediately; previously two failing gh spawns per repo per refresh.permission_denied("check your token scopes") becausehttp 403matched beforerate limit.Idle status-poll spawn churn (#7576):
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=1probe: event-loop stall gaps + per-command subprocess spawn counters (hooked into all five spawn paths ingit/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):
Screenshots
No visual change.
Testing
pnpm lint— oxlint + all gates pass;lint:switch-exhaustivenessfails onsource-control-manual-review-url.ts:164, which fails identically on the clean base commit (pre-existing, untouched by this PR)pnpm typecheckpnpm 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)status-upstream-probe-churn.test.ts), spawn-classifier unit testsAI 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:
gh api rate_limitis exempt so the refinement probe can never deadlock;rateLimitGuardfails open with no snapshot and past a stale snapshot's reset time.wsl.exe -d <distro> --wrapping,.exesuffixes, and Windows path separators (unit-tested on posix). Breaker matching is stderr-string based, platform-neutral. Bench script guardslog streambehinddarwinand usestaskkillon win32. SSH repos: cwd-fallback is local-only by construction (requiresExplicitRepoguard preserved); serve-mode runs the same runner code and benefits equally.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
getRateLimitsingle-flight prevents a probe stampede from concurrent IPC calls.Notes
AUTO_UPDATE_RETRY_INTERVAL_MS), mtime-gatinggit statusitself, daemon 5s checkpoint serialization (STA-1278 territory).Made with Orca 🐋