Repository navigation
fix(ssh): resync after watcher terminal retry - #10691
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe change adds current-desired listener checks and coalesced resynchronization to SSH remote watcher retry and reinstallation flows. It also adds Vitest coverage for terminal retries, provider registration, owner and renderer cancellation, teardown recovery, shutdown cleanup, and reopened watch lifecycles. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🔧 Fix failing CI
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 (3)
src/main/ipc/filesystem-watcher.ts (1)
1269-1288: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider gating the warn log behind the new closed/suspended check.
The
console.warnat Line 1275 now precedes a guard that treatsremoteWatchersClosed/suspendedRemoteWatcherListenersas expected, no-op outcomes. As a result, every intentional worktree close or destructive removal will log a "SSH watcher terminated" warning even though nothing actionable happens — this makes the log noisier and harder to distinguish from a real unexpected termination.♻️ Proposed reordering
remoteWatchers.delete(key) - console.warn(`[filesystem-watcher] SSH watcher terminated for ${key}:`, error) if (remoteWatchersClosed || suspendedRemoteWatcherListeners.has(key)) { return } + console.warn(`[filesystem-watcher] SSH watcher terminated for ${key}:`, error) const startedAt = Date.now()src/main/ipc/filesystem-watcher-terminal-resync.test.ts (2)
41-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMinor duplication with the custom sender in the "destroyed" test.
createSenderhardcodesisDestroyed: () => false, forcing the destroyed-renderer test (Line 181-186) to redeclare the same shape inline with a mutable flag. Consider extendingcreateSenderto accept an optional mutable destroyed-state, or extracting a sharedMockSendertype, to avoid two near-identical shapes.
179-197: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMock captures
.once()handlers by index, not by event name.
destroyedHandlersaccumulates every.once()registration on the sender regardless of event, and the test firesdestroyedHandlers[0]. If the implementation ever registers another.once()listener before the "destroyed" one, this assertion would silently target the wrong handler instead of failing loudly.♻️ Proposed fix
- once: vi.fn((_event: string, handler: () => void) => destroyedHandlers.push(handler)), + once: vi.fn((event: string, handler: () => void) => { + if (event === 'destroyed') destroyedHandlers.push(handler) + }),
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a12bd997-fbfa-458f-859b-f66bf9c71c96
📒 Files selected for processing (2)
src/main/ipc/filesystem-watcher-terminal-resync.test.tssrc/main/ipc/filesystem-watcher.ts
|
@coderabbitai[bot] resovled |
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
- Coalesce repeated recovery resyncs within 5s to reduce SSH refreshes during link flaps - Abort in-flight watcher installs when a replacement provider registers, preventing duplicate watchers from old and new transports - Clear resync state when removing watcher snapshots or on provider change to prevent stale retry timers
Avoid logging spurious warnings when a remote watcher is already closed or suspended. Move the console.warn call in handleRemoteWatcherTerminalError() to after the early-return checks. Refactor createSender() in tests to properly simulate the destroyed event for better coverage of retry-cancellation behavior.
| function flushRemoteWatcherResync(key: string): void { | ||
| const state = remoteWatcherResyncStates.get(key) | ||
| if (!state) { | ||
| return | ||
| } | ||
| state.timer = undefined | ||
| if ( | ||
| remoteWatchersClosed || | ||
| suspendedRemoteWatcherListeners.has(key) || | ||
| !remoteWatchers.has(key) | ||
| ) { | ||
| if (!desiredRemoteWatchers.has(key)) { | ||
| remoteWatcherResyncStates.delete(key) | ||
| } | ||
| return |
There was a problem hiding this comment.
Retained listeners not cleared on early-return skip
When flushRemoteWatcherResync fires its coalesce timer but !remoteWatchers.has(key) (the watcher died again between being installed and the timer expiring) and desiredRemoteWatchers.has(key), the function returns early without clearing state.listeners. The intent is to buffer the pending overflow until the watcher reinstalls and calls requestRemoteWatcherResync again — at which point delayMs === 0 (lastSentAt still at NEGATIVE_INFINITY) triggers an immediate flush that picks up the retained listeners alongside any new ones.
This works correctly and is covered by tests, but it is a non-obvious invariant: unlike the success path (state.listeners.clear() after sending) and the fully-cancelled path (remoteWatcherResyncStates.delete(key)), this third outcome leaves the map entry in a partially-consumed state. A comment co-located with the return explaining why listeners are intentionally preserved here would help future maintainers avoid accidentally "fixing" it.
Greptile SummaryThis PR fixes a pre-existing bug where a successfully retried SSH watcher (after a terminal error) never sent an overflow event to renderers, leaving them with a stale view of the filesystem. It also introduces a 5-second coalescing window to prevent overflow spam during rapid watcher flaps, and filters stale/unregistered listeners across all overflow delivery sites.
Confidence Score: 4/5Safe to merge; the bug fix and guard logic are well-scoped and all 47 tests pass, including new cases for every cancellation edge. The core fix (adding resyncOnInstall=true to terminal-error retries) is straightforward and well-tested. The new resync state machinery is more complex — three new functions, coalesce timing, and a partially-retained state on early-return — but each branch is covered by a dedicated test case. The only observations are style-level: a cleanup inconsistency between two cancellation sites and an undocumented invariant in the early-return path of flushRemoteWatcherResync. Files Needing Attention: The three new functions in filesystem-watcher.ts (clearRemoteWatcherResync, flushRemoteWatcherResync, requestRemoteWatcherResync) and the early-return branch in flushRemoteWatcherResync that intentionally retains state.listeners deserve a second look on review.
|
| Filename | Overview |
|---|---|
| src/main/ipc/filesystem-watcher.ts | Adds RemoteWatcherResyncState map, three new helper functions (clearRemoteWatcherResync, flushRemoteWatcherResync, requestRemoteWatcherResync), and wires resyncOnInstall=true through terminal-error retries; also adds inFlight.abortController.abort() on provider replacement and missing retry cancellation in forgetRemoteWatcherRemovalSnapshot. |
| src/main/ipc/filesystem-watcher-terminal-resync.test.ts | New test file with 9 focused cases covering: stale-owner filtering, initial-failure non-resync, provider-registration supersession, in-flight abort on replacement provider, coalesce deduplication, and cancellation on unwatch / snapshot forget / renderer destroy / destructive removal / shutdown reopen. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[SSH watcher terminal error] --> B{remoteWatchersClosed\nor suspendedListeners has key?}
B -- yes --> Z[Return — suppress retry]
B -- no --> C[scheduleRemoteWatcherRetry\nresyncOnInstall=true]
C --> D{Retry timeout\nexceeded?}
D -- yes --> E[Send overflow immediately\n+ schedule dormant rearm]
D -- no --> F[Wait REMOTE_WATCH_RETRY_MS 1s]
F --> G[installRemoteWatcher\nfor each live listener]
G --> H{result?}
H -- installed --> I[requestRemoteWatcherResync]
H -- unavailable --> C
H -- cancelled --> Z2[No resync — renderer\nstopped watching]
I --> J{lastSentAt within\n5-second window?}
J -- no/first send --> K[flushRemoteWatcherResync immediately]
J -- yes --> L{timer already\nscheduled?}
L -- yes --> M[Coalesce into existing timer]
L -- no --> N[Schedule timer for remaining window]
N --> K
M --> K
K --> O{watcher still\nin remoteWatchers?}
O -- no, desired --> P[Keep state — buffer until next install]
O -- yes --> Q[Send fs:changed overflow\nto isCurrentDesiredRemoteWatcher listeners]
Q --> R[Update lastSentAt for next coalesce window]
Comments Outside Diff (1)
-
src/main/ipc/filesystem-watcher.ts, line 1016-1030 (link)Inconsistent
pendingRemoteWatcherRetryListenerscleanup patternforgetRemoteWatcherRemovalSnapshotnow unconditionally deletes frompendingRemoteWatcherRetryListeners(outside theif (retryTimer)block), whilecloseRemoteWatcherForWorktreePath(line 966–971) only deletes it when a timer is present. In practice this is harmless — the two maps are always set and cleared together inscheduleRemoteWatcherRetry— but the unconditional form adopted here is more defensive and would be worth applying consistently tocloseRemoteWatcherForWorktreePathas well to make the invariant explicit.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Reviews (1): Last reviewed commit: "fix(ssh): resync after watcher terminal ..." | Re-trigger Greptile
* fix(ssh): resync after watcher terminal retry * fix(ssh): resync after watcher terminal retry - Coalesce repeated recovery resyncs within 5s to reduce SSH refreshes during link flaps - Abort in-flight watcher installs when a replacement provider registers, preventing duplicate watchers from old and new transports - Clear resync state when removing watcher snapshots or on provider change to prevent stale retry timers * fix(ssh): resync after watcher terminal retry Avoid logging spurious warnings when a remote watcher is already closed or suspended. Move the console.warn call in handleRemoteWatcherTerminalError() to after the early-return checks. Refactor createSender() in tests to properly simulate the destroyed event for better coverage of retry-cancellation behavior.
Summary
Test plan
Release-scan provenance
This PR addresses the pre-existing prod-release-scan P2 finding "SSH watcher fast-retry without overflow resync" documented in /private/tmp/prod-release-worker-reports/FINAL.md and platform.md. Nearby behavior and context are tracked in #10445 and #10470.