Repository navigation
fix(ssh, relay): keep remote sessions alive through reconnects and backpressure - #11999
Conversation
…and frame caps Three independent connection killers found in the SSH/remote freeze audit. FINDING A - the reconnect ladder never escalated for post-handshake drops. scheduleReconnect() used the single published state.reconnectAttempt for both the delay index and the give-up test, and runReconnectAttempt() zeroed it before connecting (ssh.ts gates the relay redeploy on 0-at-connected). Every post-handshake drop therefore re-entered at 1000ms forever, ~3600 relay redeploys/hour, and 'reconnection-failed' was unreachable for a flapping host. New SshReconnectLadder splits the delay index (advanced by every retry) from the failure streak (advanced only by a failed handshake), so flaps back off while give-up semantics stay byte-identical to shipped. FINDING B - notify() closed the client whenever a frame exceeded the producer frame capacity, conflating a permanently un-sendable frame with transient backpressure. A 5000-event fs.changed is 425KB against a 49KB cap, so the watcher flood killed the link and re-killed on every reattach+replay. notify() now drops and logs once per generation; fs.changed is chunked to each sink's capacity with a control-lane overflow marker as the resync fallback; agent-hook envelopes shed lastAssistantMessage/interactivePrompt/subagents to fit. FINDING B2 - sendResponse routed >1MB responses to a lane whose admission ignores the frame cap and closed the client on rejection, so a large fs.listFiles dropped the SSH host. It now substitutes a JSON-RPC error so the request fails instead of the connection. Also moves fs.streamEnd/fs.streamError to the control lane so a terminal frame cannot be dropped by the producer-lane check. Co-authored-by: Orca <[email protected]>
…ects Round-1 review fixes on the P0 freeze work. The control-lane overflow marker could reinstate the exact failure this P0 removes: dispatcher-client-writer closes the client when control-lane admission fails, and admitControl is the only lane that returns an error, so one marker per failing batch accumulated to the 256-frame/1MB bound and dropped the link. Markers are now deduped to one outstanding per (client, root), cleared on settle. Chunking also defeated the renderer's per-payload directory dedupe -- events are now stable-grouped by parent directory so one directory lands in one chunk -- and the halving walk overshot the byte minimum ~1.7x while the fast path paid three JSON encodes; both are fixed by publishing first and sizing from a measured bytes-per-event estimate. Agent-hook shedding now surrenders the blocking interactive prompt LAST rather than first, so a degraded envelope cannot strand a pane at state=waiting with no answerable question card. The dropped-notification log now distinguishes over-capacity from producer queue backpressure and no longer lets the first dropped method silence every other producer for the life of the connection.
… one freeze for another Round-2 review fixes. The round-0 change from close-on-rejection to silent drop removed the only redelivery path for agent.hook envelopes: they are fire-and-forget and the per-pane cache only replays on handler install, so a saturated link stranded a pane on a stale Working spinner until reconnect. Closing used to guarantee delivery by forcing that replay. Envelopes now publish per client and pend for bounded latest-wins redelivery when the producer queue rejects them. Shed fields are now named on the wire. The subagent roster is not cosmetic -- the renderer replaces rather than merges it, and hibernation gates on its length -- so an unmarked shed could sleep a live pane. fs.streamEnd rode the control lane because it must not be dropped, but that lane kills rather than drops. The stream's concurrency slot is now held until the terminal frame settles rather than until the fd closes, capping queued terminal frames well under the control budget; overflow costs one refused read instead of the connection. The watcher chunk walk now stops while producer retention sits past its reserve and degrades to a resync, so a 5000-event flood cannot fill the queue that interactive PTY traffic shares and stall every remote terminal. The reconnect ladder caps its flap-path delay so delay plus handshake timeout cannot cross the relay grace floor and let the remote daemon kill live PTYs. Also: the suppression key no longer embeds a NUL byte, which had made the file binary to git and grep; producerEnvelopeBudget no longer reports infinite capacity for a departed client; the drop logger no longer encodes a frame it will not log; and an over-capacity response substitution no longer settles as if the result had been delivered.
…re per client Round 3 + 4 review fixes. Watcher chunking is now gated on the *client's* retention reserve rather than the dispatcher-wide one, so one stalled peer no longer forces a healthy client into a full file-tree resync. The relay-lost redeploy ladder no longer burns its 6-attempt budget while the SSH transport itself is down: it holds at the 15s step with a non-terminal status and rearms, so a laptop that slept past the ladder comes back instead of landing on a terminal "give up" banner. The shedFields wire marker had no consumer, so an agent-hook envelope whose subagent roster was dropped to fit the frame read as "roster cleared" on the Orca side: live child rows blanked and a done pane became hibernation-eligible while its teammates were still running. ingestRemote now restores shed fields from the cached payload (interactivePrompt deliberately excluded — a stale answerable question card is worse than none). Also: stream terminal-frame slots are counted per client, since the control queue they protect is per client; the chunking fast path no longer logs a drop for a batch it goes on to deliver in full; -32010 is now RelayErrorCode.ResponseOverCapacity. Test debt from the review: pending-pane eviction, per-client stream isolation, and the reconnect budget are now asserted rather than assumed; four fragile exact-byte pins dropped in favour of the tier comparisons that carry the requirement.
- Oversized relay responses now fail their request instead of closing the connection, preventing one frame from killing every pane on the host - Restore subagent state for correct hibernation; don't resurrect stale prose across turns - Account for relay re-establishment and PTY reattach time in SSH flap delay caps - Only log drops of final unsendable envelopes, not temporary rejections during measurement probes - Fix watcher overflow marker release race when notification admission rejects without settlement; use precise byte counting for event batching
Validate that shed subagent rosters match their wire digest and turn identity before restoration, preventing stale roster resurrection. Compact interactive prompts for waiting states instead of dropping them. Demote control-queue overflow to non-fatal rejection so clients can retry on capacity recovery, keeping the link alive during transient backpressure.
|
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 (6)
📝 WalkthroughWalkthroughThe changes add bounded relay publication with payload shedding, prompt compaction, redelivery, and per-client capacity handling. Watcher and file-stream delivery now use targeted queues, frame budgeting, and overflow recovery. SSH reconnect logic separates flap delays from handshake failures and coordinates relay retries with transport state. Agent-hook envelopes now carry shed-field metadata and can restore verified cached subagent rosters. The dispatcher distinguishes producer and control overflow, returns structured errors for oversized responses, and allows callers to mark control overflow as non-fatal. 🚥 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.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/main/ipc/ssh.ts (1)
748-786: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider consuming an attempt when a deferred redeploy actually runs.
The wait path schedules a redeploy without incrementing
state.attempts. When the timer fires and the transport isconnected,s.reconnect(...)runs a real relay deploy that no attempt accounts for. If the transport alternates betweenreconnectingandconnected, the relay can be redeployed repeatedly without ever reachingRELAY_LOST_MAX_ATTEMPTS, which is the bound this backoff exists to enforce. Incrementingstate.attemptsimmediately before the deferreds.reconnect(...)keeps the budget aligned with executed deploys, while still not charging attempts for pure waiting.♻️ Proposed adjustment
const status = connectionManager?.getState(tid)?.status if (status === 'connected') { + // Why: a deferred redeploy is a real attempt; charge it so the max-attempt bound still applies. + state.attempts += 1 + relayLostBackoff.set(tid, state) void s.reconnect(liveConn, relayGracePeriodForTarget(t)) return }src/relay/fs-handler-stream.test.ts (1)
456-456: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDerive the fixture size from
STREAM_CHUNK_SIZE.The comment states "one chunk per stream", but the size is the literal
64 * 1024. IfSTREAM_CHUNK_SIZEchanges, the comment becomes wrong and each stream emits several chunks. The test still passes, because it counts only terminal frames. The file already importsSTREAM_CHUNK_SIZEat line 5.♻️ Proposed change
- writeFileSync(filePath, Buffer.alloc(64 * 1024, 0x42)) // one chunk per stream + writeFileSync(filePath, Buffer.alloc(STREAM_CHUNK_SIZE, 0x42)) // one chunk per streamsrc/relay/dispatcher-writer-admission.ts (1)
30-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftPrefer an explicit entry field over encoder identity for the non-fatal flag.
markControlOverflowNonFatalcarries the flag out of band, keyed on theencodefunction identity. Any future code that wraps or replacesencodebetweenenqueueFrameandadmitControlloses the mark. Control overflow then closes the client again, which is the failure this PR removes. An explicit field onDispatcherWriterEntry(for exampleoverflowIsNonFatal) makes the contract type-checked and removes the module-levelWeakSet.♻️ Sketch
export type DispatcherWriterEntry = { lane: DispatcherWriterLane encode: () => Buffer estimatedBytes: number onSettled: (result: DispatcherWriterSettlement) => void settled: boolean + overflowIsNonFatal?: boolean }private admitControl(entry: DispatcherWriterEntry): AdmissionResult { - // Why: best-effort controls may fail soft without weakening protocol-critical admission. - const overflowIsNonFatal = nonFatalControlEncodes.delete(entry.encode) + // Why: best-effort controls may fail soft without weakening protocol-critical admission. + const overflowIsNonFatal = entry.overflowIsNonFatal === trueAlso applies to: 152-161
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 277ba578-3fcf-4899-845c-18fb8be1ff8d
📒 Files selected for processing (27)
src/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/main/ssh/ssh-connection.test.tssrc/main/ssh/ssh-connection.tssrc/main/ssh/ssh-reconnect-ladder.test.tssrc/main/ssh/ssh-reconnect-ladder.tssrc/main/ssh/ssh-relay-session.tssrc/relay/agent-hook-envelope-publication.test.tssrc/relay/agent-hook-envelope-publication.tssrc/relay/agent-hook-integration.test.tssrc/relay/dispatcher-capacity-degradation.test.tssrc/relay/dispatcher-writer-admission.tssrc/relay/dispatcher.tssrc/relay/fs-handler-file-read.tssrc/relay/fs-handler-stream.test.tssrc/relay/protocol.tssrc/relay/relay-filesystem-watch-registry.test.tssrc/relay/relay-filesystem-watch-registry.tssrc/relay/relay-oversized-notification-survival.test.tssrc/relay/relay-watcher-event-emitter.test.tssrc/relay/relay-watcher-event-emitter.tssrc/relay/relay.tssrc/relay/wsl-agent-hook-relay.tssrc/shared/agent-hook-relay.test.tssrc/shared/agent-hook-relay.ts
Greptile SummaryThis PR adds three orthogonal resilience improvements to the SSH + relay stack: (1) a two-counter reconnect ladder that separates delay back-off from handshake-failure budget so repeated post-handshake drops back off without consuming the give-up quota; (2) per-client watcher batch sizing and one-outstanding overflow marker per
Confidence Score: 5/5Safe to merge; all three subsystems are carefully isolated and the edge cases are explicitly handled and covered by 173 focused tests. The reconnect ladder correctly separates delay back-off from the handshake-failure budget, the per-client watcher chunking with the one-outstanding overflow marker prevents producer-lane starvation, and the shed-field restoration is gated on both digest and turn identity. No path was found that silently drops state, closes a connection incorrectly, or leaks an outstanding marker slot. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/ssh/ssh-reconnect-ladder.ts | New class encapsulating reconnect policy with independent delay/failure counters; FLAP_DELAY_CAP_MS calculation and per-attempt increment logic are correct. |
| src/main/ssh/ssh-connection.ts | Switches from inline reconnect state to SshReconnectLadder; markConnected/markAttemptFailed call sites are correct and reset() is called on fresh connect() success. |
| src/main/ipc/ssh.ts | Adds TRANSPORT_TERMINAL_STATUSES guard and clearRelayLostBackoff on transport reconnect; relay-lost budget correctly preserved across transport outages and reset on a fresh transport generation. |
| src/relay/relay-watcher-event-emitter.ts | Per-client chunking with exact eventsCapacity budget; batchBytes <= eventsCapacity early-overflow correctly handles queue-full; one-outstanding overflow marker per (client, root) prevents marker flooding. |
| src/relay/agent-hook-envelope-publication.ts | New module; shedding loop, MAX_PENDING_PANES eviction, redelivery timer, and runFinalCapacityPass all look correct; MAX_PENDING_PANES is now enforced via the delete-then-set eviction loop at line 245. |
| src/relay/dispatcher.ts | Adds publishProducerNotification, producerRetentionBelowLowWater, ResponseOverCapacity fallback for oversized responses, and per-client notifyBulk targeting; all paths correctly avoid closing the connection on producer overload. |
| src/relay/fs-handler-file-read.ts | Terminal frame slot reservation via pendingTerminalFramesByClient correctly bounds concurrent terminal frames per client; slot released via settlement callback or finally block; no slot-leak path found. |
| src/shared/agent-hook-relay.ts | restoreShedStatusFields validates both digest and turn identity before restoring subagents; interactivePrompt and lastAssistantMessage deliberately not restored to avoid stale prose from an earlier turn. |
| src/relay/dispatcher-client-writer.ts | Minor changes; fixedFrameCapacity getter added for fixed-bulk lane; logic unchanged otherwise. |
| src/relay/relay-filesystem-watch-registry.ts | Trivial one-line fix; no issues. |
Reviews (4): Last reviewed commit: "fix(relay): prevent infinite redeploy on..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f876ac2a-8a7f-4590-8dc3-6389c39d1feb
📒 Files selected for processing (8)
src/main/ipc/ssh.test.tssrc/main/ssh/ssh-connection.test.tssrc/main/ssh/ssh-connection.tssrc/main/ssh/ssh-relay-session.tssrc/relay/dispatcher.tssrc/relay/relay-watcher-frame-chunking.test.tssrc/relay/relay.tstests/tools/benchmarks/terminal-perf-bench.mjs
🚧 Files skipped from review as they are similar to previous changes (5)
- src/relay/relay.ts
- src/main/ssh/ssh-relay-session.ts
- src/main/ssh/ssh-connection.ts
- src/main/ipc/ssh.test.ts
- src/main/ssh/ssh-connection.test.ts
ResponseOverCapacity should use -33008 to stay in the -33xxx range for relay protocol errors, not -32010.
|
@coderabbitai[bot] resolved |
|
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! You are interacting with an AI system. |
Replay is never retried, so it uses the control lane where overflow is fatal — the writer closes the client and reconnect reloads history rather than stranding a short buffer.
|
@coderabbitai[bot] resolved |
|
Tip For best results, initiate chat on the files or code changes.
You are interacting with an AI system. |
Charge reconnect attempts when connection restores mid-backoff, preventing infinite loop on transports that flap between states. Refactor control overflow handling to use entry property instead of WeakSet marker for clarity.
…ckpressure (stablyai#11999) * fix(ssh,relay): stop remote connections from being killed by backoff and frame caps Three independent connection killers found in the SSH/remote freeze audit. FINDING A - the reconnect ladder never escalated for post-handshake drops. scheduleReconnect() used the single published state.reconnectAttempt for both the delay index and the give-up test, and runReconnectAttempt() zeroed it before connecting (ssh.ts gates the relay redeploy on 0-at-connected). Every post-handshake drop therefore re-entered at 1000ms forever, ~3600 relay redeploys/hour, and 'reconnection-failed' was unreachable for a flapping host. New SshReconnectLadder splits the delay index (advanced by every retry) from the failure streak (advanced only by a failed handshake), so flaps back off while give-up semantics stay byte-identical to shipped. FINDING B - notify() closed the client whenever a frame exceeded the producer frame capacity, conflating a permanently un-sendable frame with transient backpressure. A 5000-event fs.changed is 425KB against a 49KB cap, so the watcher flood killed the link and re-killed on every reattach+replay. notify() now drops and logs once per generation; fs.changed is chunked to each sink's capacity with a control-lane overflow marker as the resync fallback; agent-hook envelopes shed lastAssistantMessage/interactivePrompt/subagents to fit. FINDING B2 - sendResponse routed >1MB responses to a lane whose admission ignores the frame cap and closed the client on rejection, so a large fs.listFiles dropped the SSH host. It now substitutes a JSON-RPC error so the request fails instead of the connection. Also moves fs.streamEnd/fs.streamError to the control lane so a terminal frame cannot be dropped by the producer-lane check. Co-authored-by: Orca <[email protected]> * fix(relay): stop the overflow marker from re-killing the link it protects Round-1 review fixes on the P0 freeze work. The control-lane overflow marker could reinstate the exact failure this P0 removes: dispatcher-client-writer closes the client when control-lane admission fails, and admitControl is the only lane that returns an error, so one marker per failing batch accumulated to the 256-frame/1MB bound and dropped the link. Markers are now deduped to one outstanding per (client, root), cleared on settle. Chunking also defeated the renderer's per-payload directory dedupe -- events are now stable-grouped by parent directory so one directory lands in one chunk -- and the halving walk overshot the byte minimum ~1.7x while the fast path paid three JSON encodes; both are fixed by publishing first and sizing from a measured bytes-per-event estimate. Agent-hook shedding now surrenders the blocking interactive prompt LAST rather than first, so a degraded envelope cannot strand a pane at state=waiting with no answerable question card. The dropped-notification log now distinguishes over-capacity from producer queue backpressure and no longer lets the first dropped method silence every other producer for the life of the connection. * fix(relay,ssh): keep status delivery and terminal frames from trading one freeze for another Round-2 review fixes. The round-0 change from close-on-rejection to silent drop removed the only redelivery path for agent.hook envelopes: they are fire-and-forget and the per-pane cache only replays on handler install, so a saturated link stranded a pane on a stale Working spinner until reconnect. Closing used to guarantee delivery by forcing that replay. Envelopes now publish per client and pend for bounded latest-wins redelivery when the producer queue rejects them. Shed fields are now named on the wire. The subagent roster is not cosmetic -- the renderer replaces rather than merges it, and hibernation gates on its length -- so an unmarked shed could sleep a live pane. fs.streamEnd rode the control lane because it must not be dropped, but that lane kills rather than drops. The stream's concurrency slot is now held until the terminal frame settles rather than until the fd closes, capping queued terminal frames well under the control budget; overflow costs one refused read instead of the connection. The watcher chunk walk now stops while producer retention sits past its reserve and degrades to a resync, so a 5000-event flood cannot fill the queue that interactive PTY traffic shares and stall every remote terminal. The reconnect ladder caps its flap-path delay so delay plus handshake timeout cannot cross the relay grace floor and let the remote daemon kill live PTYs. Also: the suppression key no longer embeds a NUL byte, which had made the file binary to git and grep; producerEnvelopeBudget no longer reports infinite capacity for a departed client; the drop logger no longer encodes a frame it will not log; and an over-capacity response substitution no longer settles as if the result had been delivered. * fix(relay,ssh): restore relay-shed status fields and scope backpressure per client Round 3 + 4 review fixes. Watcher chunking is now gated on the *client's* retention reserve rather than the dispatcher-wide one, so one stalled peer no longer forces a healthy client into a full file-tree resync. The relay-lost redeploy ladder no longer burns its 6-attempt budget while the SSH transport itself is down: it holds at the 15s step with a non-terminal status and rearms, so a laptop that slept past the ladder comes back instead of landing on a terminal "give up" banner. The shedFields wire marker had no consumer, so an agent-hook envelope whose subagent roster was dropped to fit the frame read as "roster cleared" on the Orca side: live child rows blanked and a done pane became hibernation-eligible while its teammates were still running. ingestRemote now restores shed fields from the cached payload (interactivePrompt deliberately excluded — a stale answerable question card is worse than none). Also: stream terminal-frame slots are counted per client, since the control queue they protect is per client; the chunking fast path no longer logs a drop for a batch it goes on to deliver in full; -32010 is now RelayErrorCode.ResponseOverCapacity. Test debt from the review: pending-pane eviction, per-client stream isolation, and the reconnect budget are now asserted rather than assumed; four fragile exact-byte pins dropped in favour of the tier comparisons that carry the requirement. * fix(relay,ssh): restore relay-shed status fields and scope backpressure - Oversized relay responses now fail their request instead of closing the connection, preventing one frame from killing every pane on the host - Restore subagent state for correct hibernation; don't resurrect stale prose across turns - Account for relay re-establishment and PTY reattach time in SSH flap delay caps - Only log drops of final unsendable envelopes, not temporary rejections during measurement probes - Fix watcher overflow marker release race when notification admission rejects without settlement; use precise byte counting for event batching * Restore relay-shed fields with digest validation and scoped backpressure Validate that shed subagent rosters match their wire digest and turn identity before restoration, preventing stale roster resurrection. Compact interactive prompts for waiting states instead of dropping them. Demote control-queue overflow to non-fatal rejection so clients can retry on capacity recovery, keeping the link alive during transient backpressure. * fix(relay): correct ResponseOverCapacity error code ResponseOverCapacity should use -33008 to stay in the -33xxx range for relay protocol errors, not -32010. * fix(relay): close client when pty.replay overflows control queue Replay is never retried, so it uses the control lane where overflow is fatal — the writer closes the client and reconnect reloads history rather than stranding a short buffer. * fix(relay): prevent infinite redeploy on flapping SSH transports Charge reconnect attempts when connection restores mid-backoff, preventing infinite loop on transports that flap between states. Refactor control overflow handling to use entry property instead of WeakSet marker for clarity. --------- Co-authored-by: Orca <[email protected]>
Summary
User impact
Remote workspaces and PTYs remain available through watcher floods, large filesystem responses, transient producer congestion, and repeated network flaps. A slow client no longer forces healthy peers to use its smaller frame capacity or resynchronize their file trees.
Agent status remains coherent when payloads must be reduced: active subagent state is restored safely, interactive prompts are compacted for waiting states, and stale shed data is not resurrected.
Implementation details
ResponseOverCapacityfor responses that cannot fit.Screenshots
No visual change.
Testing
pnpm run typecheck:nodeoxlintandoxfmtpnpm testpnpm buildAI Review Report
The review examined reconnect accounting, relay frame admission, producer/control-lane failure behavior, overflow-marker lifecycle, per-client isolation, terminal-frame settlement, agent-hook retry and shedding, stale-generation handling, and response-size failure semantics. Follow-up fixes added exact byte sizing, bounded marker suppression, per-client low-water checks, turn/digest validation, and explicit regression coverage.
Cross-platform compatibility was checked for macOS, Linux, and Windows. Runtime path grouping uses the existing cross-platform path resolver; no keyboard shortcuts, labels, UI behavior, or platform-specific shell construction were introduced. SSH-hosted and folder-workspace behavior remain in scope.
Security Audit
Reviewed remote event paths and JSON-RPC payloads as untrusted inputs, ensuring they are encoded within bounded frame budgets and cannot close the connection through an oversized producer frame. Oversized request responses now fail only the request. Shed agent state is restored only after matching the current turn and digest, reducing stale-state injection risk.
The change does not add dependencies, credentials, secret storage, or new command interpolation. No unresolved security follow-up was identified.
Notes
The main residual behavior is intentional fail-soft degradation: when a client cannot accept a watcher batch, it receives a bounded overflow resync marker rather than forcing the entire SSH connection to restart.