Skip to content

Prevent index churn from refreshing worktrees - #8431

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/terminal-input-lag-investigation
Jul 13, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/terminal-input-lag-investigation

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Classify Git-common filesystem events as structural, status-only, or ignored.
  • Keep worktrees:changed structural-only and add a desktop status-metadata signal for Source Control.
  • Preserve macOS narrow native watching, SSH rename/overflow behavior, and bounded non-overlapping Linux/Windows leaf polling.
  • Add an experimental reliability gate proving index-only bursts have zero structural fanout.
  • Keep background-worktree heads fresh: external commits/amends/soft-resets are detected from spawn-free Git metadata reads (HEAD/gitdir/loose refs/packed-refs) diffed inside the watcher debounce, and reach store rows through a new worktrees:headIdentitiesChanged event emitted only on real head moves.
  • Classify HEAD reflog appends as status-only triggers (covers amend/reset-soft, which write no watched leaf) and config.worktree as structural (the only file whose write flips the sparse flag; never touched by status/commit).
  • Add a periodic ungated index re-stat to the non-darwin poller so in-place index rewrites on coarse-mtime filesystems cannot be missed indefinitely.

At the reported 1:57 PM stall, one Orca-owned git worktree span lasted 5.502 seconds amid 142 worktree commands in one minute. Ordinary external git status calls rewrite a linked worktree index. The watcher labeled every event below .git/worktrees/ as structural, invalidating worktree caches and triggering fetchWorktrees/git worktree list. Main-process spawn pressure then queued pty:write.

This keeps index churn as a Source Control freshness hint without treating it as a worktree graph mutation. Real add/remove/HEAD/gitdir/locked changes retain the structural path.

Screenshots

The terminal has no visual design change. Live validation evidence shows all 50 sequential input chunks delivered during the linked-index storm.

Testing

  • Full oxlint run (pre-existing warnings only) and max-lines ratchet
  • All node, CLI, and web TypeScript targets
  • 128 focused reliability-gate tests across classifier, watcher, poller, head-identity reader/apply, Source Control refresh, and IPC API shape
  • 145 adjacent tests across main-thread diagnostics, structural refresh queue, IPC wiring, and web preload compatibility
  • Added high-quality count regressions for zero structural fanout, SSH rename/overflow semantics, exact polling leaves, preload cleanup, and active-visible Source Control filtering
  • Instrumented Electron dev build and live test
  • Full repository pnpm test (CI verify passed instead)
  • Packaged production build (Electron dev main/preload/renderer build passed)

Live run: 2,000 external linked-worktree git status calls while sending 50 sequential terminal input chunks. All 50 arrived in order. Six consecutive five-second diagnostic windows recorded zero Orca-owned git worktree spawns; the worst gap was 75 ms from unrelated glab auth. A linked locked create/delete positive control subsequently produced the expected structural refreshes.

Second live run (freshness fix): with no active worktree, an external commit and then an external commit --amend in a background linked worktree each updated the store row's head to the exact new sha within one debounce, with zero worktrees:changed. git sparse-checkout init fired exactly one structural refresh. A sustained index storm (readout taken mid-storm) produced 0 structural events, 27 coalesced status signals, and 0 head-identity events — the emit-on-change gate holds; typed terminal input executed during the storm.

AI Review Report

The review traced the complete renderer → main pty:write path, cache invalidation and fetchWorktrees fanout, local native/poll watcher paths, SSH event shapes, and earlier refresh-storm fixes (#5608, #6020, #6153, #6324, #6390, #7595, and the Source Control signal introduced by #7086).

It explicitly checked macOS, Linux, and Windows behavior, Node path handling (including Windows separators), SSH rename/overflow semantics, bounded/non-overlapping polling, preload cleanup, and structural Source Control nudges. It found and fixed a macOS performance regression where a repo starting without linked worktrees would remain on leaf polling instead of upgrading to the native narrow watcher. CodeRabbit then found that the reliability command omitted the touched IPC API-shape fixture; that test is now included in the gate.

The review also challenged the linked-index signature shortcut. The shortcut is intentionally gated by entry-directory changes because Git replaces indexes through lock/create/rename; a missed nonstandard in-place status-only write remains eventually consistent through normal Source Control polling. Structural HEAD/gitdir/locked signatures are always compared and have a regression test with restored parent mtime.

Security Audit

No user command execution, Git command/options, authentication, secrets, dependencies, or permission boundaries changed. Filesystem events are reduced to an explicit shallow metadata allowlist and paths are normalized with Node path utilities. The new IPC event carries only the existing internal repoId, has explicit unsubscribe cleanup, is desktop-only, and does not cross the runtime/mobile structural event boundary. Overflow/error behavior remains conservatively structural. No security follow-up is required.

Notes

  • Linux/Windows share deterministic forced-poller coverage; this run's live Electron evidence is macOS.
  • SSH uses the same semantic classifier (including the new reflog/status triggers) while preserving conservative structural overflow handling; the metadata-read head diff is local-only, so remote background-worktree heads still wait on a structural event or activation (documented in the gate's known gaps).
  • The new reliability gate stays experimental until its soak/promotion criteria are met.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Attachments

0059bda6-ea0b-40b6-8792-1d0dbbed1cba-screenshot.png
0059bda6-ea0b-40b6-8792-1d0dbbed1cba-screenshot.png

@coderabbitai

coderabbitai Bot commented Jul 12, 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

The change separates worktree filesystem events into structural and Git-status metadata categories. New Git-common polling detects linked-worktree and primary-checkout metadata changes, while collectors and watchers debounce and broadcast category-specific notifications. Main-process readers and refresh state now propagate changed worktree head identities through IPC to renderer state. Preload, web compatibility, status-refresh hooks, and tests support the new events. A reliability gate documents the event semantics and validation coverage. Unrelated settings and test formatting changes are also included.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.45% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and directly reflects the main change: reducing worktree refreshes caused by index churn.
Description check ✅ Passed The description follows the template and includes summary, screenshots, testing, AI review, security audit, and notes.
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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/main/ipc/worktree-git-common-watch.ts (1)

41-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate diff-signature logic between Darwin and non-Darwin paths.

diffMtimeMap (mtime-only) duplicates the purpose of classifySignatureDiff/diffSignatureMaps in worktree-git-common-polling.ts, but with a weaker signature (no ctime/ino/size) used only for Darwin's primary-checkout metadata poll. Consider extending startGitCommonPolling with a "primary-only" mode (skip worktrees/ scanning) so Darwin can reuse the stronger, single diffing implementation instead of maintaining two parallel mechanisms.

src/main/ipc/worktree-base-directory-poller.test.ts (1)

211-235: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider adding the analogous regression test for index.

This test proves HEAD rewrites are detected regardless of entry-dir mtime restoration (since structural files bypass the shortcut). There's no equivalent test proving index rewrites are detected under the same restored-mtime condition — which is exactly the shortcut-dependent path flagged in worktree-git-common-polling.ts (snapshotGitCommonEntry's shouldReadIndex). Adding a sibling test here (rewrite index, restore entry-dir mtime, assert update) would directly validate or falsify that shortcut.

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

48-67: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add coverage for the linked-worktree index shortcut in src/main/ipc/worktree-git-common-polling.ts:48-67. snapshotGitCommonEntry reuses previous.indexSignature when the entry dir signature is unchanged; current tests only cover first-time index creation and linked HEAD rewrites. Add a regression test for rewriting an existing worktrees/*/index (with the dir mtime restored) or drop the optimization if you don’t want to rely on that assumption.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: bb2b137d-3134-4124-a9f1-6543caa73c8d

📥 Commits

Reviewing files that changed from the base of the PR and between 9dc1f25 and a3b8f76.

📒 Files selected for processing (16)
  • config/reliability-gates.jsonc
  • src/main/ipc/worktree-base-directory-change-collector.ts
  • src/main/ipc/worktree-base-directory-event-filter.test.ts
  • src/main/ipc/worktree-base-directory-event-filter.ts
  • src/main/ipc/worktree-base-directory-poller.test.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.ts
  • src/main/ipc/worktree-remote.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.test.ts
  • src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/web/web-preload-api.ts

Comment thread config/reliability-gates.jsonc Resolved
Brennan Benson and others added 2 commits July 12, 2026 16:07
External commits, amends, and soft resets in non-active worktrees now reach
store rows through spawn-free Git metadata reads diffed in the watcher's
existing debounce, emitted only on real head moves. HEAD reflog appends become
status-only triggers, config.worktree becomes structural for sparse-flag
freshness, and the non-darwin poller gains a periodic ungated index re-stat
so in-place rewrites on coarse-mtime filesystems cannot be missed forever.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Freshness follow-up: background worktree heads (1eb8163)

Review of this PR found that narrowing the classifier removed an accidental-but-relied-on freshness path: external/agent commits in non-active worktrees previously refreshed every row's head via the structural fanout, and every remaining refresh path (push signal, command-finished, status poll) is active-worktree-scoped. Stale background heads feed the merged/diverged PR badge logic and currentHeadOid on hosted-review polls indefinitely. Two smaller gaps: commit --amend/reset --soft write no watched leaf at all, and external git sparse-checkout init/disable could never refresh isSparse.

This commit closes all three without touching the invariant:

  • Spawn-free head reader (worktree-head-identity-reader.ts): resolves head/branch for the primary checkout and every linked worktree from HEAD/gitdir/loose refs/packed-refs file reads — no Git subprocess. Diffed against a baseline inside the watcher's existing 250 ms debounce; a new worktrees:headIdentitiesChanged event fires only when a head actually moved and patches store rows via the existing updateWorktreeGitIdentity no-op-safe action. Structural ticks re-baseline silently (the full listing stays authoritative). Never routes back through fetchWorktrees or worktrees:changed.
  • Reflog trigger: worktrees/<e>/logs/HEAD and top-level logs/HEAD classify as status-only (amend/reset-soft coverage); per-ref reflogs stay ignored. The non-darwin poller stats these leaves per tick.
  • config.worktree → structural: the only file whose write flips git worktree list's sparse flag, and no status/commit path touches it — restores external sparse-toggle freshness with zero storm risk.
  • Poller backstop: every 15th tick re-stats linked indexes ungated, bounding the coarse-mtime in-place-rewrite miss the entry-dir signature gate allows.

Live evidence (macOS, dev build, fresh profile): with no active worktree, an external commit and a subsequent commit --amend in a background linked worktree each updated the store row to the exact new sha within one debounce cycle, with worktrees:changed = 0. git sparse-checkout init fired exactly one structural refresh. A sustained external index storm, read out mid-storm, produced 0 structural events, 27 coalesced status signals, 0 head-identity events, and typed terminal input executed during the storm.

Tests: gate grows 109 → 128 (reader layouts incl. packed-refs/detached/unborn/relative-gitdir; watcher emit-on-change, silent re-baseline, SSH skip; poller reflog leaves + in-place-index backstop; renderer apply-by-path incl. Windows separators). Gate manifest checker passes; full typecheck and lint clean.

Known gap (documented in the gate): the head diff is local-only — SSH background-worktree heads still wait on a structural event or activation, since diffing over SSH would add per-signal network reads.

@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

Run ID: 9ec392f2-9aa7-4698-b027-77365de2429d

📥 Commits

Reviewing files that changed from the base of the PR and between eb5e749 and 1eb8163.

📒 Files selected for processing (20)
  • config/reliability-gates.jsonc
  • src/main/ipc/worktree-base-directory-event-filter.test.ts
  • src/main/ipc/worktree-base-directory-event-filter.ts
  • src/main/ipc/worktree-base-directory-poller.test.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.ts
  • src/main/ipc/worktree-head-identity-reader.test.ts
  • src/main/ipc/worktree-head-identity-reader.ts
  • src/main/ipc/worktree-head-identity-refresh.ts
  • src/main/ipc/worktree-remote.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/hooks/worktree-head-identity-apply.test.ts
  • src/renderer/src/hooks/worktree-head-identity-apply.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • config/reliability-gates.jsonc
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/main/ipc/worktree-base-directory-event-filter.ts
  • src/main/ipc/worktree-git-common-polling.ts
  • src/preload/api-types.ts
  • src/main/ipc/worktree-base-directory-event-filter.test.ts
  • src/preload/index.ts
  • src/main/ipc/worktree-base-directory-watcher.ts
  • src/main/ipc/worktree-git-common-watch.ts

…2025/terminal-input-lag-investigation

# Conflicts:
#	config/reliability-gates.jsonc
Brennan Benson and others added 2 commits July 12, 2026 18:07
Ref content comes from repo files an attacker can craft. Backslash segments
traverse on Windows where join treats them as separators, and colons are
forbidden in Git ref names; both now fail isSafeRefName before any path is
built. Resolved values are additionally emitted only when they match a hex
SHA-1/SHA-256 object id, so no file content can leak through the identity
event even in principle.
@brennanb2025
brennanb2025 merged commit db9421d into main Jul 13, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* Prevent index churn from refreshing worktrees

* Cover IPC contract in worktree reliability gate

* Refresh background worktree heads without re-entering structural fanout

External commits, amends, and soft resets in non-active worktrees now reach
store rows through spawn-free Git metadata reads diffed in the watcher's
existing debounce, emitted only on real head moves. HEAD reflog appends become
status-only triggers, config.worktree becomes structural for sparse-flag
freshness, and the non-darwin poller gains a periodic ungated index re-stat
so in-place rewrites on coarse-mtime filesystems cannot be missed forever.

* Reject unsafe symref paths and validate object ids in the head reader

Ref content comes from repo files an attacker can craft. Backslash segments
traverse on Windows where join treats them as separators, and colons are
forbidden in Git ref names; both now fail isSafeRefName before any path is
built. Resolved values are additionally emitted only when they match a hex
SHA-1/SHA-256 object id, so no file content can leak through the identity
event even in principle.

---------

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