Skip to content

fix(scm): keep git-status pacing across scheduler rebuilds - #11820

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-git-status-pacing-survives-scheduler-rebuild
Jul 31, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-git-status-pacing-survives-scheduler-rebuild

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the git-status refresh storm that makes the app lag badly (typing latency, renderer pegged at 100-160% CPU) when a remote/mobile runtime client is attached while agents are active.

Root cause: #11346 added activeExecutionHostId to the git-status scheduler effect's dependency array in useGitStatusPolling. The rebuild on host change is intentional (generation bump + in-flight abort), but the scheduler's pacing state (lastRunEndedAt, lastRunDurationMs) was closure-local, so every rebuild reset it to -Infinity. With a connected runtime client the resolved host id flaps (local vs runtime:<env> publications overwrite each other in the repoId-keyed store), each flap minted an unthrottled scheduler, and the pre-existing loop (git status rewrites .git/worktrees/<n>/index → 2s base-directory poller → status signal) then ran at the bare 125ms debounce instead of the 3s floor + slow-task backoff (#7983).

Measured on the affected machine (1.4.163-rc.3, live trace spans): git spawn rate jumped from 26-35/min (rc.1, same workload) to a sustained 150-283/min, full 5-command status cycles every 1-3s per busy worktree, renderer main thread ~73% busy.

Fix (two commits):

  • 6eece0b41e: pacing becomes a shareable object (GitStatusRefreshPacing) owned by the hook and keyed to the current worktree, surviving scheduler rebuilds. Host/push-target changes still dispose the scheduler, abort in-flight scans, and bump the generation — they just no longer forget how recently git ran. Worktree switches keep their instant refresh (fresh pacing per worktree).
  • 1414b6a239: hardening — run-id ordering so a stale run from a disposed scheduler that settles late cannot stamp pacing over a newer run's result, and the hook holds a single current-worktree pacing slot instead of an unbounded map.

Empirical A/B validation

Beyond unit tests, the mechanism and fix were validated in a live dev app with real git subprocesses: two instances from pinned commits differing only by this fix (cd2b62ed14 = main/broken vs 6eece0b41e = main+fix), isolated ORCA_DEV_USER_DATA_PATH profiles, a fixture repo with 500ms file churn, Source Control active, then a scheduler-dep flip injected every 1s via the exposed store (same dependency array and rebuild path as the production host-id flap). Git spawns measured from each profile's main.trace.ndjson:

Baseline (churn only) Under 1s dep-flapping
main cd2b62ed14 (broken) 54 execs/min, status every 3s 60 status cycles/min at 1s gaps (floor bypassed, 466 execs)
6eece0b41e (fix) 54 execs/min, status every 3s 20 status cycles/min at exact 3s gaps (floor holds)

Baselines are identical, so the fix changes nothing in normal operation; under the storm input, the broken build runs status at the flap rate while the fix build holds the floor.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test (targeted suites run locally; full suite left to CI)
  • pnpm build (left to CI)
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Targeted runs (all green): git-status-refresh-scheduler.test.ts, useGitStatusPolling.rerender.test.ts, useGitStatusPolling.test.ts.

New regression coverage:

  • scheduler: shared pacing keeps the 3s activity floor across dispose/recreate
  • scheduler: shared pacing keeps slow-scan backoff (30s scan still paces the next run after recreation)
  • hook: execution-host flapping for the same worktree cannot bypass the floor (the storm shape)

Plus the live A/B above as end-to-end validation.

AI Review Report

Reviewed the change against the scheduler's correctness contracts:

  • Rebuild semantics preserved: generation bump, in-flight abort, and trailing-refresh behavior are untouched; only pacing continuity changes. The existing tests "aborts and rejects stale work when the execution host changes" and "triggers an immediate poll when the active worktree changes" pass unchanged.
  • Out-of-order settle handled: a disposed scheduler's still-running scan that settles after a newer run cannot regress pacing (run-id ordering, second commit).
  • Aborted-scan rule preserved: cancelled scans still record duration 0 so hide→reveal catch-up is not stretched.
  • Pacing storage is a single current-worktree slot in a ref — no growth, released on unmount.
  • pacing option is optional; the only factory consumer is useGitStatusPolling, and omitting it reproduces the old per-instance behavior.
    Cross-platform: renderer-only TypeScript using timers and in-memory state — no shortcuts, labels, paths, shell, or Electron platform APIs touched; behavior identical on macOS/Linux/Windows. Applies equally to SSH-hosted and folder workspaces since the pacing key is the worktree id + path already used by the scheduler effect.

Security Audit

No input handling, command execution, path construction, auth, secrets, dependency, or IPC changes. The pacing key is built from in-app worktree id/path values and stays in renderer memory; nothing is persisted or transmitted.

Notes

  • This clamps the amplifier regardless of what causes scheduler rebuilds. Follow-ups deliberately out of scope (separate PRs): (1) ~20 setActiveWorktree call sites clear activeWorkspaceExecutionHostId by omitting the new argument — making it sticky would reduce host-id flapping at the source; (2) detectedWorktreesByRepo is keyed by repoId alone, so local and runtime publications of the same repo overwrite each other.
  • Related but separate: PR-status polling has no pre-spawn default-branch short-circuit and bypasses its negative cache on active/post-push reasons, which multiplied gh spawns during the storm (~50-100/min). Also a candidate for its own PR.
  • Release impact: the regression is only in v1.4.163-rc.3 (landed between rc.1 and rc.3); it is not in stable v1.4.162. Recommend landing this before promoting 1.4.163 to stable.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Git status refresh scheduling now supports shared pacing state with completion timestamps and run durations. Polling stores pacing per worktree ID and path and reuses it when scheduler instances rebuild. Activity-floor and slow-scan backoff calculations use the shared state. Tests cover scheduler recreation, execution-host changes, stale and aborted runs, the three-second activity floor, and 30-second slow-scan backoff.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes preserving git-status pacing across scheduler rebuilds.
Description check ✅ Passed The description covers the summary, testing, AI review, security audit, screenshots, and notes, including CI-deferred checks.
✨ 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8030d607-a272-4ac6-a1a8-c4ba617c39a3

📥 Commits

Reviewing files that changed from the base of the PR and between 7d24dad and 6eece0b.

📒 Files selected for processing (4)
  • src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.test.ts
  • src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.ts
  • src/renderer/src/components/right-sidebar/useGitStatusPolling.rerender.test.ts
  • src/renderer/src/components/right-sidebar/useGitStatusPolling.ts

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a git-status refresh storm (150–283 spawns/min vs a normal 26–35/min) triggered when a remote/mobile runtime client is attached while agents are active. The root cause was that scheduler pacing state was closure-local: every execution-host or push-target change that rebuilt the scheduler reset lastRunEndedAt to -Infinity, granting an immediate unthrottled run and defeating the 3-second activity floor added in #7983.

  • Extracts pacing state into a shareable GitStatusRefreshPacing object (lastRunEndedAt, lastRunDurationMs) owned by the hook and keyed on worktree identity; scheduler rebuilds due to host/push-target flapping reuse the same object while worktree switches mint a fresh one (preserving instant refresh on navigation).
  • Adds a monotone runId / latestFinishedRunId pair to prevent a late-completing disposed run from overwriting newer pacing data in the shared object.
  • New regression tests cover the three critical shapes: floor survival across rebuild, slow-scan backoff survival, and host-flap immunity from the hook level.

Confidence Score: 5/5

Safe to merge. The change is purely additive renderer-side TypeScript — no IPC, shell, or persistence paths touched — and the fix is tightly scoped to pacing continuity across scheduler rebuilds.

The root cause is clearly identified and the fix is minimal: two closure-local variables are promoted to a shared object, with a monotone run-ID guard to prevent late-finishing disposed runs from corrupting the shared state. All existing scheduler contracts (generation bump, in-flight abort, trailing-refresh, aborted-scan zero-duration rule) remain intact and verified by the pre-existing test suite. The three new unit tests and one integration test directly reproduce the storm shape and the two cross-rebuild invariants. No behavioral change occurs outside of the specific host-flapping and push-target-change paths.

Files Needing Attention: No files require special attention. The core logic change in git-status-refresh-scheduler.ts is small and well-covered by tests.

Important Files Changed

Filename Overview
src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.ts Introduces GitStatusRefreshPacing as a shareable value object; replaces two closure-local pacing variables with a reference to it; adds runId ordering to prevent stale finally-callbacks from corrupting shared state. Logic is correct and all edge cases are covered by new tests.
src/renderer/src/components/right-sidebar/useGitStatusPolling.ts Adds statusPacingRef to cache one pacing object per active worktree key; correctly excludes executionHostId and pushTarget from the cache key so host/push flaps reuse pacing while worktree switches start fresh. Integration with the scheduler effect is clean.
src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.test.ts Adds four new unit tests exercising floor preservation, slow-scan backoff continuity, out-of-order late-finishing runs, and repeated rebuild pacing. Tests correctly use fake timers and the deferred helper pattern.
src/renderer/src/components/right-sidebar/useGitStatusPolling.rerender.test.ts Adds the integration regression test for host-ID flapping (the exact storm shape from the report) and extends the worktree-switch test to verify immediate refresh on back-navigation. Both additions directly cover the regressed behaviors.

Sequence Diagram

sequenceDiagram
    participant Hook as useGitStatusPolling
    participant PacingRef as statusPacingRef (worktree-keyed)
    participant S1 as Scheduler (host=local)
    participant S2 as Scheduler (host=runtime:env-2)
    participant S3 as Scheduler (host=local, rebuilt)

    Hook->>PacingRef: create pacing for worktree A
    Hook->>S1: createGitStatusRefreshScheduler(pacing)
    S1->>S1: "resumeSafety() → startRun(runId=1)"
    S1->>PacingRef: "lastRunEndedAt=T, lastRunDurationMs=D"

    Note over Hook: host flaps to runtime:env-2
    Hook->>S1: dispose() [aborts in-flight]
    Hook->>PacingRef: key matches → reuse pacing
    Hook->>S2: createGitStatusRefreshScheduler(pacing)
    S2->>S2: "resumeSafety() → delay = max(0, T+3000−now) ≈ 3s"

    Note over Hook: host flaps back to local
    Hook->>S2: dispose() [aborts in-flight]
    Hook->>PacingRef: key matches → reuse pacing
    Hook->>S3: createGitStatusRefreshScheduler(pacing)
    S3->>S3: resumeSafety() → floor still ~3s

    Note over Hook: worktree switches to B
    Hook->>PacingRef: new key → fresh pacing(-Infinity)
    Hook->>S3: dispose()
    Hook->>Hook: Scheduler for worktree B gets instant refresh
Loading

Reviews (2): Last reviewed commit: "fix(scm): order shared refresh pacing up..." | Re-trigger Greptile

@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.

🧹 Nitpick comments (1)
src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.ts (1)

160-163: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the cancellation comment.

Lines 160-163 explain implementation details across four lines. Keep only the non-obvious policy rationale in one concise line.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Proposed change
-          // Why: cancelled scans never delivered a useful result, so their wall
-          // time must not stretch the next activity/safety gap. Otherwise hide →
-          // reveal after a slow abort waits out the aborted scan's full duration
-          // before the catch-up refresh can start.
+          // Cancelled scans do not extend the next refresh gap.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d8c78a95-5462-47fe-b13d-8b7c651f948a

📥 Commits

Reviewing files that changed from the base of the PR and between 6eece0b and 1414b6a.

📒 Files selected for processing (4)
  • src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.test.ts
  • src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.ts
  • src/renderer/src/components/right-sidebar/useGitStatusPolling.rerender.test.ts
  • src/renderer/src/components/right-sidebar/useGitStatusPolling.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/right-sidebar/useGitStatusPolling.ts
  • src/renderer/src/components/right-sidebar/git-status-refresh-scheduler.test.ts

@brennanb2025

brennanb2025 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Review + Electron QA

A same-model/same-reasoning review found and fixed two PR-scope issues in 1414b6a239:

  • Ordered shared pacing completions now prevent a disposed older scan from erasing a newer scan's slow-task backoff, while still letting an aborted old scan establish the anti-storm floor until its replacement finishes.
  • Pacing is now O(1) and owned by the current worktree, so A→B→A switches keep their immediate refresh instead of inheriting A's old cooldown.

Verification:

  • Reviewer: 52 related tests, full pnpm lint, pnpm typecheck, and max-lines ratchet passed; post-fix re-review returned clean.
  • Independent run: 35 scheduler/hook tests passed.
  • Electron: attached to the mahimahi @ brennanb2025/fix-git-status-pacing-survives-scheduler-rebuild dev instance, selected PR fix(scm): keep git-status pacing across scheduler rebuilds #11820 through the real workspace UI, opened Source Control, drove 12 same-worktree host changes, restored the local host, and typed through the real terminal surface. The rendered app remained responsive with zero console errors.
  • CI: all required checks pass. Node 26 shard 15/16 initially hit the unrelated activity-portal-readiness-loop.react185.test.tsx readiness flake; that exact test passed locally under Node 26, the failed shard passed on rerun, and the final verify gate is green. No out-of-scope code change was made.

The deterministic call-count/timing tests are the primary regression evidence for this nonvisual scheduler fix; the uncropped screenshot is visible app proof after the live interaction.

Electron Source Control and responsive terminal after host-flap QA

Mobile emulator QA was not applicable: this PR changes only the desktop renderer scheduler/hook and tests, with no mobile UI or mobile package changes.

@brennanb2025
brennanb2025 merged commit 751b6b1 into main Jul 31, 2026
81 of 83 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…11820)

* fix(scm): keep git-status pacing across scheduler rebuilds

* fix(scm): order shared refresh pacing updates
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