Skip to content

perf(main): park worktree metadata pollers while the window is hidden - #9849

Merged
nwparker merged 4 commits into
mainfrom
nwparker/perf-s3-poller-gate
Jul 23, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/perf-s3-poller-gate

Conversation

@nwparker

@nwparker nwparker commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

What

The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate. At ~20 repos on macOS that's ~50 fs.stat syscalls/sec continuously, even while the Orca window is hidden/minimized — pure idle-battery drain. This parks the poll timers while the window is hidden and resumes losslessly when it becomes visible again.

  • New injected WorktreePollerWindowVisibility (mirrors the shipped ssh-port-scanner park/resume pattern). Production adapter follows each ActiveWatch.mainWindow; a null/destroyed window is treated as always visible so headless/orca serve and the macOS window-recreation gap never park.
  • Converted the three poll loops (base poller, Windows/Linux git-common polling, darwin primary-checkout metadata polling) from setInterval to a one-shot setTimeout chain that checks visibility before the stat fan-out: if hidden, it parks (parkedWhileHidden = true, no reschedule) without touching the retained snapshot. onWindowBecameVisible resumes with an immediate tick that diffs a fresh snapshot against the retained pre-hide snapshot (base forces a full scan; git-common forces the linked-index leaf read), so anything changed while hidden surfaces on reveal.
  • The darwin native worktrees/ fsevents watcher, its teardown/re-arm lifecycle, and the directory-existence poll stay always-on (push-based, ~0 idle cost; parking it would risk the [Bug]: app crashes #8732 teardown heap-corruption race).

ELI5

When Orca was hidden, it still poked your disk ~50 times a second per second to notice git changes across all your repos — for windows you couldn't even see, draining battery. Now it stops poking while hidden and, the moment you come back, does one fresh check that catches anything that changed while it was away. The always-on native file watcher (which is basically free) keeps running so nothing is missed on macOS.

Proof of zero regression

  • Lossless resume: parking never resets the retained snapshot; resume forces an immediate full/leaf-read diff against it, so a git worktree add/remove, commit, or HEAD move made while hidden is detected on reveal (covered by tests).
  • Headless/serve exemption: null/destroyed window ⇒ always visible ⇒ polls normally, so a windowless host is never starved (tested).
  • Native watcher untouched: only the poll timers are gated; the darwin native subscription and re-arm path are never parked/resubscribed (tested to keep flowing while hidden).
  • Same-granule detection preserved: git-common resume forces the linked-index read; logs/HEAD is still stat'd directly every tick.
  • Tests: extended worktree-base-directory-poller.test.ts, worktree-git-common-watch.test.ts, worktree-base-directory-watcher.test.ts — 45/45 pass (verified in main worktree, not just the author's). New cases: no scans while hidden, hidden add/HEAD-move detected on reveal, null-window & destroyed-window exemptions, native watcher stays subscribed while hidden. pnpm typecheck:node: clean. oxlint + max-lines ratchet: pass.

Proof of perf improvement

While the window is hidden/minimized this parks ~50 local fs.stat/sec at 20 repos (5 primary-metadata stats per 2s per repo, plus the Windows/Linux readdir + per-linked-worktree structural fan-out). The tests assert the poll body (onFullScan/snapshot) does not run while hidden — directly proving the syscalls stop — and that a reveal triggers exactly one immediate catch-up scan. Pure background/idle battery win; zero cost while visible, and the always-on native fsevents watch means no missed events on macOS.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 22, 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
📝 Walkthrough

Walkthrough

Worktree polling now accepts a window-visibility contract. Base-directory and git-common polling use self-rescheduling timeouts, pause while hidden, and trigger forced scans when visibility resumes. Watcher wiring derives visibility from the active browser window and ignores events from disposed watches. Tests cover hidden-state suppression, resume behavior, headless and destroyed windows, HEAD updates, native stream forwarding, and cleanup.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and omits Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Rewrite the description to match the template and add Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes with the required details.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the core change: parking worktree metadata pollers when the window is hidden.
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.

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.

🧹 Nitpick comments (3)
src/main/ipc/worktree-base-directory-poller.ts (1)

260-308: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Optional: extract the shared visibility-gated tick scaffold. All three loops repeat the same structure (timer=null/disposed/park-on-hidden/ticking guard/reschedule + parkedWhileHidden resume + unsubscribe teardown), diverging only in the per-tick body and the forced-scan flag. A small createVisibilityGatedTicker({ pollIntervalMs, visibility, run }) helper would remove the duplication and keep the concurrency/teardown invariants defined once.

  • src/main/ipc/worktree-base-directory-poller.ts#L260-L308: replace the inline tick/resume/unsubscribe with the shared ticker, passing run(force) => poll(force).
  • src/main/ipc/worktree-git-common-polling.ts#L243-L306: reuse the ticker, passing the git-common snapshot/diff body and forceIndexRead.
  • src/main/ipc/worktree-git-common-watch.ts#L82-L137: reuse the ticker for the snapshot-diff body (no force flag).
src/main/ipc/worktree-base-directory-poller.test.ts (1)

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

Duplicate visibility-harness helper; extract to a shared test util.

createVisibilityHarness() here is structurally identical to the one added in src/main/ipc/worktree-git-common-watch.test.ts (lines 28-56). Extracting a single shared helper (e.g. under a test-utils module) avoids drift between the two copies. While extracting, consider a short comment on the listener === nextListener guard (lines 33-35) explaining that it exists to prevent a stale unsubscribe call from clearing a listener registered by a later subscription.

See consolidated comment for the paired site in worktree-git-common-watch.test.ts.

Source: Coding guidelines

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

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

Duplicate visibility-harness helper; extract to a shared test util.

Same createVisibilityHarness() shape as src/main/ipc/worktree-base-directory-poller.test.ts (lines 18-48). See consolidated comment.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5e603cfe-5299-4486-997c-bc8ce3a09107

📥 Commits

Reviewing files that changed from the base of the PR and between 9097ea0 and 8b8ccfd.

📒 Files selected for processing (7)
  • src/main/ipc/worktree-base-directory-poller.test.ts
  • src/main/ipc/worktree-base-directory-poller.ts
  • src/main/ipc/worktree-base-directory-watcher.test.ts
  • src/main/ipc/worktree-base-directory-watcher.ts
  • src/main/ipc/worktree-git-common-polling.ts
  • src/main/ipc/worktree-git-common-watch.test.ts
  • src/main/ipc/worktree-git-common-watch.ts

@nwparker
nwparker force-pushed the nwparker/perf-s3-poller-gate branch from 8b8ccfd to f784f65 Compare July 22, 2026 03:39
@nwparker

Copy link
Copy Markdown
Contributor Author

Adversarial review pass (independent frontier model) found and I fixed one real regression, and cleared everything else:

Fixed (was a real regression): an ORCA_E2E_HEADLESS launch keeps a live but never-shown BrowserWindow, so isMainWindowVisible stayed false forever with no show/restore signal to resume — the pollers would have parked permanently and silently dropped watcher behavior from the electron-headless suite. The adapter now parks a window only after it has actually been shown at least once; a never-shown (headless/starting-up) window and null/destroyed windows stay always-visible. Added two unit tests (live-never-shown keeps polling; shown-then-hidden parks). 47/47 watcher tests + typecheck:node green.

Pre-existing, out of scope (not introduced here): during the macOS dock-reactivation rebind gap the destroyed window is treated as visible, so a due tick can advance the baseline while handleLocalWatchEvents drops the event. Today's unconditional setInterval polls during that same gap identically, so this PR does not change that behavior; the narrow race predates it and is better addressed separately.

Cleared: no timer-stall interleaving, lossless resume for all three pollers, per-watch visibility re-checked under the global signal, darwin native watcher fully ungated, gap-after-completion cadence + unref preserved, SSH watches bypass these pollers, all disposal paths clear timers + unsubscribe.

@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/ipc/worktree-base-directory-watcher.ts (1)

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

Document the lifecycle rationale for these guards.

The disposed-watch check and active-watch visibility fallback are non-obvious TypeScript lifecycle constraints. Add concise comments explaining why these checks are required.

As per coding guidelines: “For non-obvious TypeScript code, add a concise comment explaining why the constraint exists, not how the code works.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0c596968-a6b5-4e31-8e6b-b1a7036055e1

📥 Commits

Reviewing files that changed from the base of the PR and between 8b8ccfd and f784f65.

📒 Files selected for processing (7)
  • src/main/ipc/worktree-base-directory-poller.test.ts
  • src/main/ipc/worktree-base-directory-poller.ts
  • src/main/ipc/worktree-base-directory-watcher.test.ts
  • src/main/ipc/worktree-base-directory-watcher.ts
  • src/main/ipc/worktree-git-common-polling.ts
  • src/main/ipc/worktree-git-common-watch.test.ts
  • src/main/ipc/worktree-git-common-watch.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/main/ipc/worktree-base-directory-watcher.test.ts
  • src/main/ipc/worktree-git-common-polling.ts
  • src/main/ipc/worktree-base-directory-poller.test.ts
  • src/main/ipc/worktree-git-common-watch.ts
  • src/main/ipc/worktree-git-common-watch.test.ts
  • src/main/ipc/worktree-base-directory-poller.ts

Comment on lines +198 to +201
if (currentWatch && !currentWatch.disposed) {
handleLocalWatchEvents(currentWatch, null, events)
}
handleLocalWatchEvents(currentWatch, null, 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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n -C 10 'activeWatches\.(set|delete|get)|subscribeTarget|unsubscribe|disposed' \
  src/main/ipc/worktree-base-directory-watcher.ts
rg -n -C 12 'unsubscribe|callback|timer|disposed' \
  src/main/ipc/worktree-base-directory-poller.ts

Repository: stablyai/orca

Length of output: 14033


🏁 Script executed:

#!/bin/bash
sed -n '218,310p' src/main/ipc/worktree-base-directory-watcher.ts
sed -n '1,120p' src/main/ipc/worktree-base-directory-watcher.ts

Repository: stablyai/orca

Length of output: 7476


🏁 Script executed:

sed -n '211,330p' src/main/ipc/worktree-base-directory-poller.ts

Repository: stablyai/orca

Length of output: 3701


Bind the callback to the originating watch. target.key can be reused, so a stale poll result can be routed to a newly created watch with the same key; capture the watch reference or a per-subscription token before dispatching.

@nwparker
nwparker force-pushed the nwparker/perf-s3-poller-gate branch 2 times, most recently from 4dedb21 to 16455fd Compare July 22, 2026 23:27

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

♻️ Duplicate comments (1)
src/main/ipc/worktree-base-directory-watcher.ts (1)

197-204: 🎯 Functional Correctness | 🟡 Minor

Bind poller callbacks to the originating watch, not only its key.

The callback now checks whether activeWatches.get(target.key) exists and is not disposed, but target.key can be reused while the previous subscription is still unwinding. A stale event from the old poller can therefore be delivered to the replacement watch. Capture the originating watch or a per-subscription token and require identity matching before calling handleLocalWatchEvents; apply the same binding to the visibility callback.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3e742e51-6464-44a8-89b3-ff42b9177e76

📥 Commits

Reviewing files that changed from the base of the PR and between 97922aae596583f85a1634454a8d4f08e8880d99 and 4dedb210c130fe90884c9a1d09d63bc0fb08a2d9.

📒 Files selected for processing (1)
  • src/main/ipc/worktree-base-directory-watcher.ts

nwparker and others added 4 commits July 22, 2026 17:49
The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate
(~50 fs.stat/sec at 20 repos on macOS while the window is hidden). Park the poll
timers while the window is hidden and resume losslessly (immediate fresh-vs-retained
snapshot diff) on reveal, via an injected WorktreePollerWindowVisibility mirroring
the ssh-port-scanner pattern.

Only the poll timers are gated; the darwin native worktrees/ fsevents watch and its
teardown/re-arm lifecycle stay always-on (push-based, ~0 idle cost; #8732 race).

A window is parked only once it has actually been shown and is now hidden: a live
never-shown window (ORCA_E2E_HEADLESS keeps one) and null/destroyed windows stay
always-visible, so a windowless/headless host never permanently parks the poller.

Co-authored-by: Orca <[email protected]>
…out change

Parking the pollers moved them from setInterval to a one-shot setTimeout chain, but
scheduling the next tick a full pollIntervalMs AFTER each scan completed turned the
cadence into gap-after-completion — every visible refresh landed ~one scan-duration
late per tick. Measure from tick start and schedule max(0, interval - elapsed) so the
cadence is start-to-start like the original interval, while keeping the one-shot chain
that park/resume needs.

Co-authored-by: Orca <[email protected]>
Date.now() is not monotonic: a backward wall-clock jump (NTP correction) during a scan
makes (now - startedAt) negative, so the start-to-start delay pollIntervalMs - elapsed
would exceed one interval by the adjustment — suppressing visible metadata refreshes for
minutes/hours, unlike the former setInterval. Cap the computed delay at pollIntervalMs
(upper) as well as 0 (lower) in all three pollers.

Co-authored-by: Orca <[email protected]>
…ines

The visibility-parking change pushed worktree-base-directory-watcher.ts to 303 code
lines (limit 300). clearTimeout tolerates null/undefined, so the two truthy guards
around it are redundant — remove them (coalescing null→undefined for the type). No
behavior change; back under the limit without an eslint-disable.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-s3-poller-gate branch from 16455fd to a8f397a Compare July 23, 2026 00:49
@nwparker
nwparker merged commit 63bd3ff into main Jul 23, 2026
1 check failed
@nwparker
nwparker deleted the nwparker/perf-s3-poller-gate branch July 23, 2026 03:38
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#9849)

* perf(main): park worktree pollers while hidden

The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate
(~50 fs.stat/sec at 20 repos on macOS while the window is hidden). Park the poll
timers while the window is hidden and resume losslessly (immediate fresh-vs-retained
snapshot diff) on reveal, via an injected WorktreePollerWindowVisibility mirroring
the ssh-port-scanner pattern.

Only the poll timers are gated; the darwin native worktrees/ fsevents watch and its
teardown/re-arm lifecycle stay always-on (push-based, ~0 idle cost; stablyai#8732 race).

A window is parked only once it has actually been shown and is now hidden: a live
never-shown window (ORCA_E2E_HEADLESS keeps one) and null/destroyed windows stay
always-visible, so a windowless/headless host never permanently parks the poller.

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

* fix(main): keep start-to-start poller cadence after the interval→timeout change

Parking the pollers moved them from setInterval to a one-shot setTimeout chain, but
scheduling the next tick a full pollIntervalMs AFTER each scan completed turned the
cadence into gap-after-completion — every visible refresh landed ~one scan-duration
late per tick. Measure from tick start and schedule max(0, interval - elapsed) so the
cadence is start-to-start like the original interval, while keeping the one-shot chain
that park/resume needs.

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

* fix(main): clamp poller reschedule delay to [0, pollIntervalMs]

Date.now() is not monotonic: a backward wall-clock jump (NTP correction) during a scan
makes (now - startedAt) negative, so the start-to-start delay pollIntervalMs - elapsed
would exceed one interval by the adjustment — suppressing visible metadata refreshes for
minutes/hours, unlike the former setInterval. Cap the computed delay at pollIntervalMs
(upper) as well as 0 (lower) in all three pollers.

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

* refactor(main): drop redundant notifyTimer guards to stay under max-lines

The visibility-parking change pushed worktree-base-directory-watcher.ts to 303 code
lines (limit 300). clearTimeout tolerates null/undefined, so the two truthy guards
around it are redundant — remove them (coalescing null→undefined for the type). No
behavior change; back under the limit without an eslint-disable.

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

---------

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