Repository navigation
fix(ssh): stop orphaning live relays when an endpoint is taken over - #17821
Conversation
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.
|
Warning Review limit reachedNext included review available in 36 seconds. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (10)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
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. |
There was a problem hiding this comment.
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 | exitedverdict fromlsof/pgrep/psevidence; Windows hosts returnunverifiablewithout 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'sRelaySocketOwnershiphandleunverifiablepaths. - Superseded sweep — lists sibling
relay-*version dirs and retains/reaps/removes their sockets beforegcOldRelayVersions, unpinning dirs GC otherwise keeps forever. - Session wiring —
ssh-relay-session.tstreatsRelayEndpointHeldErroras 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.
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, { |
There was a problem hiding this comment.
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 .)', |
There was a problem hiding this comment.
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.
Correction to my own ordering note, and this is more urgent than I saidI had recorded the constraint as "#17821's socket unlink fires on any
Blast radius of the bug currently on main: unlinking a unix socket does not close a listener the incumbent already holds. On any 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
The one destructive action retained is a SIGTERM to a relay proven to hold nothing: argv match, exactly one socket holder, and Revised priorityI 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. |
Live production measurement on a real Linux host — the fd numbers are diagnosticMeasured on the reporter's Ubuntu box ( The inheritance signature, shown directlyTwo different processes holding the same fd numbers: 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 framingThe 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: So the user-visible harm is the one the patch header names: a child holding a dup keeps 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, separately23 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 Cross-posted to #17821. |
…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
…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.

The bug
ssh-relay-deploy.tsprobed the relay socket withtest -S <sock>, triedrelay.js --connect, and on failure did: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:
waitForSentineldoes build a typedRelayVersionMismatchErrorfrom exit-42, butlaunchRelay's catch is untyped and swallows it. The two typed handlers inssh-relay-session.tsare never reached on this path. A version mismatch is precisely the alive-but-refusing case.src/relay/relay-socket-ownership.ts:96-113shows the daemon already does the right thing onEADDRINUSE— connect-probe, refuse to steal a socket that accepts, unlink only when the inode identity is unchanged, atomic with its ownlisten. The client'srm -fdefeated that check entirely: with the inode gone, the replacement'slisten()just succeeds and the incumbent is never contended with.relay-grace-branch.ts:112-133: with PTYs present andconfiguredGraceMs === 0, no grace timer is ever armed. Nothing reclaims it.A second alive-but-refusing case the issues do not mention:
writeRelayEndpointCredentialruns 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.
unverifiableis allowed to proceed precisely becauseRelaySocketOwnershipis the authority and refuses to steal a live socket — the checkrm -fwas destroying.Three new modules: a read-only incumbent probe producing a strict
live | unverifiable | exitedverdict (missinglsofyieldsunverifiable, neverexited), a takeover decision, and a sweep of superseded version directories.live, holds childrenRelayEndpointHeldError— nothing unlinked, nothing signalledretained-live-worklive, proven empty huskreaped/reap-unconfirmedexited(refused and no holder)stale-endpoint-removedunverifiableKilling 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, emittingMISMATCH/BUSYand signalling nothing if either fails. SIGTERM only;reapedis returned only from akill -0that 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 0plus credential rotation is a realistic trigger. Alternatives: auto-reset, or surface it as a prompt rather than an error.Honest status per issue
launchVersionwith a semantic protocol version plus a stable, version-independent socket path — a genuine wire change needing capability negotiation, deliberately not slipped in here.Residual risk
lsofreturning exactly one pid whose argv contains bothrelay.jsand our socket path. A host whoselsofmis-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.Verification
Includes a real-shell integration suite that runs the generated scripts through
/bin/shagainst real unix sockets and real processes: it assertslsofis present rather than silently degrading, verifies a SIGKILLed relay's leftover inode readsexited, 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
--grace-time 0plus a credential rotation.