Skip to content

perf(git): stagger and bound metadata polling - #16175

Closed
nwparker wants to merge 13 commits into
mainfrom
nwparker/perf-git-metadata-scheduler
Closed

nwparker wants to merge 13 commits into
mainfrom
nwparker/perf-git-metadata-scheduler

Conversation

@nwparker

@nwparker nwparker commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​334 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​331
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​842 $\color{#cf222e}{\Huge{\mathbf{−}}}$​488 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​354

Problem / Why

Visible Orca windows currently give every repository its own 2-second Git metadata timer. At fleet scale those timers align into filesystem bursts across repositories and linked worktrees. The macOS native watcher is fast when healthy, but a silently lost native stream also needs bounded reconciliation so external branch, index, upstream, and linked-worktree changes cannot stay stale indefinitely.

Solution

  • Add one host-local staggered Git metadata scheduler with a fixed filesystem-I/O concurrency ceiling of 8.
  • Coalesce overdue ticks instead of accumulating timer/queue work, park hidden targets, and perform one prompt visibility catch-up.
  • Use a monotonic production clock, with an injected clock dependency for deterministic fake-clock coverage.
  • Keep the macOS native watcher as the fast path and add a scheduler-owned 30-second forced reconciliation that reads linked indexes on every reconciliation tick.
  • Track the worktrees root identity, re-arm native watching after same-name root replacement, and generation-fence stale callbacks, interruption hooks, and late subscription resolutions.
  • Preserve Darwin/non-Darwin and local/WSL/SSH/runtime routing, existing detection windows, and 30-second ungated backstops.

ELI5

Instead of every repository ringing its alarm at the same moment, one host clock gives each repository a different turn and allows only eight filesystem checks at once. Hidden windows stop taking turns and catch up once when shown. macOS still uses its instant native watcher, while a quiet 30-second safety check repairs a watcher that silently stopped reporting.

Proof

  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/git-metadata-poll-scheduler.test.ts src/main/ipc/worktree-git-common-watch.test.ts src/main/ipc/worktree-base-directory-poller.test.ts src/main/ipc/folder-repo-git-upgrade.test.ts
    • 4/4 files passed
    • 75/75 tests passed
  • pnpm run typecheck:node
    • passed

User tradeoffs

  • macOS adds one bounded reconciliation I/O pass every 30 seconds per visible Git-common target; native events remain the immediate path.
  • The concurrency ceiling of 8 can queue bursts under sustained overload, trading peak filesystem pressure for bounded, coalesced latency.

Readiness verdict

CLEAN — P0: 0, P1: 0, P2: 0.

Review status

  • Exact reviewed commit: c51edbda012b1ac3c00b67471213a9fff008e932
  • All seven readiness/security reviews: CLEAN, P0/P1/P2 = 0
  • Git 2.25 compatibility: neutral
  • Mobile-facing surface: none
  • Review-loop findings fixed: monotonic-clock liveness, deterministic fake clocks, visibility catch-up coalescing, 30-second forced index recovery, same-name root replacement detection, and stale native subscription generation fencing.

@coderabbitai

coderabbitai Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c6bba097-b732-40d9-bf9a-c7845b19ed65

📥 Commits

Reviewing files that changed from the base of the PR and between 37d9222 and cca2711.

📒 Files selected for processing (1)
  • src/main/ipc/worktree-git-common-watch.test.ts

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


📝 Walkthrough

Walkthrough

The change adds a shared Git metadata polling scheduler with visibility handling, poll coalescing, staggered schedules, and bounded filesystem I/O. Existing repository and worktree pollers now use the scheduler and I/O wrapper. Common-directory snapshots detect worktrees directory replacement. A crash-isolated narrow watcher now handles retries, stale generations, root replacement, and polling fallback. Reconciliation polling performs forced full scans. Tests cover concurrency, timing, visibility, and watcher lifecycle behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, solution, rationale, ELI5 summary, testing, and tradeoffs, but it omits several required template sections. Add the required Linked Issue, Visual Proof or N/A, Testing checklist, AI Disclosure, Review, boundary, Notes, and Checklist sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
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 summarizes the main change: staggered and bounded Git metadata polling.
✨ 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.

@nwparker nwparker closed this Aug 24, 2026
@nwparker nwparker reopened this Aug 24, 2026

@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 (4)
src/main/ipc/git-metadata-poll-scheduler.ts (2)

71-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Separate the poll-concurrency limit from the filesystem-I/O limit.

this.concurrency bounds two unrelated things: concurrent run callbacks in drainPollQueue (Line 240) and concurrent filesystem operations in drainFilesystemQueue (Line 282). The constant is named GIT_METADATA_FILESYSTEM_CONCURRENCY, so the poll limit is invisible to callers and cannot be tuned independently. Introduce a second field with its own constant.

♻️ Proposed split
 export const GIT_METADATA_FILESYSTEM_CONCURRENCY = 8
+export const GIT_METADATA_POLL_CONCURRENCY = 8
@@
   constructor(
     private readonly concurrency = GIT_METADATA_FILESYSTEM_CONCURRENCY,
-    private readonly now: () => number = () => performance.now()
+    private readonly now: () => number = () => performance.now(),
+    private readonly pollConcurrency = GIT_METADATA_POLL_CONCURRENCY
   ) {

180-214: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Consider a due-time heap if target counts grow.

armTimer and collectDuePolls each iterate every registered poll. Staggered phases produce about one timer fire per poll per interval, so the scan cost per interval grows with the square of the target count. With a few hundred targets this is acceptable. If the host must hold thousands of targets, replace the linear scan with a min-heap keyed on dueAt.

src/main/ipc/git-metadata-poll-scheduler.test.ts (1)

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

Add coverage for setIntervalMs and reschedule.

The suite exercises the timer, coalescing, and visibility paths only. setIntervalMs recomputes dueAt only while the poll runs, and folder-repo-git-upgrade.ts depends on that exact branch to switch between the active and idle cadence. reschedule also has a distinct hidden-window branch that parks the poll. Add two cases: an interval change applied from inside a running run, and a reschedule call while the window is hidden.

src/main/ipc/worktree-git-common-polling.ts (1)

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

Expose the directory identity from the signature producer instead of parsing the string.

gitCommonDirectoryIdentity recovers the inode by slicing the signature that gitCommonDirectorySignature builds in src/main/ipc/worktree-git-common-entry-snapshot.ts. The two modules share only an unwritten string format. If that format changes, this parse still returns a value, and root-replacement detection at Line 192 fails without any error. Return the identity from the producer, or add a shared parser next to the producer.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 58014987-6ecb-45f6-abbc-2bc0ce1968ec

📥 Commits

Reviewing files that changed from the base of the PR and between 5bcbaff and d6397d9.

📒 Files selected for processing (11)
  • src/main/ipc/folder-repo-git-upgrade.ts
  • src/main/ipc/git-metadata-poll-scheduler.test.ts
  • src/main/ipc/git-metadata-poll-scheduler.ts
  • src/main/ipc/worktree-base-directory-poller.ts
  • src/main/ipc/worktree-git-common-entry-snapshot.ts
  • src/main/ipc/worktree-git-common-narrow-watch.ts
  • src/main/ipc/worktree-git-common-polling.ts
  • src/main/ipc/worktree-git-common-primary-polling.ts
  • src/main/ipc/worktree-git-common-watch-reconciliation.ts
  • src/main/ipc/worktree-git-common-watch.test.ts
  • src/main/ipc/worktree-git-common-watch.ts

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

Comment on lines +70 to +90
usingPollingFallback = true
const pending = reconciliation
.unsubscribe()
.catch(() => {})
.then(() =>
startGitCommonPolling(target.path, onEvents, pollIntervalMs, visibility, onFullScan, false)
)
.then(async (fallback) => {
if (disposed || subscription) {
await fallback.unsubscribe()
return
}
subscription = fallback
})
const tracked = pending.finally(() => {
if (pollingFallbackPromise === tracked) {
pollingFallbackPromise = null
}
})
pollingFallbackPromise = tracked
return pollingFallbackPromise

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear fallback state when fallback startup fails.

If startGitCommonPolling rejects during setup, usingPollingFallback remains true. The error path can re-arm a native subscription, but canStart and shouldKeep then prevent reconciliation from starting. The forced reconciliation path stays disabled after a transient filesystem error.

Reset usingPollingFallback when fallback setup fails. Add a regression test for a rejected fallback initialization followed by a successful native re-subscribe.

Comment on lines +100 to +105
if (installed && !disposed) {
stopExistencePoll()
await reconciliation.ensureStarted()
// The dir appearing means a first linked worktree was just
// registered; surface it so the repo's worktree list refreshes.
onEvents([{ type: 'create', path: worktreesDir }])

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Retry a failed reconciliation startup.

If reconciliation.ensureStarted() rejects, this call rejects after the native subscription is installed and the existence poll is stopped. Calls from the interval and visibility handler discard that rejection. Later upgrade attempts do not retry because subscription is already set.

Make reconciliation startup retry independently of native subscription installation. Add a test that makes the initial reconciliation snapshot fail once.

Comment on lines +63 to +80
const coarseRootReplacement = events.some(
(event) =>
event.type === 'create' &&
event.path !== worktreesDir &&
dirname(event.path) === worktreesDir
)
if (rootWasReplaced || coarseRootReplacement) {
onRootReplacement()
}
onEvents(
coarseRootReplacement
? events.map((event) =>
event.type === 'update' && event.path === worktreesDir
? { ...event, type: 'create' }
: event
)
: events
)

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 | 🟠 Major | ⚡ Quick win

Do not treat every child creation as a root replacement.

A normal git worktree add creates a path directly under worktreesDir. That makes coarseRootReplacement true. The caller then removes the active native subscription and may rewrite a root update event to create, although the root was not replaced.

Trigger this recovery only from confirmed root replacement evidence, such as root identity change or explicit root delete/create events. Add a test that a normal child creation keeps the native subscription active.

@nwparker

Copy link
Copy Markdown
Contributor Author

Closing: reconciliation and hidden-window parking already landed on main. Staggering on top doesn't buy enough to keep.

@nwparker nwparker closed this Oct 14, 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