Repository navigation
Cut fseventsd load: fix macOS exclusion cap, drop wide always-on FSEvents streams - #7068
Conversation
…ents streams - @parcel/watcher maps plain-path ignores to FSEventStreamSetExclusionPaths, but macOS caps exclusions at 8 per stream and fails closed. Orca passed 9, silently disabling ALL daemon-side exclusions: fseventsd delivered every node_modules/.git event to each per-worktree explorer stream (measured 16x client CPU). Cap plain paths at 8 (extras demoted to userspace globs) via a shared filesystem-watcher-ignore module, also unifying the runtime file-watcher host list so identical roots share one native stream. - worktree-base-directory-watcher subscribed recursive FSEvents streams over every repo's ENTIRE workspace root (all worktrees) and whole common .git (objects included) with glob-only ignores (zero daemon-side exclusion), just to observe a few shallow paths. Replace with a 2s readdir/stat poller (zero fseventsd clients, measured 70x less delivery CPU); SSH targets keep provider.watch unchanged. - serve-sim state watcher held an app-lifetime fs.watch on $TMPDIR (the noisiest dir on the system); its existing 250ms existence poll makes the parent watch redundant, so drop it. Co-authored-by: Orca <[email protected]>
|
Ready to review this PR? Stage has broken it down into 4 individual chapters for you: Chapters generated by Stage for commit 3beffc6 on Jul 2, 2026 4:37am UTC. |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR replaces several 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
🧹 Nitpick comments (4)
src/main/emulator/serve-sim-state-watcher.ts (1)
156-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim the
Whycomment to guideline length.Logic is correct (guard/poll substitution for the removed
parentWatcher), but the added comment spans 4 lines where the guideline asks for one or two.✏️ Suggested tightening
- // Why: $TMPDIR/serve-sim/ may not exist until the first terminal `serve-sim --detach`. - // Poll for it instead of fs.watch on the parent tmpdir: watching $TMPDIR - // registers a permanent FSEvents client on the system's highest-churn - // directory, while an existence poll costs the daemon nothing. + // Why: poll for stateDir existence instead of fs.watch on $TMPDIR, which + // would register a permanent FSEvents client on the highest-churn dir.As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason."
Source: Coding guidelines
src/main/ipc/filesystem-watcher-ignore.ts (1)
5-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a readonly type for the shared constant.
WATCHER_IGNORE_DIRSis exported and consumed by multiple modules (filesystem-watcher.ts,file-watcher-host.ts). Typing it asreadonly string[](oras const) would prevent accidental mutation by a consumer from affecting every watcher.♻️ Proposed tweak
-export const WATCHER_IGNORE_DIRS: string[] = [ +export const WATCHER_IGNORE_DIRS: readonly string[] = [src/main/ipc/worktree-base-directory-poller.ts (2)
82-84: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueSequential per-entry
statcalls could be parallelized.Each candidate/entry is stat'd one at a time in a
forloop. For repos with many worktrees this adds up, though the 2s poll interval limits impact today.♻️ Proposed parallelization
- for (const dir of candidates) { - markers.set(dir, await hasGitMarker(dir)) - } + await Promise.all( + candidates.map(async (dir) => { + markers.set(dir, await hasGitMarker(dir)) + }) + )Also applies to: 116-123
176-198: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPersistent snapshot failures are silently swallowed forever.
The
.catch(() => {...})treats every snapshot failure as transient and never logs. If a target becomes permanently unreadable (permissions revoked, deleted mount, etc.), the poller will retry silently every 2s indefinitely with no diagnostic trail — unlike the previous@parcel/watchererror callback, which logged and triggered explicit cleanup. Consider logging (rate-limited) on repeated consecutive failures so real problems are debuggable.🔍 Illustrative fix
+ let consecutiveFailures = 0 const timer = setInterval(() => { if (disposed || ticking) { return } ticking = true void takeSnapshot(target, getRepos) .then((next) => { if (disposed) { return } const events = diffSnapshots(snapshot, next) snapshot = next + consecutiveFailures = 0 if (events.length > 0) { onEvents(events) } }) - .catch(() => { - // Transient fs error: keep the previous snapshot and retry next tick. - }) + .catch(() => { + consecutiveFailures++ + if (consecutiveFailures === 5) { + console.error(`[worktree-base-directory-poller] repeated snapshot failures for ${target.key}`) + } + }) .finally(() => { ticking = false }) }, pollIntervalMs)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 36ae6b93-c70d-4930-ad6e-763736150487
📒 Files selected for processing (10)
src/main/emulator/serve-sim-state-watcher.test.tssrc/main/emulator/serve-sim-state-watcher.tssrc/main/ipc/filesystem-watcher-ignore.test.tssrc/main/ipc/filesystem-watcher-ignore.tssrc/main/ipc/filesystem-watcher.tssrc/main/ipc/worktree-base-directory-poller.test.tssrc/main/ipc/worktree-base-directory-poller.tssrc/main/ipc/worktree-base-directory-watcher.test.tssrc/main/ipc/worktree-base-directory-watcher.tssrc/main/runtime/file-watcher-host.ts
There was a problem hiding this comment.
🧹 Nitpick comments (4)
src/main/emulator/serve-sim-state-watcher.ts (1)
156-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim the
Whycomment to guideline length.Logic is correct (guard/poll substitution for the removed
parentWatcher), but the added comment spans 4 lines where the guideline asks for one or two.✏️ Suggested tightening
- // Why: $TMPDIR/serve-sim/ may not exist until the first terminal `serve-sim --detach`. - // Poll for it instead of fs.watch on the parent tmpdir: watching $TMPDIR - // registers a permanent FSEvents client on the system's highest-churn - // directory, while an existence poll costs the daemon nothing. + // Why: poll for stateDir existence instead of fs.watch on $TMPDIR, which + // would register a permanent FSEvents client on the highest-churn dir.As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason."
Source: Coding guidelines
src/main/ipc/filesystem-watcher-ignore.ts (1)
5-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a readonly type for the shared constant.
WATCHER_IGNORE_DIRSis exported and consumed by multiple modules (filesystem-watcher.ts,file-watcher-host.ts). Typing it asreadonly string[](oras const) would prevent accidental mutation by a consumer from affecting every watcher.♻️ Proposed tweak
-export const WATCHER_IGNORE_DIRS: string[] = [ +export const WATCHER_IGNORE_DIRS: readonly string[] = [src/main/ipc/worktree-base-directory-poller.ts (2)
82-84: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueSequential per-entry
statcalls could be parallelized.Each candidate/entry is stat'd one at a time in a
forloop. For repos with many worktrees this adds up, though the 2s poll interval limits impact today.♻️ Proposed parallelization
- for (const dir of candidates) { - markers.set(dir, await hasGitMarker(dir)) - } + await Promise.all( + candidates.map(async (dir) => { + markers.set(dir, await hasGitMarker(dir)) + }) + )Also applies to: 116-123
176-198: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPersistent snapshot failures are silently swallowed forever.
The
.catch(() => {...})treats every snapshot failure as transient and never logs. If a target becomes permanently unreadable (permissions revoked, deleted mount, etc.), the poller will retry silently every 2s indefinitely with no diagnostic trail — unlike the previous@parcel/watchererror callback, which logged and triggered explicit cleanup. Consider logging (rate-limited) on repeated consecutive failures so real problems are debuggable.🔍 Illustrative fix
+ let consecutiveFailures = 0 const timer = setInterval(() => { if (disposed || ticking) { return } ticking = true void takeSnapshot(target, getRepos) .then((next) => { if (disposed) { return } const events = diffSnapshots(snapshot, next) snapshot = next + consecutiveFailures = 0 if (events.length > 0) { onEvents(events) } }) - .catch(() => { - // Transient fs error: keep the previous snapshot and retry next tick. - }) + .catch(() => { + consecutiveFailures++ + if (consecutiveFailures === 5) { + console.error(`[worktree-base-directory-poller] repeated snapshot failures for ${target.key}`) + } + }) .finally(() => { ticking = false }) }, pollIntervalMs)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 36ae6b93-c70d-4930-ad6e-763736150487
📒 Files selected for processing (10)
src/main/emulator/serve-sim-state-watcher.test.tssrc/main/emulator/serve-sim-state-watcher.tssrc/main/ipc/filesystem-watcher-ignore.test.tssrc/main/ipc/filesystem-watcher-ignore.tssrc/main/ipc/filesystem-watcher.tssrc/main/ipc/worktree-base-directory-poller.test.tssrc/main/ipc/worktree-base-directory-poller.tssrc/main/ipc/worktree-base-directory-watcher.test.tssrc/main/ipc/worktree-base-directory-watcher.tssrc/main/runtime/file-watcher-host.ts
…ktree-metadata stream - base targets: tick is now one stat of each gate dir (root + nested containers); the readdir + marker fan-out runs only when a gate dir changed, with a 30s ungated backstop and a bounded pending-marker recheck list. Idle tick 600us -> 1.1us at 146 worktrees. - git-common targets on macOS: replace the 2s entry sweep with one narrow native stream on <common>/.git/worktrees (tiny, rare-churn tree): zero idle syscalls and external worktree add/remove/HEAD detection back to sub-second. Re-arms via existence poll across git worktree prune deleting/recreating the dir. Win/Linux keep the listing poll (no fseventsd there; a Windows dir handle could block prune). - split git-common logic into worktree-git-common-watch.ts (max-lines). Co-authored-by: Orca <[email protected]>
…ents streams (stablyai#7068) * Cut fseventsd load: fix macOS exclusion cap, drop wide always-on FSEvents streams - @parcel/watcher maps plain-path ignores to FSEventStreamSetExclusionPaths, but macOS caps exclusions at 8 per stream and fails closed. Orca passed 9, silently disabling ALL daemon-side exclusions: fseventsd delivered every node_modules/.git event to each per-worktree explorer stream (measured 16x client CPU). Cap plain paths at 8 (extras demoted to userspace globs) via a shared filesystem-watcher-ignore module, also unifying the runtime file-watcher host list so identical roots share one native stream. - worktree-base-directory-watcher subscribed recursive FSEvents streams over every repo's ENTIRE workspace root (all worktrees) and whole common .git (objects included) with glob-only ignores (zero daemon-side exclusion), just to observe a few shallow paths. Replace with a 2s readdir/stat poller (zero fseventsd clients, measured 70x less delivery CPU); SSH targets keep provider.watch unchanged. - serve-sim state watcher held an app-lifetime fs.watch on $TMPDIR (the noisiest dir on the system); its existing 250ms existence poll makes the parent watch redundant, so drop it. Co-authored-by: Orca <[email protected]> * Eliminate base-poller idle cost: mtime-gated ticks + narrow macOS worktree-metadata stream - base targets: tick is now one stat of each gate dir (root + nested containers); the readdir + marker fan-out runs only when a gate dir changed, with a 30s ungated backstop and a bounded pending-marker recheck list. Idle tick 600us -> 1.1us at 146 worktrees. - git-common targets on macOS: replace the 2s entry sweep with one narrow native stream on <common>/.git/worktrees (tiny, rare-churn tree): zero idle syscalls and external worktree add/remove/HEAD detection back to sub-second. Re-arms via existence poll across git worktree prune deleting/recreating the dir. Win/Linux keep the listing poll (no fseventsd there; a Windows dir handle could block prune). - split git-common logic into worktree-git-common-watch.ts (max-lines). Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
Problem
macOS
fseventsdballooned to 95GB RSS on a machine running Orca with ~146 worktrees and multiple agents. fseventsd memory/CPU scales with event volume × registered client streams × delivery work (documented multi-GB blowups exist from a single over-broad client: colima#1569), and macOS 26.x additionally has a widely-reported system memory-leak regression that compounds under heavy delivery. There is also a system-wide 1024 FSEvents client cap past which watching silently fails.Orca was making fseventsd do dramatically more delivery work than needed, three ways:
Root causes fixed
1. macOS exclusion-path cap silently disabled all daemon-side exclusions
@parcel/watcherpasses plain-pathignoreentries toFSEventStreamSetExclusionPaths(true daemon-side filtering), but macOS caps that at 8 paths per stream and fails closed — and parcel never checks the return value. Orca passed 9 entries, so every per-worktree explorer stream (one per worktree with an open editor tab, persisted across restarts) received full per-filenode_modules/.gitdelivery and discarded it in userspace.Fixed by capping plain paths at 8 (extras demoted to userspace globs) in a shared
filesystem-watcher-ignoremodule, used by both the explorer watcher and the runtime file-watcher host — which also unifies the two ignore lists, so parcel's native per-(root, ignore)dedup now shares one stream when both watch the same root.2. Always-on recursive streams over entire workspace roots and whole
.gitdirsworktree-base-directory-watchersubscribed a recursive FSEvents stream per repo over the entire workspace root (all worktrees, e.g.~/orca/workspaces/orcawith 146 of them) plus another over the repo's whole common.git(objects included) — with glob-only ignores, i.e. zero daemon-side exclusion — just to observe<wt>/.gitcompletion markers,<wt>deletions, and.git/worktrees/*metadata. Every agent write, build, fetch, and pnpm install in any worktree was delivered to Orca (and buffered per-stream inside fseventsd) to be thrown away by a JS filter.Replaced with a two-part scheme sized to what the event filter actually consumes:
git-common), macOS: one narrow native stream rooted at<common>/.git/worktrees— a tiny, rare-churn tree. Zero idle cost, zero wide-scope delivery, and instant detection:git worktree add/removealways writes here, so external add/remove/HEAD changes surface sub-second. If the dir doesn't exist yet (no linked worktrees) a 1-stat existence poll arms the stream when it appears; ifgit worktree prunedeletes it, the watcher re-arms the same way. On Windows/Linux this stays a listing poll (no fseventsd to protect; on Windows an open directory handle could interfere withpruneremoving the dir).base), all platforms: a 2s poll whose tick is mtime-gated — onestatof the root (plus nested repo containers); the readdir + per-worktree.git-marker fan-out only runs when a gate dir actually changed, with a 30s ungated full-scan backstop and a bounded recheck list for worktrees whose.gitmarker lands after the dir. Registers zero fseventsd clients.3. App-lifetime
fs.watchon$TMPDIRThe serve-sim state watcher held a permanent FSEvents client on the system's highest-churn directory, even though a 250ms existence poll already ran alongside it. Dropped the parent watch; the poll alone attaches the narrow
$TMPDIR/serve-sim/watcher when the dir appears.Evidence (reproduced before fixing)
Identical 30k-op
node_moduleschurn burst; metric is watching-process CPU including the native FSEvents drain thread, proportional to what fseventsd had to enqueue + deliver:Idle cost of the replacement, simulated at 146 worktrees:
Control experiments on the affected machine showed fseventsd RSS is insensitive to raw churn (~0.14MB per 80k events), suspended clients (bounded queue, then drops), and 100 idle clients (~6KB each) — the damage comes from sustained wide-scope delivery, which is exactly what these changes eliminate. At 15 repos + 50 open worktrees this removes ~30 always-on whole-tree streams (replaced by ~15 tiny
.git/worktreesstreams + gated polls) and restores daemon-side exclusion on the ~50 per-worktree streams.E2E verification (dev build, CDP)
Orca: nwparker/fseventsd.git worktree addfrom a terminal → sidebar store updated in 728ms.git worktree remove→ detected in 2.4s (pre-narrow-stream build; now event-driven on macOS).node_moduleschurn delivered zero events.pnpm typecheckclean.ELI5
macOS has one built-in "post office" for file changes (
fseventsd). Any app can subscribe: "deliver me a note whenever anything changes under this folder." The post office does real work for every note — sorting, packaging, delivering a copy to each subscriber — and on macOS 26 it also has a hoarding problem: under heavy load it never quite gives back the memory it used. That's the 95GB.Orca was the post office's worst customer, three ways:
pnpm install, every build in any of 146 worktrees got packaged and delivered to Orca... which read the address and threw it away. Now Orca subscribes only to git's tiny worktree-bookkeeping folder (a few entries, changes only when worktrees actually change) and otherwise just checks a timestamp — one glance every 2 seconds, escalating to a real look only when the timestamp moved.node_modules,.git, ...). macOS only accepts stickers with 8 or fewer entries — one over, and it silently ignores the whole sticker. So the post office delivered all the junk mail anyway. Now the sticker has 8 entries and actually works: junk is discarded at the post office, never delivered.Orca can't fix the post office's hoarding bug (that's Apple's), but it can stop sending it 100× more work than needed — which is what feeds the hoarding.
User-visible trade-offs
Honest list of what changes, and by how much:
git worktree add/removein a terminal, scripts)rm -rf)prune) is still instant on macOS.serve-sim --detachpickupstat; measured at 146 worktrees), 0 syscalls for macOS worktree metadata, plus a 30s full-scan backstop__pycache__churn (the demoted 9th ignore entry)Explicitly unchanged: file-explorer auto-refresh behavior and its ignore semantics (dirs like
dist/node_modulesnever auto-refreshed by design), SSH/remote worktree watching (stillprovider.watch), WSL watching (still the snapshot subprocess with the same plain-name list), and all Orca-initiated worktree flows.Not fixed here (follow-ups)
persistence.ts300ms full-state rewrites, unthrottled conflict-summarygit fetch/merge-tree— same.ps -o rss= -p $(pgrep -x fseventsd)trend +log show --predicate 'process == "fseventsd"'will attribute it.