Skip to content

fix(ssh): start the pty.spawn deadline when its frame reaches the wire - #17748

Closed
nwparker wants to merge 1 commit into
mainfrom
nwparker/crashfix-g5-ssh-pty-spawn
Closed

nwparker wants to merge 1 commit into
mainfrom
nwparker/crashfix-g5-ssh-pty-spawn

Conversation

@nwparker

@nwparker nwparker commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​589 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​583
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​148 $\color{#cf222e}{\Huge{\mathbf{−}}}$​38 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​110

What

A relay RPC's timeout was armed at enqueue, not when its frame actually reached the wire.

SshChannelMultiplexer.request() called setTimeout(timeoutMs) and then handed the frame to SshMultiplexerTransportWriter. While that writer is saturated the control lane is parked (pump() early-returns), and the dead-link check that would otherwise rescue a stuck request is deliberately suppressed in exactly that state. So a pty.spawn frame could burn its entire 30 s budget sitting in the queue, never having been written. The pane settled the connect as timed out and re-armed a retry for a spawn that had never started.

The change:

  • New opt-in request option budgetStartsAtWire on SshChannelMultiplexer.request(). Opt-in rather than default, so callers that deliberately chose a short fail-fast timeoutMs keep it.
    • The queue wait gets its own bound, sshRelayQueueWaitMs(timeoutMs) = max(timeoutMs, 30_000) — never below the caller's own budget, so opting in can never shorten a call.
    • The response budget is armed fresh from the writer's per-request settlement callback, so a stall that parks one frame cannot suspend the deadline of a request already out on the wire, and a writer that never drains still surfaces a timeout.
    • The two phases produce distinguishable errors: timed out after Nms without reaching the wire vs. the existing timed out after Nms.
  • pty.spawn opts in (a spawn that never reached the wire started nothing and retries safely), and so do both pty.getCapabilities probes that gate it — supportsClaims (agentSessionEnsure) and supportsCreateOperations (agentSessionCreateOperationId). Without that, the 5 s probe expires in the same queue first, pty.spawn is never enqueued, and the spawn's wire-started budget never engages on the first spawn of a connection.
  • New src/shared/ssh-relay-request-budget.ts exports sshRelayQueueWaitMs / sshRelayRequestWorstCaseMs (functions of the caller's budget) rather than one fixed constant, plus SSH_PTY_CONNECT_WORST_CASE_MS, which sums the whole connect sequence: two probes + spawn + the pty.shutdown that cleans up a spawn whose claim failed validation. The renderer backstops DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS and TRANSPORT_CONNECT_SETTLE_GRACE_MS now derive from that one number.

Fix evidence

All output below is verbatim from this worktree.

Before — the new tests fail against pre-change ssh-channel-multiplexer.ts

src/main/ssh/ssh-channel-multiplexer.ts restored to its merge-base blob (git show 872bd51d479:...), everything else at the branch tip:

$ pnpm test src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts

     × does not charge the response budget to a request still parked in the writer 5ms
     × starts the response budget when the frame reaches the wire 1ms
     × charges only the post-flush budget to a request that saturated the writer itself 0ms
     × bounds the flush wait so a writer that never drains still times out 1ms
     × bounds the queue wait at the advertised wait for a long caller budget 2ms
     × still fails a parked request when the link is genuinely lost 1ms
     × reaches the wire with the first spawn of a connection whose writer is saturated 4ms
     × settles the whole claimed connect sequence inside the connect worst case 2ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 8 ⎯⎯⎯⎯⎯⎯⎯
 Test Files  2 failed (2)
      Tests  8 failed | 5 passed (13)

The core assertion — a parked request must not be charged the response budget:

 FAIL  src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts > SshChannelMultiplexer request deadlines under writer saturation > does not charge the response budget to a request still parked in the writer
AssertionError: expected true to be false // Object.is equality

- Expected
+ Received

- false
+ true

 ❯ src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts:132:29
    130|
    131|     expect(mux.isDisposed()).toBe(false)
    132|     expect(state.settled()).toBe(false)
       |                             ^

And the whole-connect case, driving the real SshPtyProvider over a saturated MultiplexerTransport, produced an unhandled execution_owner_unavailable because the gating probe died in the queue and the spawn was never dispatched:

⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯

Vitest caught 1 unhandled error during the test run.

⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯
Error: execution_owner_unavailable
 ❯ SshPtyProvider.spawn src/main/providers/ssh-pty-provider.ts:115:13
    113|     if (opts.agentSessionCreateOperationId && !supportsCreateOperation…
    114|       // Why: host routing owns legacy selection; a changed relay must…
    115|       throw new Error('execution_owner_unavailable')
       |             ^

Before — the perf-audit finding, reproduced independently

The perf audit claimed SSH_PTY_CONNECT_WORST_CASE_MS counted only one capability probe while SshPtyProvider.spawn() issues two (ssh-pty-provider.ts:84 and :107, independently cached in SshAgentSessionCapabilities, and orca-runtime.ts:31058-31072 sets both launch flags together). I extended the worst-case test to set both flags and ran it against the branch tip before touching the constant:

 FAIL  src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts > SSH pane connect over a saturated writer > settles the whole claimed connect sequence inside the connect worst case
AssertionError: expected 159994 to be less than 125000
 ❯ src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts:220:24
    218|
    219|     await expect(outcome).resolves.toBe('execution_owner_unavailable')
    220|     expect(Date.now()).toBeLessThan(SSH_PTY_CONNECT_WORST_CASE_MS)
       |                        ^

 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)

Confirmed the audit's exact numbers (159994 measured vs. 125000 claimed). Fixed by summing two probe worst cases:

$ node -e "const P=5000,F=30000,R=30000;const q=t=>Math.max(t,F),w=t=>q(t)+t;
           console.log('probe worst',w(P),'spawn worst',w(R),'connect worst',2*w(P)+w(R)+R)"
probe worst 35000 spawn worst 60000 connect worst 160000

After — final runs at the committed tree

$ pnpm test src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts src/main/providers/ssh-pty-provider-agent-session-create-operation.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts

 Test Files  5 passed (5)
      Tests  41 passed (41)
   Start at  15:04:02
   Duration  2.39s

Full surrounding suites:

$ pnpm test src/main/ssh src/main/providers

 Test Files  206 passed | 3 skipped (209)
      Tests  2614 passed | 21 skipped (2635)
   Start at  15:04:08
   Duration  10.55s

$ pnpm test src/renderer/src/components/terminal-pane

 Test Files  415 passed (415)
      Tests  4038 passed (4038)
   Start at  15:04:19
   Duration  21.30s

Gates:

$ pnpm run check:code-quality:changed
code quality: 0 new finding(s) across 10 changed file(s).
type-aware code quality: 0 new finding(s) across 10 changed file(s).
React Doctor: 0 new finding(s) across 10 changed file(s).
Changed-code quality gate passed since 872bd51d479e.

$ pnpm tc; echo "EXIT=$?"
$ pnpm run typecheck
$ node config/scripts/run-typecheck-projects-in-parallel.mjs
EXIT=0

$ npx oxfmt --check <changed files>
All matched files use the correct format.

Evidence I do NOT have

  • No Windows repro, and no Windows exit codes. Everything above ran on macOS (Darwin 25.3.0). The originating crash report is not reproduced here as a native crash; the defect is reproduced as a deterministic fake-timer simulation of a saturated writer.
  • No real-SSH end-to-end run. The saturated writer is a test transport whose write() returns false; I did not congest an actual relay link.
  • No before/after UI capture of a pane that retried a never-dispatched spawn.

ELI5

Imagine mailing a letter that must be answered in 30 minutes. The old code started the 30-minute clock the moment you dropped the letter in your outbox — not when the mail carrier actually picked it up. If the outbox was jammed (the network write buffer was full), the letter sat there, the 30 minutes ran out, and you declared "no reply!" and mailed a duplicate — even though the first letter had never left the house.

Now, for the letters where a duplicate would be dangerous (starting a terminal on a remote machine), the clock starts when the carrier picks it up. The time spent jammed in the outbox has its own separate, bounded limit — so a permanently jammed outbox still fails, it just fails saying "never got picked up" instead of pretending it was ignored. Every letter is timed individually, so one jammed letter can't freeze the clock on letters already in transit.

Trade-offs

Real, user-facing, and worth reading:

  1. Worst-case SSH pane connect goes from ~31 s to ~161 s before the renderer gives up and retries. DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS moves from 31_000 to SSH_PTY_CONNECT_WORST_CASE_MS + 1_000 = 161_000. On a genuinely dead-but-not-closed link where the writer is saturated, a user now stares at a connecting pane for up to ~2m40s instead of ~30s. That is the direct cost of not retrying a spawn that may have actually started: the old fast failure was fast because it was wrong. There is no cheaper way to distinguish "never sent" from "sent, unanswered" while the writer is parked and the dead-link detector is standing down.

  2. TRANSPORT_CONNECT_SETTLE_GRACE_MS grows the same way (60 s → 160 s), and its slack shrank to zero. It is now set exactly equal to the connect worst case rather than exceeding it. It is still a correct upper bound (the measured worst path is 159994 ms against a 160000 ms bound), but it is a 6 ms margin, not a comfortable one. Practical effect: input-triggered recovery on a wedged pane is suppressed for up to 160 s instead of 60 s.

  3. The two gating capability probes now wait out the writer queue too. Each pty.getCapabilities can now take up to 35 s (30 s queue + 5 s response) instead of 5 s flat. This only bites when the writer is saturated — on a healthy link the frame is written synchronously and the response budget is still 5 s — but it does mean a relay that is reachable-but-congested delays capability detection rather than falling back to legacy behavior quickly.

  4. Two new latency knobs that can drift. SSH_PTY_CONNECT_CAPABILITY_PROBES = 2 is a hand-maintained count of probe call sites in SshPtyProvider.spawn(). If a third gating probe is ever added and that constant is not bumped, the backstops silently understate the worst case again — exactly the bug fixed in this PR. The worst-case test in ssh-pty-provider-saturated-writer-connect.test.ts asserts expect(probeIds).toHaveLength(2) and drives the real provider, so a third probe should fail it, but that is a test-level guard, not a structural one.

  5. budgetStartsAtWire is opt-in. Every other relay caller keeps the old enqueue-started deadline and remains vulnerable to the same class of premature timeout. That is deliberate — making it the default silently gave every short fail-fast caller up to +30 s (this was caught and rejected in adversarial round 2) — but it means the fix is scoped to the spawn path, not to the multiplexer generally.

Adversarial review

4 rounds. This hit the round cap; it did not converge to a clean round. Round 4 still returned two majors (both fixed), and a separate perf audit afterwards returned a further confirmed major that was also fixed here — so the last review pass over this code found real defects, and no reviewer has since signed off on the current tree.

Round 1 — [blocker] ssh-channel-multiplexer.ts: the original design used parkRequestDeadlines()/resumeRequestDeadlines(), which suspended every pending request's deadline (including requests whose frame had already reached the wire), and the 120 s bound was per saturation episode — a writer flapping saturated/drained (the normal state under sustained pty.data) re-armed the grace on every cycle, so deadlines could be suspended without limit. Reproduced with a probe: a git.status request already on the wire, then 200 × {saturate → advance 30 s → drain} gave settled=false, disposed=false after 6,000,000 ms simulated. [major] ssh-agent-session-create-operation.ts: raising the pty.spawn budget to 120 s broke the documented coupling with the renderer's DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS = 31_000, which had been left untouched. → Both confirmed. The global park/resume design was abandoned and rewritten as a per-request wire-started budget; the renderer backstop was made to derive from the same shared budget module.

Round 2 — [blocker]: the new queue-wait bound was a fixed 30 s even when the caller asked for a much larger budget, so any request with timeoutMs > 30_000 would newly fail at 30 s if parked — a failure mode that did not exist before. [major]: the wire-started behavior was the default, with hardDeadline as an opt-out that only teardown ever passed, so every caller that deliberately chose a short fail-fast timeoutMs silently gained up to +30 s. → Both confirmed, neither rejected. One root cause. Inverted to opt-in (budgetStartsAtWire), and made the queue bound scale with the caller's budget: sshRelayQueueWaitMs(t) = max(t, 30_000).

Round 3 — [major] ssh-relay-request-budget.ts: SSH_RELAY_REQUEST_WORST_CASE_MS was hardcoded at FLUSH + REQUEST = 60_000, but for an opted-in caller with a non-default timeoutMs the true worst case is max(timeoutMs, 30s) + timeoutMs — e.g. 130_000 for timeoutMs: 130_000 — and the change's own test blessed exactly that shape. [major]: the branch's HEAD commit still contained the abandoned round-1 design and described it in its message, while the real fix was uncommitted and its new module untracked. → Both valid, both fixed. The fixed constant became the function sshRelayRequestWorstCaseMs(timeoutMs); the commit was rewritten to match the shipped design.

Round 4 — [major] ssh-pty-provider.ts: the gating pty.getCapabilities probe (5 s, not opted into budgetStartsAtWire) failed first under the very saturation the fix targets, so pty.spawn was never enqueued and the wire-started budget never engaged on the first spawn of a connection. Reproduced verbatim by driving the real SshPtyProvider over a saturated MultiplexerTransport: { e: 'execution_owner_unavailable' } with frames ['pty.data', 'pty.getCapabilities#1', 'rpc.cancel'] — no pty.spawn. [major] pty-connect-limits.ts: TRANSPORT_CONNECT_SETTLE_GRACE_MS (60 s) was strictly less than the connect worst case it claimed to cover (5 s probe + 60 s spawn = 65 s), and the new comment asserted the opposite. → Both valid and reproduced, both fixed. Nothing rejected. The probes opt in, and SSH_PTY_CONNECT_WORST_CASE_MS was introduced to size the grace from the whole sequence.

What remains open at the cap

  • No clean review round was ever achieved. Rounds 1–4 each surfaced at least one blocker or major, and the post-round-4 perf audit surfaced another (see below). The rate of findings was not obviously decaying; a 5th round would plausibly find more.
  • The probe count is a magic 2 (trade-off Add Ctrl+Click to open links in terminal #4). Structurally, the worst case should be derived from the provider rather than hand-counted.
  • TRANSPORT_CONNECT_SETTLE_GRACE_MS has ~0 ms of engineered slack (trade-off Fix Ctrl+Backspace not deleting word in terminal #2). It is correct but brittle; a future call added anywhere in the connect sequence invalidates it.
  • The connect latency regression in trade-off Linux support #1 (~31 s → ~161 s) was never reviewed as a product decision, only as a correctness one.

Perf review

A performance audit was run over the worktree (branch e31e7e167e5 + the then-uncommitted work), with all measurements taken in-tree and scratch files removed afterwards.

F1 — CONFIRMED, and fixed in this PR. SSH_PTY_CONNECT_WORST_CASE_MS understated the real connect by 35 s. src/shared/ssh-relay-request-budget.ts:43 summed one capability probe, but SshPtyProvider.spawn() issues two independent pty.getCapabilities calls — supportsAgentSessionClaims() (ssh-pty-provider.ts:84, gated on agentSessionEnsure) and supportsAgentSessionCreateOperations() (ssh-pty-provider.ts:107, gated on agentSessionCreateOperationId) — and orca-runtime.ts:31058-31072 sets both flags on the same launch. Both now opt into budgetStartsAtWire, so each can spend sshRelayRequestWorstCaseMs(5_000) = 35 s. Measured by extending the worst-case test with both flags set (two probe ids observed on the wire):

AUDIT_ELAPSED 159994   CONSTANT 125000   OUTCOME execution_owner_unavailable
AssertionError: expected 159994 to be less than 125000

At the audited state DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS was 126,000 ms, so it would fire ~34 s before the connect settled — the pane settles timed-out, the retry re-arms, and a second spawn is dispatched. That is precisely the defect this PR exists to remove; at the audited state it had been moved from 31 s to 126 s, not eliminated.

Resolution in this PR: I independently reproduced F1 (identical 159994 / 125000 numbers, quoted verbatim under Fix evidence), then fixed it by counting both probes in SSH_PTY_CONNECT_WORST_CASE_MS (now 160,000 ms, backstop 161,000 ms) and by permanently strengthening ssh-pty-provider-saturated-writer-connect.test.ts to set both launch flags and assert probeIds has length 2 — so the audit's exact scenario is now a standing regression test rather than a one-off probe. The suite passes.

Net perf posture: this change adds no per-frame CPU or allocation work on the hot path. The only per-request cost is one extra clearTimeout + setTimeout for opted-in requests when the writer settles their frame, and a closure capture on the settlement callback — both bounded by the number of in-flight pty.spawn/pty.getCapabilities calls, which is at most a handful per connection. It does not touch pty.data, the writer's pump() loop, or any streaming path. The cost is entirely in latency budgets under an already-degraded link, quantified in Trade-offs #1–#3.

A request's deadline was armed at enqueue, before the frame was handed to
SshMultiplexerTransportWriter. While the writer is saturated the control lane
is parked (pump() early-returns), so a pty.spawn frame could sit in the queue
for its whole budget without ever reaching the wire, and the dead-link check
that would otherwise rescue it is deliberately suppressed in exactly that
state. The pane then settled the connect as timed out and retried a spawn that
had never started.

Add an opt-in `budgetStartsAtWire` request option instead of changing every
caller: the queue wait gets its own bound (never below the caller's own budget,
so opting in cannot shorten a call), and the response budget is armed fresh
from the writer's per-request settlement callback. Per-request, so a stall that
parks one frame cannot suspend the deadline of a request already out on the
wire, and a writer that never drains still surfaces a timeout.

pty.spawn opts in — a spawn that never reached the wire started nothing and
retries safely — and so do the two pty.getCapabilities probes that gate it
(supportsClaims, supportsCreateOperations). Without them the probe expires in
the same queue first and pty.spawn is never enqueued at all, so the spawn's
own wire-started budget never engages on the first spawn of a connection.

The resulting worst case is a function of the caller's budget, so
src/shared/ssh-relay-request-budget.ts exports sshRelayQueueWaitMs and
sshRelayRequestWorstCaseMs rather than one fixed number. SSH_PTY_CONNECT_-
WORST_CASE_MS sums the whole connect sequence — both probes, the spawn, and
the shutdown that cleans up a spawn whose claim failed validation — because
both probes have independent cache entries and a launch that asks for a claim
and a create-operation sends both. The pane-connect backstops
(DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS,
TRANSPORT_CONNECT_SETTLE_GRACE_MS) size themselves from that one number.
@greptile-apps

greptile-apps Bot commented Aug 31, 2026

Copy link
Copy Markdown

Greptile Summary

The PR gives selected SSH relay RPCs separate queue and response budgets so pty.spawn and its capability probes do not expire before reaching the wire. It also centralizes the resulting connect limits and updates renderer retry/recovery backstops.

  • Adds per-request wire-settlement deadline arming to the SSH channel multiplexer.
  • Opts both agent-session capability probes and PTY spawn into the new behavior.
  • Derives renderer connect deadlines from the combined probe, spawn, and cleanup budgets.
  • Adds saturation and retry regression coverage across the main and renderer processes.

Confidence Score: 4/5

The PR appears safe to merge, with a non-blocking maintainability issue in the hand-maintained capability-probe count used to size renderer deadlines.

The two-phase multiplexer deadlines and current spawn sequence are coherently bounded and guarded against late settlement, but future probe additions require synchronized manual updates to avoid understating the connect window.

Files Needing Attention: src/shared/ssh-relay-request-budget.ts

Important Files Changed

Filename Overview
src/main/ssh/ssh-channel-multiplexer.ts Adds an opt-in two-phase request deadline with guarded timer rearming when each frame reaches the transport.
src/main/providers/ssh-agent-session-create-operation.ts Applies wire-started budgets to create-operation capability detection and PTY spawning.
src/main/providers/ssh-agent-session-claim-validation.ts Applies the queue-safe request budget to the claim-capability probe.
src/shared/ssh-relay-request-budget.ts Centralizes request and connect limits, but the full-connect calculation depends on a manually synchronized probe count.
src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts Resizes retry settlement and input-recovery grace periods from the shared SSH connect bound.
src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts Exercises queue saturation, per-request settlement, cancellation, connection loss, and long/short timeout behavior.
src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts Covers first-connect capability gating and the complete claimed-spawn worst-case sequence under writer saturation.

Reviews (1): Last reviewed commit: "fix(ssh): start the pty.spawn deadline w..." | Re-trigger Greptile

// supportsClaims (agentSessionEnsure) then supportsCreateOperations
// (agentSessionCreateOperationId) — and a launch that asks for both sends both.
const SSH_PTY_CONNECT_CAPABILITY_PROBES = 2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Hand-maintained probe count

SSH_PTY_CONNECT_CAPABILITY_PROBES duplicates the number of probes in SshPtyProvider.spawn(), so adding another probe without updating this constant understates the renderer backstops and makes retry or recovery run while that connect is still active. Please derive the bound structurally from the connect sequence or otherwise keep the count coupled to it.

@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The changes add shared SSH relay request and PTY connection budgets. The channel multiplexer supports deadlines that start when frames reach the wire and reports bounded pre-wire flush timeouts. PTY capability probes and spawn requests use these deadlines and shared constants. New tests cover saturated writers, queue timing, connection loss, and PTY connection sequences. Renderer retry and transport grace limits now use the shared pane connect budget.

Merge Risk: 🟡 Moderate · up to a557b

The PR changes PTY deadlines so a queued spawn can time out before transmission, but the original frame may still be sent later while cancellation is queued behind it. A retry could therefore create an untracked or duplicate remote PTY, so the change is not merge-ready until queued requests are suppressed or equivalent idempotency is enforced.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives detailed implementation, rationale, testing, trade-offs, and limitations. However, it omits required template sections, including Linked Issue with a real issue reference, `Vis… Add all required template sections. Include a valid linked issue under Fixes #, state N/A with a reason under Visual Proof if no UI change exists, complete the testing checklist, provide AI disclosure details when applicable, complete…
Docstring Coverage ⚠️ Warning Docstring coverage is 17.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 10 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 summarizes the primary change: starting the pty.spawn deadline when its frame reaches the wire.
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.
Full details: Description check

Explanation

The description gives detailed implementation, rationale, testing, trade-offs, and limitations. However, it omits required template sections, including Linked Issue with a real issue reference, Visual Proof with N/A and a reason, the testing checklist, AI disclosure, review sections, and the final checklist.

Resolution

Add all required template sections. Include a valid linked issue under Fixes #, state N/A with a reason under Visual Proof if no UI change exists, complete the testing checklist, provide AI disclosure details when applicable, complete the review and agent-skill sections, and complete the final checklist.

  • Fix all pre-merge checks with AI
✨ 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.

@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: 03318c68-61e6-4e32-9d6d-0858a1258ac2

📥 Commits

Reviewing files that changed from the base of the PR and between 18e8fe4 and a557b40.

📒 Files selected for processing (10)
  • src/main/providers/ssh-agent-session-claim-validation.ts
  • src/main/providers/ssh-agent-session-create-operation.ts
  • src/main/providers/ssh-pty-provider-agent-session-create-operation.test.ts
  • src/main/providers/ssh-pty-provider-saturated-writer-connect.test.ts
  • src/main/ssh/ssh-channel-multiplexer-saturation-deadline.test.ts
  • src/main/ssh/ssh-channel-multiplexer.ts
  • src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts
  • src/shared/ssh-relay-request-budget.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +309 to +312
expire(
budgetStartsAtWire
? sshMuxWriteFlushTimeoutError(method, queueWaitMs)
: sshMuxRequestTimeoutError(method, timeoutMs)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Suppress or revoke the queued request on a pre-wire timeout.

When budgetStartsAtWire expires, the pending state is removed and rpc.cancel is enqueued, but the original pty.spawn frame remains in the FIFO control lane. The relay can therefore receive cancellation before the spawn exists and later execute the spawn after the caller has already timed out. A retry can create an untracked or duplicate PTY.

Make writer entries cancellable or tombstone them before rejecting the request, and add a regression that drains a timed-out queue and verifies that no pty.spawn frame is sent.

📍 Affects 2 files
  • src/main/ssh/ssh-channel-multiplexer.ts#L309-L312 (this comment)
  • src/main/providers/ssh-agent-session-create-operation.ts#L75-L75

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

ℹ️ One rough edge worth a look — the fix logic is sound and the coverage is strong, but a generic connect grace is now sized to a direct-SSH-specific worst case.

Reviewed changes

  • Relay budget module — ssh-relay-request-budget.ts centralizes the request/flush timeouts and the sshRelayQueueWaitMs / sshRelayRequestWorstCaseMs helpers.
  • Split request deadline — SshChannelMultiplexer.request() gains opt-in budgetStartsAtWire: the queue wait is bounded separately from the response budget, with a distinct ... without reaching the wire error.
  • Spawn/probe opt-in — pty.spawn and both gating pty.getCapabilities probes (supportsClaims, supportsCreateOperations) opt in, so a saturated writer no longer expires the spawn before its frame is written.
  • Widened pane-connect backstops — DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS and TRANSPORT_CONNECT_SETTLE_GRACE_MS now derive from SSH_PTY_CONNECT_WORST_CASE_MS (160 s).
  • Fake-timer saturation suites — two new test files pin the per-request wire-started budget and the whole claimed-connect worst case.

I verified the core mechanism end to end against ssh-multiplexer-transport-writer.ts: the settlement.ok signal re-arms the deadline only once the frame is out of the writer (the stream flush callback on the real transport, write()===true/drain on the test transport), the timer/cleanup closure is safe across re-arm, and the two capability probes are independently cached so a both-flags launch really sends both. The 160 s worst-case accounting (2×35 s probes + 60 s spawn + 30 s shutdown) checks out, and the tests assert exact values rather than loose bounds.

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

export const TRANSPORT_CONNECT_SETTLE_GRACE_MS = 60_000
// Sized to the whole connect sequence — both capability probes, spawn, cleanup
// shutdown — not spawn alone, so a connect past it cannot still be live.
export const TRANSPORT_CONNECT_SETTLE_GRACE_MS = SSH_PTY_CONNECT_WORST_CASE_MS

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.

TRANSPORT_CONNECT_SETTLE_GRACE_MS is not SSH-scoped: pty-input-recovery.ts fences the #8104-class fossil-pane recovery for every transport, fresh-spawn-start.ts / deferred-session-reattach-connect.ts set transportConnectInFlightSince on local, WSL, and remote-runtime connects alike, and the pre-existing comment above even names the "wedged daemon call" (local) class as a target. Sizing it to the direct-SSH SSH_PTY_CONNECT_WORST_CASE_MS (160 s) widens that suppression window from 60 s to 160 s for transports that settle in seconds and gain nothing from the extra 100 s. If the original 60 s was a deliberate generic bound, keep it and only derive the direct-SSH retry settlement from the worst case.

Technical details
# Generic connect grace widened to a direct-SSH worst case

## Affected sites
- `src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts:24` — `TRANSPORT_CONNECT_SETTLE_GRACE_MS = SSH_PTY_CONNECT_WORST_CASE_MS` (was `60_000`)
- `src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts:283-288` — `connectStillSettling` gate suppresses `requestRecoveryForUndeliverableInput` for every transport
- `src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts:70` and `deferred-session-reattach-connect.ts:40` — set `transportConnectInFlightSince` on generic connects

## Required outcome
- Non-SSH transports keep a connect grace commensurate with their real settle time (seconds), or the widening is an explicitly accepted choice rather than a side effect.

## Suggested approach (optional)
- Leave `TRANSPORT_CONNECT_SETTLE_GRACE_MS` at `60_000` (its pre-change value) and keep only `DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS` derived from `SSH_PTY_CONNECT_WORST_CASE_MS`; or introduce a separate SSH-only grace.

## Open questions for the human (optional)
- Was the original `60_000` sized on purpose, or was it already a proxy for the direct-SSH connect worst case that should scale with it?

@nwparker

Copy link
Copy Markdown
Contributor Author

Confirming review (post-cap)

The adversarial loop hit its 4-round cap, so an independent agent ran a confirming pass on the final tree. Result: 9/9 prior findings verified genuinely fixed (not just claimed), no correctness defect found in the multiplexer change itself, nothing wire-facing.

Tests proven load-bearing. Neutering only the core change (budgetStartsAtWire forced to false) fails 8 of 13 tests:

❯ ssh-channel-multiplexer-saturation-deadline.test.ts (11 tests | 6 failed)
    × does not charge the response budget to a request still parked in the writer
    × starts the response budget when the frame reaches the wire
    × charges only the post-flush budget to a request that saturated the writer itself
    × bounds the flush wait so a writer that never drains still times out
    × bounds the queue wait at the advertised wait for a long caller budget
    × still fails a parked request when the link is genuinely lost
❯ ssh-pty-provider-saturated-writer-connect.test.ts (2 tests | 2 failed)
    × reaches the wire with the first spawn of a connection whose writer is saturated
    × settles the whole claimed connect sequence inside the connect worst case

The 5 survivors are the intentional regression guards (opt-out default, short fail-fast budget, saturation flap, unsaturated dead-link) — they are supposed to pass under old behavior.

Test Files  1217 passed | 7 skipped (1224)
     Tests  13032 passed | 88 skipped (13120)
pnpm tc → EXIT=0 ;  oxlint → clean

Budget ladder is internally consistent (rebuilt from source):

sshRelayQueueWaitMs(t)          max(t, 30_000)
sshRelayRequestWorstCaseMs(t)   max(t,30k) + t
  probe (5s) → 35_000 ; spawn (30s) → 60_000
SSH_PTY_CONNECT_WORST_CASE_MS   2*35_000 + 60_000 + 30_000 = 160_000

Residual findings — flagged, not fixed here

  • N1 (medium, wants a decision before merge). Raising TRANSPORT_CONNECT_SETTLE_GRACE_MS 60s → 160s is forced by the new budget, but it widens the window in which pty-input-recovery.ts suppresses remount recovery. transportConnectInFlightSince is cleared in .finally() on all three set sites, so this only bites a connect that never settles — in that case the pane silently swallows keystrokes for 160s instead of 60s. This trades a 30s-premature-failure bug for a longer silent-input-loss window in a failure path, and that trade was not separately justified in any review round. Either bound the grace independently, or accept it explicitly.
  • N2 (low). Grace (160s) is now 1s below DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS (161s), inverting an ordering that previously held the other way. Traced as benign — settleDirectSshPaneRetryState guards on attemptId/authority/tabGeneration so the late settle is a no-op — but the invariant is now silent and uncommented.
  • N4 (low). SSH_PTY_CONNECT_CAPABILITY_PROBES = 2 is a hand-maintained count with nothing tying it to SshPtyProvider.spawn(). A third gating probe silently under-sizes both renderer backstops — exactly the R4 failure mode, one refactor away from recurring.
  • N5 (informational). The comment "a spawn that never reached the wire started nothing and retries safely" overstates: expire() sends rpc.cancel but nothing removes the frame from the writer's scheduler, so on drain the relay still receives the pty.spawn. Retry safety actually rests on agentSessionCreateOperationId + the relay replay ledger.
  • N3 (pre-existing, amplified). A transport stall is still laundered into a host capability verdict (agent_session_claim_unavailable / execution_owner_unavailable) — adjacent to the ssh-execution-boundary.md rule that loss of contact is not evidence about the host. This PR makes the user wait 6x longer for the same wrong verdict. Predates this change; should be its own PR.

Scope

The reviewer explicitly recommended against narrowing this to just "don't charge parked time + named budget": dropping the probe opt-in reintroduces R4 verbatim (the 5s probe expires in the queue and the spawn it gates is never enqueued, so the fix does nothing on a connection's first spawn), and dropping the backstop resize reintroduces R4's second half. Those pieces are load-bearing for the core fix, not scope creep.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Superseded — recommending we close this in favour of #17817, which fixes the cause this PR works around.

The premise this PR names is itself the bug

From the description above: a pty.spawn can burn its whole budget parked in a saturated writer because "the dead-link check that would otherwise rescue a stuck request is deliberately suppressed in exactly that state."

That suppression is unbounded, and it is the actual defect. SshChannelMultiplexer gated its dead-link check on writerSaturated, so on a half-open link (sleep/resume, dropped NAT mapping) nothing ever left the writer, the writer's single-outstanding liveness guard silenced every keepalive after the first, and the one check that could have noticed was disabled forever. The mux never disposed, so onRelayLost (ssh-relay-session.ts:975) never fired and the bounded-backoff reconnect never ran.

#17817 removes the suppression. A wedged writer now disposes in ~20s and reconnects. A reproduction test (ssh-channel-multiplexer-saturation-wedge.test.ts) fails against the pre-change code: the mux never disposes after 200s, and exactly one keepalive is ever written.

Three concrete reasons not to land this on top

  1. It lengthens the failure the report complained about. SSH_PTY_CONNECT_WORST_CASE_MS goes to 160s, and the renderer backstops are sized from it, so a user on a broken host waits ~6x longer before the pane gives up — versus ~20s to a clean connection_lost and a reconnect.
  2. The orphan-PTY hazard dissolves rather than needing a fix. A spawn that expires "without reaching the wire" is still queued here, and its rpc.cancel queues behind it. Under fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817 the mux disposes and SshMultiplexerTransportWriter.dispose() clears the scheduler, so the parked frame can never later reach the wire and spawn something nobody owns.
  3. The "several minutes to connect" half was never a writer problem. It is [Bug]: Direct SSH Connect hangs on Deploying relay (native probe never finishes) #14830: probeRequiredNativeDeps converted an unanswered probe into "all native deps missing", triggering an 8-minute npm install + rebuild that could not help, then looping until the 900s RELAY_DEPLOY_TIMEOUT_MS expired. Also fixed in fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817, three-state now.

Two independent reviews reached this conclusion separately, including the observation that a parked frame's unackedTimestamps entry is stamped at enqueue (ssh-channel-multiplexer.ts:617), so it now ages into the 20s check on its own.

Worth salvaging

  • The two test files, which are good: ssh-channel-multiplexer-saturation-deadline.test.ts and ssh-pty-provider-saturated-writer-connect.test.ts.
  • Dequeue-on-timeout in the writer, as a small standalone change. fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817 makes the orphan unreachable via the dispose path, but a request that times out while its frame is still queued arguably ought to withdraw that frame regardless.

Closing is the recommendation, not a decision — happy to be overruled if you see a case #17817 leaves open.

@nwparker nwparker closed this Sep 1, 2026
@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Closing note, for the record: superseded by #17817.

This PR's own description names the defect #17817 fixes — the dead-link check being "deliberately suppressed" while the writer is saturated. That suppression was unbounded, which is why a wedged link never reconnected. With it removed, a link that stops draining is declared lost in ~20s and reconnects, rather than a pty.spawn burning 30s in a queue on a link that is already dead. Stacking this on top would have pushed the connect worst case to 160s and lengthened the exact failure the original report complained about.

The "several minutes to connect" half of that report was never a writer problem — it was #14830: an unanswered native-deps probe read as "all deps missing", triggering an eight-minute npm install + rebuild that looped to the 900s deploy cap. Also fixed in #17817.

Nothing is lost. #17882 tracks the two pieces worth keeping: porting the saturated-writer connect harness to assert the new behaviour, and dequeue-on-timeout in the writer — the one real hazard this PR identified and did not fix.

The diagnosis here is what pointed at the right layer, even though the fix landed a level down.

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