Back off SSH reattach and collapse its status spam during a host outage

Closed
SM
2mo ago
+883-20

Fixes #10173.

Scope: the reattach schedule and the reattach presentation. An earlier revision of this PR also wrote hidden attempt diagnostics to a file under TMPDIR; that is removed — see Out of scope below.

Mechanism

SSHPTYAttachRetryScriptBuilder.lines already doubled the reconnect delay after every wait, but two case branches reset it back to the 2s initial delay on every failed attempt:

252) ... cmux_ssh_attach_reconnect_delay="$cmux_ssh_attach_reconnect_initial_delay"; ...
254) ... cmux_ssh_attach_reconnect_delay="$cmux_ssh_attach_reconnect_initial_delay" ;;

An outage on a Tailscale host cycles statuses — 255 while the transport is dead, 254 when the bridge closes before the remote PTY exit can be confirmed, 252 when the daemon is not serving yet — so the schedule was reset roughly every second or third attempt and never grew. That is the "no visible backoff" in the report: attempt 26/∞ on a host that had been down for minutes.

The presentation piled on top: one status line per attempt, plus the CLI's own raw Error: ssh-pty-attach: … and, on a reauthenticating workspace, ssh: connect to host … / mux_client_request_session: … — 2-3 fresh scrollback lines per attempt, forever.

Delay schedule

Unbounded retrying is kept: the issue is explicit that "the reattach persistence is correct; the presentation is not", and a host asleep overnight must still be attached in the morning. The flood control is the schedule, not a retry limit.

  • 2s → 4 → 8 → 16 → 30s ceiling (unchanged defaults, still overridable with CMUX_SSH_RECONNECT_DELAY_SECONDS / CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS). A multi-minute outage retries twice a minute, not thirty times.
  • The schedule resets on evidence, not on an exit status: an attempt that stayed connected for at least 30s starts a fresh streak. 30s is SSHPTYAttachExitCode.healthyBridgeUptime, the same threshold that already separates a healthy bridge from a rapid no-progress closure, so the two budgets agree on what "connected" means. A bridge that dies instantly is a failed attempt whatever status it reports, which is exactly what the 252/254 resets got wrong.
  • The schedule, the healthy-attempt threshold and the status wording live in one value type, SSHPTYAttachReconnectBackoffPolicy, which the builder reads for the shell defaults, the reset rule and the message format. It is tested directly, so the schedule is not inferred from generated script text.
  • Edges are closed. delaySeconds(afterConsecutiveFailures:) compares before doubling, so a ceiling near Int.max clamps instead of trapping; the initializer clamps zero, negative and inverted configurations, and clamps any ceiling to one day. The generated loop clamps the same way before any shell arithmetic: a setting of six digits or more is capped, because on the pre-fix loop CMUX_SSH_RECONNECT_DELAY_SECONDS=99999999999999999999 aborted the comparison with /bin/sh: [: 99999999999999999999: integer expression expected before the first reattach. CMUX_SSH_RECONNECT_LIMIT is capped the same way: an oversized all-digit limit made both budget comparisons fail rather than answer, so the wrapper could neither retry nor stop on its own terms. Padding zeros are stripped before that cap counts digits, so 0000002 is still a budget of two retries. CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT is capped in SSHPTYAttachExitCode.noProgressShellPolicy() for the same reason, and that one matters most: it is the budget that stops a bridge which never makes progress, so an unanswerable comparison there left nothing to stop it.
  • No jitter: each pane runs its own wrapper started at its own time, so there is no synchronized herd to spread, and a good entropy source in the generated /bin/sh would cost more than it buys. Easy to add to the policy type later if a shared-host herd shows up.

Message policy

  • One line, rewritten in place, carrying the repeat count: [cmux] reconnecting to the remote PTY (attempt 7, next retry in 30s). Repeats rewrite it (\r + erase-line), so a 40-attempt outage adds one line to scrollback, not 40. It closes with a newline when the session comes back or retrying stops, so the scrollback keeps one line per outage.
  • The line does not name a host state, or even claim the connection is lost. An earlier revision mapped the attach exit status onto "SSH host is unreachable" / "remote cmux daemon is not ready" and so on. That mapping cannot be made honest at this layer: SSHPTYAttachExitCode.classifyNormalized returns 255 for timed out, connection refused, connection reset and remote daemon is not ready alike — all three failure shapes quoted in #10173 collapse into one status by the time the wrapper sees it, and 251/252 are a busy or unready daemon rather than a dead link. The line reports only what the wrapper knows: it is reattaching, which attempt is next, and when. Naming the state properly needs the cause carried across the retry boundary (distinct statuses or a structured hand-off), which is #10173's item 4 and its own change.
  • The cause is printed once per outage, not once per attempt. The first failure of a streak keeps its raw stderr — the useful one. While the streak lasts, each further attempt's stderr is discarded, and the attempt counter in the status line is what tells the user it is still happening. A connected attempt (30s+) ends the streak, so the next outage prints its cause again.
  • Reauthentication does not restart the streak. A workspace that reauthenticates sets reauth_required on every 255, so clearing quiet mode there would print the same attach error once per cycle. The prompt runs outside the quieted attempt, so it stays visible while the repeats behind it stay hidden.
  • Nothing is written to disk. When retrying stops on a failure while repeats were being hidden — fatal status, reconnect limit, no-progress budget, terminal auth failure — the pane gets [cmux] stopped reconnecting to the remote PTY; repeated error output was hidden while retrying. Reattach to see it, or check the connection to the host., so a silenced final attempt never looks like a failure without a reason. A clean exit says nothing; the raw exit status stays with the process, out of the pane.
  • Quieting only engages when stderr is a terminal, so non-interactive wrappers keep writing everything to their stderr as before. Foreground authentication is never quieted: it talks to the user.

What the user sees during a multi-minute outage

The first failure prints its real error, then a single line keeps updating in place: attempt 2 (next retry in 4s), attempt 3 (8s), attempt 4 (16s), attempt 5+ every 30s. Nothing else is appended until the session comes back or retrying stops.

Red/green

The new tests fail on the pre-fix loop. Running this PR's test file against upstream/main's SSHPTYAttachRetryScriptBuilder:

✘ theRetryLoopWaitsTheScheduledDelays: (delays → ["2", "2", "2", "2", "2"]) == ["2", "4", "8", "16", "30"]
✘ aConnectedAttemptRestartsTheSchedule: delays == ["2", "4", "2", "4", "8"]
✘ anAbsurdDelaySettingClampsInsteadOfBreakingTheLoop("99999999999999999999"):
    result.stderr → "/bin/sh: line 15: [: 99999999999999999999: integer expression expected"
✘ repeatedFailuresRewriteOneStatusLineInsteadOfAppendingMore: (statusLineCount → 0) == 1
✘ onlyTheFirstFailureOfAStreakPrintsItsRawErrorOutput: transcript contains "cmux-test-raw-noise 2..5"

Green on this head: the SSHPTYAttach* suites run 30 tests, all passing.

The tests come in two layers. The policy type is tested directly — the schedule for attempt N, the ceiling, Int.max configurations, zero/negative/inverted settings, the progress predicate, and the exact status line for attempt N. The generated loop is then driven for real under /bin/sh and under a terminal, with stubbed sleep/date and a scripted sequence of attach exit statuses, asserting the delays waited, how many status lines scrollback keeps, which raw stderr survived, and that its TMPDIR is still empty afterwards. No assertions on generated script text.

Two existing tests in SSHPTYAttachRetryScriptBuilderTests waited for the old remote PTY bridge closed; reattaching text as their "backoff started" marker; they now wait for reconnecting to the remote PTY.

Validation

swift test --package-path Packages/macOS/CmuxFoundation --no-parallel            # 233 tests in 38 suites, green
swift test --package-path Packages/macOS/CmuxFoundation --filter SSHPTYAttach    # 30 tests, green
swift test --package-path Packages/macOS/CmuxSimulator --filter Localization     # catalog parses, green

The default parallel run has one unrelated flake, CommandRunnerDescriptorLifecycleTests ("Capture pipes are close-on-exec and close before success returns", a process spawn returning no exit status under load). It passes in isolation and in the serial run, and this change does not touch it.

The change is confined to the CmuxFoundation package, so the app and CLI targets only consume the unchanged SSHPTYAttachRetryScriptBuilder().lines(command:reauthenticates:) signature. I could not run the cmux-cli xcodebuild target locally: package resolution needs a built GhosttyKit.xcframework, which this machine does not have.

Localization

Two keys in Resources/Localizable.xcstrings, both with en and ja: cli.sshPtyAttach.reconnectStatus and cli.sshPtyAttach.reconnectQuietedStop. The four cli.sshPtyAttach.reconnectState.* keys and cli.sshPtyAttach.reconnectDiagnosticsLogged from the earlier revision are removed with the code that used them. Audit: the changed user-facing surfaces are the two wrapper messages; both locales present for both keys, with matching %s counts (two in the status line, none in the stop note); the catalog parses — swift test --package-path Packages/macOS/CmuxSimulator --filter Localization reads and validates it — and no other entry is touched; no bare English literal is introduced (both go through String(localized:defaultValue:)); no web catalog or docs strings are in this change.

Out of scope

  • On-disk reconnect diagnostics. The earlier revision wrote every hidden attempt to $TMPDIR/cmux-ssh-attach-<pid>.log (overridable) and replayed it when retrying stopped. That path was predictable, followed a pre-created symlink, was not owner-only, and grew for as long as the outage lasted; rotating and hardening it is a change of its own, with its own path and retention review. It is removed here — the pane stays readable without it — and preserving that raw history is tracked separately in #10410.
  • The garbled buffered-keystroke replay (#10173 item 3) is a different mechanism — input buffered while the bridge is down and flushed into the reattached PTY — and does not run through the retry wrapper. Not touched here.
  • Naming the host state (#10173 item 4) needs the failure cause carried across the retry boundary; see Message policy.
  • SSHPTYAttachExitCode.retryLoopLines is an older duplicate of this loop with the same reset bug. It has no production caller (only its own test), so I left it alone rather than widen this PR; happy to delete it in a follow-up if you prefer.

Fork-PR workflows sit in action_required, so GitHub CI has not run on this PR yet.

Summary by CodeRabbit

  • New Features
    • Improved SSH PTY reconnection with configurable exponential backoff.
    • Added clearer reconnect status updates, retry timing, and stop-retry diagnostics.
    • Long-running healthy connections now reset the retry backoff.
    • Repeated errors are condensed to reduce terminal noise.
    • Added English and Japanese localization for reconnect messages.