Repository navigation
fix(remote-terminal): keep the stream stall deadline armed on unacknowledged credit - #17871
Conversation
There was a problem hiding this comment.
Important
The stall-deadline fix is sound, but the ack-failure retry path in the flow controller can leak an unbounded timer when the transport write throws. See the inline comment.
Reviewed changes
remote-terminal-stream-watchdog.ts— splits the delivery-stall deadline into parse credit (outstandingDeliveryBytes) and unacknowledged credit (unacknowledgedBytes), and anchors the deadline to the oldest pending byte instead of re-arming it on every settle.remote-runtime-terminal-flow-controller.ts—flushOutputAcknowledgementnow records a successful ack to the watchdog and, on a failed send, re-charges the pending ack bytes and reschedules the flush instead of silently dropping them.remote-terminal-stream-watchdog.test.ts— three fake-timer tests pinning the anchored deadline, the stays-armed-while-unacknowledged behavior, and disarm once the ack reaches the transport.
ℹ️ The flow-controller retry/record path has no integration test
The three new tests exercise createRemoteTerminalStreamWatchdog in isolation. The actual production fix lives in flushOutputAcknowledgement — the failure re-charge plus the recordOutputAcknowledged wiring — and that integration is not covered. The existing remote-runtime-terminal-stall-recovery.test.ts never drives an ack-send failure, so the "read-only RPC unwedges it" regression this PR closes could return without a test noticing.
Technical details
# Cover the ack-failure integration
## Affected sites
- `src/renderer/src/runtime/remote-runtime-terminal-flow-controller.ts:101` — `flushOutputAcknowledgement` re-charge + `recordOutputAcknowledged` wiring, untested.
- `src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts` — existing harness that drives `subscribeTerminal` + `sendBinary` and could assert the retry.
## Required outcome
- A test that forces `acknowledgeOutput` to fail once (e.g. `sendBinary` stubbed to return a failed subscription write), then asserts the ack is retried and the watchdog stays armed until the ack succeeds.
## Suggested approach (optional)
- Extend the existing stall-recovery harness to stub a write failure on the first ack flush, then let the retry succeed, asserting `onTransportClose` is not called.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Review finding: reproduced an unbounded self-rescheduling timer this PR introduces. Forcing Path: From then on
this.streams.get(stream.streamId) !== streamThe new re-charge path does not. That is pullfrog Second open item: the production fix lives in Both are one guard and one test away from fixed. |
5bc102c to
876f603
Compare
|
Warning Review limit reachedNext included review available in 3 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 1af05b43d62e3363b9ec08ff70d838e3c983f376 and 740f1c8. 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe watchdog now tracks parsed output bytes until transport acknowledgement and uses an anchored delivery deadline. The flow controller extracts acknowledgement timer scheduling, records successful acknowledgements, and retries failed writes while the stream remains registered. Tests cover failed-write cleanup, acknowledgement-driven recovery, anchored stall deadlines, and watchdog disarming after transport acknowledgement. Merge Risk: 🔵 Low · up to The PR improves recovery from stalled remote terminals, but one regression test may not reliably verify sibling-frame settlement, and acknowledgements can retry while a registered stream is temporarily unable to send. The change is mergeable with explicit owner awareness and follow-up on the test and retry lifecycle. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the bug, root cause, scope, linked issue, testing, follow-up fixes, and regression risk. However, it does not follow the repository template and omits required sections such as Visual Proof or an explicit N/A statement, Testing checkboxes, AI Disclosure, Review, boundary confirmation, Notes, and Checklist. Full details: Linked Issues checkExplanation The changes satisfy issue Full details: Out of Scope Changes checkExplanation The production changes and tests are focused on remote terminal watchdog and acknowledgement behavior required by issue ✨ Finishing Touches 💡 1📝 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.
✅ No new issues found. The prior ack-failure timer-leak concern is fixed via an
isRegisteredStreamguard, and the retry/record path is now covered by integration tests.
Reviewed changes
flushOutputAcknowledgementfailure guard — re-charging a dropped stream is now gated onisRegisteredStream, so a transport write that throws and tears the stream down returnsfalsewithout arming another flush timer.queueOutputAcknowledgementrefactor — switched the inline registration check to the sharedisRegisteredStreamhelper and added abytes <= 0early-return.- New integration tests —
parse-backpressureasserts the ack flush stops re-arming after a failed ACK tears the stream down;stall-recoverycovers the keep-alive-on-ack and anchored-deadline paths.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
876f603 to
1af05b4
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 043c9aba-5190-4f9d-9445-7be537a4c21a
📥 Commits
Reviewing files that changed from the base of the PR and between d8ca420 and 1af05b43d62e3363b9ec08ff70d838e3c983f376.
📒 Files selected for processing (5)
src/renderer/src/runtime/remote-runtime-terminal-flow-controller.tssrc/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.tssrc/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.tssrc/renderer/src/runtime/remote-terminal-stream-watchdog.test.tssrc/renderer/src/runtime/remote-terminal-stream-watchdog.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| emitOutput(stream.streamId, 'sibling frame that settles') | ||
| credits[1]?.() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use a cumulative output seq and require the sibling credit.
emitOutput assigns seq from each text length. The second frame regresses from 31 to 26, although output seq is a high-water value. Sequence handling can reject this frame, and credits[1]?.() then lets the test pass without a settled sibling delivery.
Pass 31 + 26 as the second frame sequence. Assert that two credits exist before settling the second credit.
Proposed test fix
- emitOutput(stream.streamId, 'frame the renderer never parses')
+ const firstText = 'frame the renderer never parses'
+ emitOutput(stream.streamId, firstText)
await vi.advanceTimersByTimeAsync(REMOTE_TERMINAL_DELIVERY_STALL_TIMEOUT_MS - 5_000)
- emitOutput(stream.streamId, 'sibling frame that settles')
- credits[1]?.()
+ const siblingText = 'sibling frame that settles'
+ emitOutput(stream.streamId, siblingText, firstText.length + siblingText.length)
+ expect(credits).toHaveLength(2)
+ credits[1]!()- function emitOutput(streamId: number, text: string): void {
+ function emitOutput(streamId: number, text: string, seq = text.length): void {
callbacks?.onBinary(
encodeTerminalStreamFrame({
opcode: TerminalStreamOpcode.Output,
streamId,
- seq: text.length,
+ seq,…wledged credit A paired-runtime terminal could stall silently with a live socket, a live PTY and no transport error (#11265). Two compounding defects on the read side: - The stream watchdog re-armed its 30s delivery deadline from zero on every settled delivery, so sibling traffic postponed the verdict indefinitely, and it cleared the timer entirely once renderer parse credit hit zero. Re-arming required inbound output -- the exact thing an exhausted host ACK window stops -- so once an ACK went missing nothing could ever detect the stall. The deadline is now anchored to the oldest unsettled delivery and stays armed while delivered bytes remain unacknowledged to the host. - flushOutputAcknowledgement zeroed pendingAckBytes before knowing the ACK frame was accepted, permanently shrinking the host's send window. Unsent bytes are re-charged and the flush timer re-armed. Recovery still reports onTransportClose({recoverable:true}); no path claims the PTY exited.
…iled send dropped A failing ACK send tears the stream down inside sendFrame, so the re-charge path armed a 4ms timer on an unregistered stream whose watchdog was already disposed; every later send returned false on !ready and rescheduled again. Also adds the missing integration coverage for the real ack -> watchdog flow.
1af05b4 to
ce4bcb4
Compare
The branch's en.json predates #18245, which added both the translate() call and its key. Rebasing took the branch copy wholesale, silently dropping the key and failing verify:localization-catalog.
…wledged credit (stablyai#17871) * fix(remote-terminal): keep the stream stall deadline armed on unacknowledged credit A paired-runtime terminal could stall silently with a live socket, a live PTY and no transport error (stablyai#11265). Two compounding defects on the read side: - The stream watchdog re-armed its 30s delivery deadline from zero on every settled delivery, so sibling traffic postponed the verdict indefinitely, and it cleared the timer entirely once renderer parse credit hit zero. Re-arming required inbound output -- the exact thing an exhausted host ACK window stops -- so once an ACK went missing nothing could ever detect the stall. The deadline is now anchored to the oldest unsettled delivery and stays armed while delivered bytes remain unacknowledged to the host. - flushOutputAcknowledgement zeroed pendingAckBytes before knowing the ACK frame was accepted, permanently shrinking the host's send window. Unsent bytes are re-charged and the flush timer re-armed. Recovery still reports onTransportClose({recoverable:true}); no path claims the PTY exited. * fix(remote-terminal): stop rearming the ack flush for a stream the failed send dropped A failing ACK send tears the stream down inside sendFrame, so the re-charge path armed a 4ms timer on an unregistered stream whose watchdog was already disposed; every later send returned false on !ready and rescheduled again. Also adds the missing integration coverage for the real ack -> watchdog flow. * fix(i18n): restore the activity-options key the rebase dropped The branch's en.json predates stablyai#18245, which added both the translate() call and its key. Rebasing took the branch copy wholesale, silently dropping the key and failing verify:localization-catalog. * fix(i18n): union en.json with main so the rebase cannot drop keys

#11265 — fixed
"Paired remote terminals silently stall with live TCP sockets; a read-only CLI RPC (
orca status) wakes them." No offline indicator, no transport error, bytes sitting unread in the receive queue — and an unrelated RPC unwedges it.That last detail is the tell: something was gated on activity rather than on a timer.
remote-terminal-stream-watchdog.tsdisarmed its delivery-stall deadline on a path where credit went unacknowledged, so the one thing that could have noticed the stall stood down, and only incidental traffic could restart it.This is the third instance this week of the same family — a component that suppresses its own detection machinery and can then never recover:
SshChannelMultiplexergated its dead-link check on writer saturation with no bound, so a half-open link wedged forever (fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817).WebRuntimeConnectionHeartbeatarmed its dead-socket deadline only if the probe was successfully sent, so an unsendable probe disarmed the only branch that could declare the socket dead (fix(web): declare a socket dead even when its probe cannot be sent #17838).That is three independent transports making the same mistake, which is the argument for #17823 (unify the liveness policy) rather than fixing it a fourth time.
Post-review fixes
1. The re-charge path armed an unbounded self-rescheduling timer.
flushOutputAcknowledgement->acknowledgeOutput->sendFramethrows ->handleClose()runsthis.streams.clear()andstream.watchdog.dispose(); control then returns to the newstream.pendingAckBytes += bytes; scheduleOutputAcknowledgementFlush(stream), which arms a 4 ms timer on an unregistered stream whose watchdog is gone. Every latersendFramereturnsfalseon!this.readyrather than throwing, so it re-charged and rescheduled forever, at 250 Hz, per stream.queueOutputAcknowledgementalready had the right guard (this.streams.get(stream.streamId) !== stream); the new path did not. Counting live fake timers after teardown, withsendBinaryforced to throw onAck:Both guards now go through the existing
isRegisteredStream()helper.2. The production fix had no integration coverage. The three watchdog tests exercise
createRemoteTerminalStreamWatchdogin isolation, so neither the runaway timer nor therecordOutputAcknowledgedwiring was reachable from them. Added three specs that drive the real multiplexer flow:remote-runtime-terminal-parse-backpressure.test.ts);recordOutputAcknowledgedcall turns it red, becauseunacknowledgedBytesnever drains and a working pane gets recovered at 30 s;main'sarmDeliveryTimer, which re-armed a full 30 s on every sibling settle and so postponed the wedge detection forever.#12452 — already fixed on current main; no change made
"Terminal keyboard input dies after renderer reattach; replay guard detects wedged write pipeline." Verified fixed. A secondary
writable:ask in the issue was deliberately left alone rather than bundled in.#17743 — root-caused, deliberately NOT fixed
"Restored workspace tab keeps
ptyId: nullafter client restart — live SSH terminal renders black.""ptyId": nullis not corruption — hydration nulls it on purpose (terminal-helpers.ts:26-32, contract stated atterminal-session-row-hydration.ts:36-40). The damage is that the persistence subscriber fires on any store change, so the post-hydration store — nulled, before any pane has bound a PTY — is uploaded to the relay as areplace-sessionpatch, overwriting the id the file still held. The relay never inspectsptyId(workspace-session-handler.ts:122), so it cannot defend it.Why no surviving identity: the only Gate-1 survivor for SSH is
remoteSessionIdsByTabId, emitted only whenhasLivePty(tab.id) || (!tab.ptyId && lastKnown[tab.id]). On a fresh process where the tab never rebound this run, both are empty, so nothing is emitted andactiveWorktreeIdsOnShutdownexcludes the worktree too.Why nothing corrects it at startup: the legacy-worker reconciler defers every SSH candidate when
connectionId === undefined— which is exactly how startup calls it (index.ts:1057-1064). SSH candidates only reconcile later on relay-ready, and only for orchestration-dispatch rows, never a plain user tab. Orphan adoption is claim-driven and needs the client to already supply the ptyId, so it cannot bootstrap a lost binding.A pane-key rebind does exist (
web-session-terminal-orphan-recovery-pane.ts:127-147) but is unreachable here: its surface is gated onisWebTerminalSurfaceTabId, and its identity is parsed as a remote-runtime pty id. A desktop SSH-host tab is neither.Net: the client erases its own reattach identity during hydration, republishes the erasure over the good persisted one, and has no startup pass that consults the relay's live handle registry to re-derive it.
The fix is a startup reconciliation by pane key for SSH-backed tabs — ungating one of the two existing reconcilers rather than adding a third — plus not republishing a hydration-nulled
ptyIdover a good persisted one. It spans session persistence, the SSH execution boundary (any such pass must treat a missing handle asunverifiable, never evidence to retire the tab), and the relay wire. Doing that without proper tests would be worse than this handoff, so it is left for its own change.Fixes #11265
Refs #12452, #17743
ELI5
Paired remote terminals could silently stall with the network connection still alive — bytes sitting unread, no error shown — and an unrelated command would wake them up.
User-facing regression risk