Skip to content

fix(ssh): stop orphaning live relays when an endpoint is taken over - #17821

Merged
nwparker merged 1 commit into
mainfrom
fix/ssh-relay-endpoint-takeover
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/ssh-relay-endpoint-takeover

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​735 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​733
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​631 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​620

Draft — one behavior change below needs a product decision before this is ready. See "The call I need."

The bug

ssh-relay-deploy.ts probed the relay socket with test -S <sock>, tried relay.js --connect, and on failure did:

// Why: stale socket from a crashed relay — remove it so the fresh launch can bind at the same path.
await execCommand(conn, `rm -f ${shellEscape(sockFile)}`, { signal })

then launched a fresh relay at the same path. Unlinking a unix socket does not close the listener the old process already holds, so the incumbent kept running forever with its PTYs.

Three findings make this unconditional rather than a rare race:

  1. waitForSentinel does build a typed RelayVersionMismatchError from exit-42, but launchRelay's catch is untyped and swallows it. The two typed handlers in ssh-relay-session.ts are never reached on this path. A version mismatch is precisely the alive-but-refusing case.
  2. src/relay/relay-socket-ownership.ts:96-113 shows the daemon already does the right thing on EADDRINUSE — connect-probe, refuse to steal a socket that accepts, unlink only when the inode identity is unchanged, atomic with its own listen. The client's rm -f defeated that check entirely: with the inode gone, the replacement's listen() just succeeds and the incumbent is never contended with.
  3. relay-grace-branch.ts:112-133: with PTYs present and configuredGraceMs === 0, no grace timer is ever armed. Nothing reclaims it.

A second alive-but-refusing case the issues do not mention: writeRelayEndpointCredential runs on the fresh-launch path only, so once a launch rotates the credential, a still-running incumbent holding the old one destroys every future handshake — same orphan, no version change required.

The fix

The client no longer unlinks anything on the relaunch path. unverifiable is allowed to proceed precisely because RelaySocketOwnership is the authority and refuses to steal a live socket — the check rm -f was destroying.

Three new modules: a read-only incumbent probe producing a strict live | unverifiable | exited verdict (missing lsof yields unverifiable, never exited), a takeover decision, and a sweep of superseded version directories.

verdict same path (relaunch) superseded path (sweep)
live, holds children throw RelayEndpointHeldError — nothing unlinked, nothing signalled retained-live-work
live, proven empty husk SIGTERM, confirm, then launch reaped / reap-unconfirmed
exited (refused and no holder) launch permitted, nothing unlinked stale-endpoint-removed
unverifiable launch permitted, nothing unlinked nothing touched

Killing processes on a user's remote host is the highest-risk thing here, so the reap re-verifies argv and child count on the host inside the same command, immediately before kill -TERM, emitting MISMATCH/BUSY and signalling nothing if either fails. SIGTERM only; reaped is returned only from a kill -0 that then failed.

No wire change — everything is client→host shell and client-local error typing, so mixed versions are unaffected.

The call I need

This converts a silent leak into a visible outage. Where a live incumbent owns the same path and holds work, deploy now fails with a terminal error instead of silently succeeding with a second relay. The user gets no remote terminals until they hit Reset Relay. I believe that is correct — today's "success" is precisely the bug, and it is what strands agent sessions — but it will generate support noise the first time it fires, and --grace-time 0 plus credential rotation is a realistic trigger. Alternatives: auto-reset, or surface it as a prompt rather than an error.

Honest status per issue

Residual risk

  1. The reap is gated on lsof returning exactly one pid whose argv contains both relay.js and our socket path. A host whose lsof mis-attributes a unix socket could see a wrong SIGTERM — narrowed by the on-host argv re-check, not eliminated. Blast radius is bounded to processes already looking like our relay at our socket.
  2. Pid reuse between probe and signal is narrowed by the in-command re-verification, not closed.
  3. Windows is untouched: named pipes have no inode to unlink, so this mechanism cannot occur; both new paths no-op there.

Verification

$ pnpm test src/main/ssh/ssh-relay-endpoint-incumbent.test.ts src/main/ssh/ssh-relay-endpoint-takeover.test.ts \
            src/main/ssh/ssh-relay-superseded-endpoints.test.ts \
            src/main/ssh/ssh-relay-endpoint-incumbent-shell.integration.test.ts src/main/ssh/ssh-relay-deploy.test.ts
 Test Files  5 passed (5)
      Tests  82 passed (82)

$ pnpm test src/main/ssh
 Test Files  131 passed | 2 skipped (133)
      Tests  1839 passed | 16 skipped (1855)

$ pnpm tc:node                              # clean
$ pnpm run check:code-quality:changed       # 0 new findings across 10 changed files

Includes a real-shell integration suite that runs the generated scripts through /bin/sh against real unix sockets and real processes: it asserts lsof is present rather than silently degrading, verifies a SIGKILLed relay's leftover inode reads exited, and verifies the reap refuses both a relay that gained a child (BUSY) and a bystander pid (MISMATCH) without signalling either.

Fixes #8585
Refs #13614, #13852


ELI5

When Orca reconnects, an old copy of its helper can still be running on the remote. Orca used to delete the socket file and start a second one — but deleting the file does not stop the old process, so it kept running forever holding your terminals.

User-facing regression risk

  • Accepted, user-visible: if a live old relay still holds running work, connecting now fails with an error telling you to hit Reset Relay, where before it silently 'succeeded' with a second relay. You get no remote terminals until you do. This was an explicit product decision — the old 'success' is what strands agent sessions on every update.
  • Likely to generate support noise the first time it fires. The realistic trigger is --grace-time 0 plus a credential rotation.
  • Relays orphaned before this ships have already-unlinked sockets and stay invisible; they still need a one-time manual cleanup.

A failed `--connect` was read as "the relay crashed": the client `rm -f`'d
the socket and launched a replacement at the same path. Unlinking a unix
socket does not close the listener the incumbent already holds, so an
alive-but-refusing relay — the RelayVersionMismatchError case — kept running
forever with its PTYs and agents (#8585).

Establish the incumbent with host evidence instead, in the fixed
live/unverifiable/exited vocabulary, and never unlink from the client: the
daemon's own RelaySocketOwnership already performs an identity-checked
takeover that is atomic with its bind. A live incumbent now raises a typed
terminal RelayEndpointHeldError naming its pid rather than being abandoned.

Also sweep sibling version directories for this target's socket after launch,
so the relay an app update supersedes (#13614, #13852) is visible and dealt
with deliberately. Only a relay proven to hold nothing — argv matched, single
socket holder, zero children re-checked on the host immediately before the
signal — is SIGTERMed, and `reaped` is claimed only from a post-signal
`kill -0` that failed. Anything unreachable stays `unverifiable` and untouched.
@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 36 seconds.

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: cabb48d1-d9bb-4c61-bd5a-2b79390a9021

📥 Commits

Reviewing files that changed from the base of the PR and between 9bc564c and 96ba054.

📒 Files selected for processing (10)
  • src/main/ssh/ssh-relay-deploy.test.ts
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-endpoint-incumbent-shell.integration.test.ts
  • src/main/ssh/ssh-relay-endpoint-incumbent.test.ts
  • src/main/ssh/ssh-relay-endpoint-incumbent.ts
  • src/main/ssh/ssh-relay-endpoint-takeover.test.ts
  • src/main/ssh/ssh-relay-endpoint-takeover.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-relay-superseded-endpoints.test.ts
  • src/main/ssh/ssh-relay-superseded-endpoints.ts

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.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Decision made: ship as-is (fail loudly). Marked ready for review.

Where a live incumbent relay owns the endpoint and holds running work, deploy now fails with a terminal error naming Reset Relay, rather than silently launching a second relay beside it. That is a deliberate trade: it converts a silent leak into a visible outage, and it will generate support noise the first time it fires. The reasoning is that today's "success" is precisely the bug — it is what strands running agent sessions on every app update — and a user who is told to hit Reset Relay still has their session, whereas a user who is silently given a second relay does not.

Auto-reset was considered and rejected: it would reap whatever the incumbent was running, which is exactly the data loss #13852 is about.

A prompt ("an older relay is still running with N terminals — reconnect to it, or stop it?") remains the better long-term UX and is worth a follow-up once this has been in the wild long enough to see how often it actually fires.

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

Caution

The terminal error path this PR adds is never reached: RelayEndpointHeldError is swallowed in launchRelay's outer catch, so deploy falls through to a fresh launch and still orphans the incumbent.

Reviewed changes

One commit reworks SSH relay socket takeover: ssh-relay-deploy.ts now calls resolveRelayEndpointBeforeRelaunch instead of rm -f on a refused --connect, backed by three new modules (a read-only incumbent probe, a takeover decision, and a superseded-version-dir sweep) plus a real-shell integration suite.

  • Incumbent probe — a POSIX-only live | unverifiable | exited verdict from lsof/pgrep/ps evidence; Windows hosts return unverifiable without shelling out.
  • Takeover decision — refuses to rebind a live relay holding work (RelayEndpointHeldError), reaps only a proven-empty husk via a SIGTERM with in-command argv/child-count re-verification, and lets the daemon's RelaySocketOwnership handle unverifiable paths.
  • Superseded sweep — lists sibling relay-* version dirs and retains/reaps/removes their sockets before gcOldRelayVersions, unpinning dirs GC otherwise keeps forever.
  • Session wiring — ssh-relay-session.ts treats RelayEndpointHeldError as terminal alongside version-mismatch and owner-admission errors.

ℹ️ Product decision is still open

The PR body's "call I need" — converting a silent leak into a visible outage — remains unresolved while the PR is marked ready for review. Settle the auto-reset / prompt-vs-error question (or drop the draft language) before merge; it determines whether the first real firing of RelayEndpointHeldError is a support ticket or a recovery prompt.

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

// Why not `rm -f`: unlinking does not close the listener the incumbent already holds,
// so a refused --connect (version mismatch, rotated credential) used to leave a live
// relay running forever with its PTYs while a replacement bound the same path (#8585).
await resolveRelayEndpointBeforeRelaunch(conn, hostPlatform, nodePath, sockFile, err, {

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.

RelayEndpointHeldError thrown here lands in launchRelay's outer catch (line 1467), which only rethrows unconfirmed terminations — so the error is swallowed and execution falls through to the fresh-launch path, orphaning the incumbent this PR exists to protect. The isRelayEndpointHeldError handlers added to ssh-relay-session.ts are therefore unreachable for this error.

Technical details
# RelayEndpointHeldError is swallowed in launchRelay

## Affected sites
- src/main/ssh/ssh-relay-deploy.ts:1461 — `resolveRelayEndpointBeforeRelaunch` may reject with `RelayEndpointHeldError`; the enclosing `try` (1435) catches it at 1467.
- src/main/ssh/ssh-relay-deploy.ts:1467-1473 — the outer `catch` rethrows only `isUnconfirmedSshCommandTermination`, then falls through to the fresh-launch block at 1475.
- src/main/ssh/ssh-relay-session.ts:635-639, 793-799 — the two new `isRelayEndpointHeldError` branches never see this error.

## Required outcome
- `RelayEndpointHeldError` must propagate from `launchRelay` to `SshRelaySession`, terminating the attempt without launching a replacement or rotating the credential.
- Add a deploy-level regression test: mock the incumbent probe to return a live holder with children, and assert `deployAndLaunchRelay` rejects with `RelayEndpointHeldError` and issues no `--detached` launch.

## Suggested approach
- In the outer `catch` at line 1467, rethrow `isRelayEndpointHeldError(err)` alongside the existing unconfirmed-termination rethrow.

'args=$(ps -o args= -p "$pid" 2>/dev/null | tr "\\n" " ")',
'case "$args" in *relay.js*"$sock"*) ;; *) printf \'MISMATCH\\n\'; exit 0 ;; esac',
"command -v pgrep >/dev/null 2>&1 || { printf 'BUSY\\n'; exit 0; }",
'kids=$(pgrep -P "$pid" 2>/dev/null | grep -c .)',

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.

pgrep -P "$pid" 2>/dev/null | grep -c . prints 0 both when the relay genuinely has no children and when pgrep itself fails (exit 2/3), so an erroring enumeration authorizes the SIGTERM. The probe side models this as unknown/null for exactly this reason; have the reap re-check emit BUSY when pgrep cannot answer, rather than treating a failed count as zero.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my own ordering note, and this is more urgent than I said

I had recorded the constraint as "#17821's socket unlink fires on any --connect failure." That is backwards. The unlink is on origin/main; this PR is the patch that deletes it.

launchRelay on main, ~lines 1449-1471, is a bare catch (err) with zero discrimination — no exit code, no stderr marker, no error-type check. Anything thrown by conn.exec(...) or waitForSentinel(...) lands there and runs rm -f <sockFile>. So a version mismatch, a credential rotation, a wedged-but-live daemon, a transient channel drop, and a sentinel timeout are all read identically as "the relay crashed."

Blast radius of the bug currently on main: unlinking a unix socket does not close a listener the incumbent already holds. On any --connect failure against a live relay, the incumbent keeps running with all its PTYs and agent processes; its socket inode is gone so nothing can ever address it again; and a replacement relay binds the same path. The result is a permanently orphaned relay process consuming host resources, all its terminals and running agent sessions unreachable from the UI forever, and the user's tabs returning as fresh empty shells. With --grace-time 0 the orphan never self-exits.

That is a direct contributor to the reported "SSH perf degrades over time" symptom, and it matches the production evidence gathered on a Linux host during this sweep: 19 orphan relays, oldest 6.7 days, 11 relay directories each holding a live socket, 839 MB RSS.

What this PR does instead

resolveRelayEndpointBeforeRelaunch probes the host and returns live / unverifiable / exited. Only live blocks the relaunch, throwing the new typed RelayEndpointHeldError. The client never unlinks at all any more — the daemon's RelaySocketOwnership.listen does an identity-checked unlink atomic with its own bind. unverifiable deliberately permits the launch, which is the correct reading of the boundary rule.

The one destructive action retained is a SIGTERM to a relay proven to hold nothing: argv match, exactly one socket holder, and childCount === 0, re-checked host-side in the same command via reapEmptyRelayHuskCommand, with MISMATCH/BUSY aborting before the signal.

Revised priority

I had this filed as a prerequisite for #13852 work. It is that, but it is also a standalone fix for a live orphan-creating bug on main, and it should be weighted accordingly rather than treated as scaffolding for a change that is not happening yet.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Live production measurement on a real Linux host — the fd numbers are diagnostic

Measured on the reporter's Ubuntu box (Linux 7.0.0-28-generic x86_64, 8 cores) using the same census shape as tests/e2e/ssh-docker-resource-accumulation.spec.ts (walk /proc, exclude *relay.js*, count ptmx symlinks):

LEAKED_MASTER_FDS_TOTAL = 355
relay_dirs   = 11
relay_procs  = 23
sockets      = 33
oldest relay dir: 2026-08-23   (10 days)

The inheritance signature, shown directly

Two different processes holding the same fd numbers:

pid=985426  bash                              → 151, 27, 30,31,32,33,34,35,36,37,38,39
pid=63138   claude --dangerously-skip-…       → 151, 27, 30,31,32,33,34,35,36,37

fd numbers are unique within a process, so identical numbers across two processes can only come from fork inheritance. And the later-spawned child holds two more of the run than the earlier one — the triangular growth shape predicted from the CLOEXEC hypothesis: child k inherits the k masters open at its spawn instant.

This is not merely consistent with the hypothesis; it is close to diagnostic of it.

It also confirms the corrected framing

The relay processes themselves hold 0–21 masters each — nowhere near a limit, and legitimately so, one per live terminal. The 355 is entirely duplicates in children:

pid=63138   claude   n=10    ← a user's agent pinning 10 pty devices
pid=985426  bash     n=12
pid=377363  git diff n=6
pid=377364  pager    n=6     ← a git pager holding 6 masters
pid=444290  bash     n=11

So the user-visible harm is the one the patch header names: a child holding a dup keeps /dev/pts/N alive after the relay closes its master, so the shell never receives EOF/SIGHUP — terminals that will not die. Not fd exhaustion in the relay.

Validation note for whoever verifies this fix: expect the census to drop toward ~0 while the relay's own fd count is unchanged. A flat relay fd table is the expected outcome, not evidence the fix failed.

Relay accumulation, separately

23 live relay processes across 11 install directories with 33 sockets, oldest 10 days. That is item C — "SSH perf degrades over time" — measured rather than inferred, and it is the blast radius of the --connect-failure socket unlink that #17821 removes (unlinking does not close a listener the incumbent holds, so the old relay keeps running with its PTYs while a replacement binds the same path).

Cross-posted to #17821.

@nwparker
nwparker merged commit d838ca1 into main Sep 2, 2026
119 of 121 checks passed
@nwparker
nwparker deleted the fix/ssh-relay-endpoint-takeover branch September 2, 2026 05:35
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…tablyai#17821)

A failed `--connect` was read as "the relay crashed": the client `rm -f`'d
the socket and launched a replacement at the same path. Unlinking a unix
socket does not close the listener the incumbent already holds, so an
alive-but-refusing relay — the RelayVersionMismatchError case — kept running
forever with its PTYs and agents (stablyai#8585).

Establish the incumbent with host evidence instead, in the fixed
live/unverifiable/exited vocabulary, and never unlink from the client: the
daemon's own RelaySocketOwnership already performs an identity-checked
takeover that is atomic with its bind. A live incumbent now raises a typed
terminal RelayEndpointHeldError naming its pid rather than being abandoned.

Also sweep sibling version directories for this target's socket after launch,
so the relay an app update supersedes (stablyai#13614, stablyai#13852) is visible and dealt
with deliberately. Only a relay proven to hold nothing — argv matched, single
socket holder, zero children re-checked on the host immediately before the
signal — is SIGTERMed, and `reaped` is claimed only from a post-signal
`kill -0` that failed. Anything unreachable stays `unverifiable` and untouched.

Mirror-Of: d838ca1
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#17821)

A failed `--connect` was read as "the relay crashed": the client `rm -f`'d
the socket and launched a replacement at the same path. Unlinking a unix
socket does not close the listener the incumbent already holds, so an
alive-but-refusing relay — the RelayVersionMismatchError case — kept running
forever with its PTYs and agents (stablyai#8585).

Establish the incumbent with host evidence instead, in the fixed
live/unverifiable/exited vocabulary, and never unlink from the client: the
daemon's own RelaySocketOwnership already performs an identity-checked
takeover that is atomic with its bind. A live incumbent now raises a typed
terminal RelayEndpointHeldError naming its pid rather than being abandoned.

Also sweep sibling version directories for this target's socket after launch,
so the relay an app update supersedes (stablyai#13614, stablyai#13852) is visible and dealt
with deliberately. Only a relay proven to hold nothing — argv matched, single
socket holder, zero children re-checked on the host immediately before the
signal — is SIGTERMed, and `reaped` is claimed only from a post-signal
`kill -0` that failed. Anything unreachable stays `unverifiable` and untouched.
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.

Orphaned detached relays are never reaped: failed --connect deletes the socket but leaves the old relay (and its PTYs/agents) running forever

1 participant