Skip to content

fix(remote-terminal): keep the stream stall deadline armed on unacknowledged credit - #17871

Merged
nwparker merged 4 commits into
mainfrom
fix/remote-terminal-read-wedge
Sep 2, 2026
Merged

nwparker merged 4 commits into
mainfrom
fix/remote-terminal-read-wedge

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​180 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​180
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​62 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​42

#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.ts disarmed 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:

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.

$ pnpm test src/renderer/src/runtime/remote-terminal-stream-watchdog.test.ts
  fails before, passes after

Post-review fixes

1. The re-charge path armed an unbounded self-rescheduling timer. flushOutputAcknowledgement -> acknowledgeOutput -> sendFrame throws -> handleClose() runs this.streams.clear() and stream.watchdog.dispose(); control then returns to the new stream.pendingAckBytes += bytes; scheduleOutputAcknowledgementFlush(stream), which arms a 4 ms timer on an unregistered stream whose watchdog is gone. Every later sendFrame returns false on !this.ready rather than throwing, so it re-charged and rescheduled forever, at 250 Hz, per stream.

queueOutputAcknowledgement already had the right guard (this.streams.get(stream.streamId) !== stream); the new path did not. Counting live fake timers after teardown, with sendBinary forced to throw on Ack:

before: pending timers after teardown: 1 -> +10s: 1 -> +70s: 1
after:  pending timers after teardown: 0 -> +10s: 0 -> +70s: 0
main:   pending timers after teardown: 0 -> +10s: 0 -> +70s: 0

Both guards now go through the existing isRegisteredStream() helper.

2. The production fix had no integration coverage. The three watchdog tests exercise createRemoteTerminalStreamWatchdog in isolation, so neither the runaway timer nor the recordOutputAcknowledged wiring was reachable from them. Added three specs that drive the real multiplexer flow:

  • the pending-timer count above (remote-runtime-terminal-parse-backpressure.test.ts);
  • a healthy stream stays alive once the transport takes the ACK for its parsed output — deleting the recordOutputAcknowledged call turns it red, because unacknowledgedBytes never drains and a working pane gets recovered at 30 s;
  • the deadline stays anchored while sibling frames keep settling — red against main's armDeliveryTimer, 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: null after client restart — live SSH terminal renders black."

"ptyId": null is not corruption — hydration nulls it on purpose (terminal-helpers.ts:26-32, contract stated at terminal-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 a replace-session patch, overwriting the id the file still held. The relay never inspects ptyId (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 when hasLivePty(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 and activeWorktreeIdsOnShutdown excludes 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 on isWebTerminalSurfaceTabId, 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 ptyId over a good persisted one. It spans session persistence, the SSH execution boundary (any such pass must treat a missing handle as unverifiable, 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

@pullfrog pullfrog 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.

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 — flushOutputAcknowledgement now 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Review finding: reproduced an unbounded self-rescheduling timer this PR introduces.

Forcing sendBinary to throw on the Ack opcode and counting live fake timers:

branch:  pending timers after teardown: 1 -> +10s: 1 -> +70s: 1
         (70s of fake time took 4.9s real, ~17,500 iterations)
main:    pending timers after teardown: 0 -> +10s: 0 -> +70s: 0

Path: flushOutputAcknowledgement -> acknowledgeOutput -> sendFrame throws -> handleClose() runs this.streams.clear() and stream.watchdog.dispose() -> control returns -> the new stream.pendingAckBytes += bytes; this.scheduleOutputAcknowledgementFlush(stream) arms a 4ms timer on an unregistered stream whose watchdog is already gone.

From then on sendFrame returns false on !this.ready rather than throwing, so it re-charges and reschedules forever, at 250 Hz, per stream, with nothing left that can stop it.

queueOutputAcknowledgement already has the correct guard:

this.streams.get(stream.streamId) !== stream

The new re-charge path does not. That is pullfrog 3901881711 verbatim, still unaddressed — and it is a regression introduced by this PR, not a pre-existing condition.

Second open item: the production fix lives in flushOutputAcknowledgement (the re-charge plus the recordOutputAcknowledged wiring) and has zero integration coverage. The three new tests exercise createRemoteTerminalStreamWatchdog in isolation, so the #11265 claim in the title is not what the tests encode.

Both are one guard and one test away from fixed.

@nwparker
nwparker force-pushed the fix/remote-terminal-read-wedge branch from 5bc102c to 876f603 Compare September 2, 2026 20:39
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

Next included review available in 3 minutes.

Check out review usage here.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: bc91f92b-4594-44e1-b8c3-83f119e705bf

📥 Commits

Reviewing files that changed from the base of the PR and between 1af05b43d62e3363b9ec08ff70d838e3c983f376 and 740f1c8.

📒 Files selected for processing (1)
  • src/renderer/src/i18n/locales/en.json
📝 Walkthrough

Walkthrough

The 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 1af05

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 a… Restructure the description using the repository template. Add the missing required sections and checklist items. For Visual Proof, state N/A with a brief reason if no visual or interaction change applies.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary fix: keeping the remote terminal stream stall deadline armed when acknowledgement credit remains unacknowledged.
Linked Issues check ✅ Passed The changes satisfy issue #11265 by keeping the watchdog active while delivery credit remains unacknowledged, anchoring the stall deadline to the oldest unsettled delivery, recovering failed acknowled…
Out of Scope Changes check ✅ Passed The production changes and tests are focused on remote terminal watchdog and acknowledgement behavior required by issue #11265. References to #12452 and #17743 explicitly state that no changes were ma…
Full details: Description check

Explanation

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 check

Explanation

The changes satisfy issue #11265 by keeping the watchdog active while delivery credit remains unacknowledged, anchoring the stall deadline to the oldest unsettled delivery, recovering failed acknowledgements, and adding integration coverage for these behaviors.

Full details: Out of Scope Changes check

Explanation

The production changes and tests are focused on remote terminal watchdog and acknowledgement behavior required by issue #11265. References to #12452 and #17743 explicitly state that no changes were made for those issues.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@pullfrog pullfrog 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.

✅ No new issues found. The prior ack-failure timer-leak concern is fixed via an isRegisteredStream guard, and the retry/record path is now covered by integration tests.

Reviewed changes

  • flushOutputAcknowledgement failure guard — re-charging a dropped stream is now gated on isRegisteredStream, so a transport write that throws and tears the stream down returns false without arming another flush timer.
  • queueOutputAcknowledgement refactor — switched the inline registration check to the shared isRegisteredStream helper and added a bytes <= 0 early-return.
  • New integration tests — parse-backpressure asserts the ack flush stops re-arming after a failed ACK tears the stream down; stall-recovery covers the keep-alive-on-ack and anchored-deadline paths.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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: 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.ts
  • src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts
  • src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts
  • src/renderer/src/runtime/remote-terminal-stream-watchdog.test.ts
  • src/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.

Comment on lines +165 to +166
emitOutput(stream.streamId, 'sibling frame that settles')
credits[1]?.()

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.

🎯 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.
@nwparker
nwparker force-pushed the fix/remote-terminal-read-wedge branch from 1af05b4 to ce4bcb4 Compare September 2, 2026 21:13
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.
@nwparker
nwparker merged commit 3a8f806 into main Sep 2, 2026
27 of 28 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
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.

[Bug]: Paired remote terminals silently stall with live TCP sockets; remote CLI RPC wakes them

1 participant