Repository navigation
fix(ssh): reclaim relay PTYs the client has provably lost, on host attestation only - #17831
Conversation
Greptile SummaryThe PR adds host-attested ownership metadata to relay PTY inventory and performs conservative orphan cleanup after SSH reattachment.
Confidence Score: 5/5The PR appears safe to merge; no concrete blocking or independently actionable non-blocking defect was established. The cleanup path fails closed when ownership evidence, routing state, session authority, age, pane binding, agent adoption state, or incarnation identity is uncertain.
|
| Filename | Overview |
|---|---|
| src/main/ssh/ssh-orphan-relay-pty-sweep.ts | Adds best-effort reconciliation that combines current routes and durable lease state before issuing incarnation-fenced shutdowns. |
| src/shared/ssh-relay-pty-ownership-proof.ts | Centralizes fail-closed eligibility rules and refuses oversized cleanup passes. |
| src/main/ssh/ssh-relay-session.ts | Runs orphan reconciliation after pending-kill replay and known-PTY reattachment. |
| src/relay/pty-handler.ts | Captures authenticated spawn ownership and publishes optional host-relative ownership evidence in process inventory. |
| src/relay/ssh-pty-consumer-session-adapter.ts | Exposes active authenticated consumer identity to the PTY ownership-attestation path. |
| src/shared/pty-consumer-session.ts | Adds lookup of the client identity associated with an active consumer connection. |
Sequence Diagram
sequenceDiagram
participant Client as SSH client session
participant Relay as Relay consumer session
participant PTY as PTY handler
Client->>Relay: Open authenticated session-owner grant
Client->>PTY: Spawn pane PTY
PTY->>Relay: Resolve active client identity
Relay-->>PTY: Authenticated clientInstanceId
PTY->>PTY: Record owner, creation time, and pane binding
Client->>PTY: Reattach known routed PTYs
Client->>PTY: pty.listProcesses
PTY-->>Client: Inventory with optional ownership evidence
Client->>Client: Exclude routed, young, foreign, bare, or adoptable PTYs
alt Safe orphan set is nonempty and within limit
Client->>PTY: Shutdown each matching incarnation
else Evidence is absent or disagreement is excessive
Client->>Client: Leave PTYs running
end
Reviews (1): Last reviewed commit: "fix(ssh): reap relay PTYs the host attes..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between d8ca420 and 7f8a9131d5c3e901b821f04adcaca6cdb4538931. 📒 Files selected for processing (27)
🚧 Files skipped from review as they are similar to previous changes (26)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe relay records PTY creation age and authenticated consumer ownership. It publishes host age, pane binding, owner identity, incarnation data, and foreground process evidence. A pure planner classifies orphan candidates using ownership, routing, lease, age, pane, session, foreground-state, and authorization checks. SSH reattachment invokes a guarded sweep that lists processes and issues fenced immediate shutdowns. Reattach cleanup now distinguishes confirmed relay absence from live PTYs. Tests cover attestation, planning, cleanup, legacy entries, lease states, failures, process states, and pass cancellation. Merge Risk: ⚪ Minimal · up to The change adds fail-safe reclamation of provably lost relay PTYs while skipping unverifiable or active sessions; no actionable merge-blocking risk remains beyond normal checks and review. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description contains detailed rationale, implementation scope, safety constraints, linked issue references, and test results. However, it omits most required template sections and checklist items, including explicit What Changed, Why, Linked Issue with Fixes #, Visual Proof or N/A, Testing checkboxes, AI Disclosure, Agent skill boundary, Notes, and Checklist. Resolution Retain the existing technical content, but organize it under the repository template headings. Add an explicit Linked Issue entry using the required Fixes # format, add Visual Proof with N/A and a reason if applicable, complete the Testing checkboxes, provide the AI Disclosure, complete the Agent skill upstream boundary section, add Notes covering the requested compatibility areas, and complete the final Checklist. ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 705a1f65-72f7-4b4a-9f18-766bbea850a2
📒 Files selected for processing (12)
src/main/providers/pty-process-info.tssrc/main/ssh/ssh-orphan-relay-pty-sweep.test.tssrc/main/ssh/ssh-orphan-relay-pty-sweep.tssrc/main/ssh/ssh-relay-session-orphan-sweep.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/pty-handler-ownership-attestation.test.tssrc/relay/pty-handler.tssrc/relay/relay-runtime-services.tssrc/relay/ssh-pty-consumer-session-adapter.tssrc/shared/pty-consumer-session.tssrc/shared/ssh-relay-pty-ownership-proof.test.tssrc/shared/ssh-relay-pty-ownership-proof.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| // never published the field. Neither is a pane this client lost. | ||
| return 'not a pane-bound PTY' | ||
| } | ||
| if (entry.agentSessionOwners !== undefined && entry.agentSessionOwners.length > 0) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Reject missing agent-session evidence.
Line 86 accepts agentSessionOwners: undefined. An entry with all other evidence then enters sweep, and sweepOrphanedRelayPtys sends an immediate shutdown. A host that omits this field can therefore cause cleanup of a PTY with an adoptable agent session.
Treat absent agent-session evidence as unknown. Sweep only when the host reports an empty array. Add a test for an otherwise eligible entry with no agentSessionOwners field.
Proposed fix
- if (entry.agentSessionOwners !== undefined && entry.agentSessionOwners.length > 0) {
+ if (!Array.isArray(entry.agentSessionOwners)) {
+ return 'host published no adoptable agent-session evidence'
+ }
+ if (entry.agentSessionOwners.length > 0) {The PR objective requires cleanup to skip when evidence is absent or ambiguous.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (entry.agentSessionOwners !== undefined && entry.agentSessionOwners.length > 0) { | |
| if (!Array.isArray(entry.agentSessionOwners)) { | |
| return 'host published no adoptable agent-session evidence' | |
| } | |
| if (entry.agentSessionOwners.length > 0) { |
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Host-side ownership attestation —
pty.listProcessesgains three optional fields (hostAgeMs,paneBound,ownerClientInstanceId), stamped at spawn from the live consumer grant rather than from a spawn parameter. - Client-side sweep — a pure
planRelayPtySweeprule plussweepOrphanedRelayPtys, run once per connect after reattach and gated on the negotiated session-owner grant. - Session wiring —
SshRelaySessioninvokes the sweep afterreattachKnownPtyson both establish and reconnect. - Tests — 31 tests across the rule, client half, session end-to-end, and host attestation; all pass locally.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The added regression test is correct and pins a load-bearing invariant. The prior
deadlineMssuggestion remains open and unaddressed (this commit is test-only).
Reviewed changes
- Pinned the revive-never-attests invariant — added a test to
src/relay/pty-handler-ownership-attestation.test.tsasserting a revived PTY lists withpaneBound: truebut noownerClientInstanceId, so a relay restart can never make a restored session sweepable.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Independent audit confirms the kill path, and names the precise inversionThe claim that this PR alone can stop a live remote process is CONFIRMED, with one wording correction: in every reachable case the pane has already been detached locally, so "still-attached" is too strong. The process on the remote host is live, is often a running agent or build, and the user never asked for it to stop. The mechanism
None of those gates observes whether anything is running in the PTY. The inversion is here: if (lease.state !== 'terminated' && lease.state !== 'expired') {
routed.add(lease.ptyId)
}
Exact reaching sequenceConnect N: Connect N+1: the PTY is absent from What this changes about the merge requirementI had recorded "land #17831 with #17939". That is not sufficient. The sweep's orphan test rests on The dependency is on the lease-vocabulary work:
With those, Recommendation: hold this PR until #17965 and #17966 land, then revisit the |
|
HOLD. #17939 closes the reproduced path, but a pane with a backgrounded or suspended job is still attested "idle" and SIGKILLed, process group and all. 1. The kill on #17831 alone — reproducedDriving the real So the pairing requirement is real and #17939 does its job. But the reaching sequence is not the one described. 2. The surviving kill — measured, and one step past where #17939 fixed itJoining the real relay publisher (
Container evidence: with
3. Two structural findings
#17939's 4. What is verified soundCredit where due: the attestation is minted only in 5. Harness: #17939 fixes one file of nine
Six further harness gaps make the sweep's session-level coverage structurally incomplete — OSS precedentNo system with this shape reclaims processes on client-side evidence. tmux's only path to That last point has teeth beyond the citation: VS Code's orphan answer is deliberately lossy (a 500ms reply window behind a 4s barrier), which is safe because a wrong answer only mis-populates a picker. Reusing a display-grade signal as a kill authorization changes what a false positive costs, and those tolerances were never sized for it. Comment dispositions
Also note the branch is 156 commits behind main, and main has since added To lift the holdGate on evidence that can see background and stopped work (session/process-group membership, not |
|
Addendum — a second, independent hole: the kill authorization is the display signal, and its staleness field is falsified. This is the defect shape where a tolerance sized for a display path gets reused as a kill authorization. Confirmed at the producer:
One computation, two consumers, no separate error budget. A signal whose false-positive cost was "a stale pane title" now also carries "SIGKILL a process group." Worse, the freshness field that exists to bound this is a hardcoded lie:
So the authorization is a snapshot of unbounded, unrepresentable age. This is precisely the inversion the VS Code precedent warns about. Also correcting both PR bodies: #17939's Defect 1 says Two further items:
Branch is 156 commits behind main, and main has since added |
aaa3933 to
89161bc
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
89161bc to
c28cb74
Compare
|
Superseded the stacked shape: #17939 is folded into this PR's single commit and closed (why). This PR is now the complete, safe change and targets The reason it is one commit rather than a tidy series: the sweep reaps live processes at every intermediate commit of its own history — before any foreground gate it takes a hand-launched Re-verified on this exact tree (not inherited from the earlier run): Rebased onto current |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Host-side shutdown fence —
pty.shutdowngains an optionalexpectedOwnerClientInstanceId, andassertShutdownOwnershipre-decides the one irreversible call on the host: the requesting connection must still authenticate as that identity (read from the live grant, never the parameter) and the host must have recorded that same identity as the PTY's creator at spawn. - Whole-tty idle predicate —
shellIsForegroundis replaced byshellOwnsEveryTtyProcessGroup, computed ingetTtyOccupancyover the same process-group setforceKillPosixPtyProcessGroupswould SIGKILL, so backgrounded and Ctrl-Z'd work is attested as busy. expiredlease named skip — the sweep now tracksexpiredLeasePtyIdsseparately fromroutedPtyIds, so a process a writer deliberately left running is never reaped.- Class-based absence discrimination — both
spawn-execute.tscopies key the destructive lease-expiry branch onisSshPtyAbsentFromRelayErrorrather than the sharedSSH_SESSION_EXPIREDmessage, so a liverestoreRequiredPTY no longer has its lease and ownership erased. - Truthful evidence age + connect budget —
capturedAgeMsis stamped from the actual (worst-case) capture time,RELAY_PTY_SWEEP_MAX_EVIDENCE_AGE_MSbounds staleness at the decision, andRELAY_PTY_SWEEP_PASS_BUDGET_MScovers the listing and every stop on the connect path. - Harness repair — the session-level suite moved to one target per test and added identity-mint guards, so the positive control can no longer silently pass for the wrong reason.
The load-bearing verdict test (ssh-orphan-sweep-pane-state-verdicts.test.ts) runs the real publisher into the real planner over verbatim ps transcripts, and the whole-tty predicate provably measures the same set the kill signals. No new concerns.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
c28cb74 to
806800e
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Unified foreground-candidate selection —
resolveAgentForegroundProcessesFromIndexnow delegates candidate choice to the sharedselectForegroundProcessCandidateinstead of its own inline score-and-pick loop, removing a duplicate of the logic the other two call sites (agent-foreground-process.ts,relay/pty-shell-utils.ts) already use.
The substitution is behavior-preserving for every realistic case: single-agent scoring is byte-identical (foregroundCandidateScore equals the removed scoreForegroundCandidateRow), the omp→codex wrapper chain still resolves to the outer wrapper, and the sweep's processName now agrees with the pane-title path. The only divergence — distinct sibling agents, which now yield null where the old loop named one — can change a kill verdict only under the set +m residual this PR already documents as an accepted limit, so it does not warrant a change. The shared function is independently covered by foreground-process-selection.test.ts.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
806800e to
7f8a913
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
…9819) Orca could lose track of terminals running on an SSH relay until the 50-slot cap refused to open any more. This reclaims them, and the whole design is built around the fact that getting it wrong destroys a user's running process on their remote machine: the failure mode is leak, never kill. A stop requires all nine of: 1. the relay published an `ownerClientInstanceId` read from the live authenticated consumer grant of the connection that requested the spawn — never from a spawn parameter, since an echoed claim is no evidence; absent means skip 2. that id equals this client's persisted consumer identity 3. this connection holds the negotiated `session-owner` grant 4. `paneBound === true`, host-published 5. no `agentSessionOwners` — the host still advertises it as adoptable 6. `hostAgeMs >= 30s`, measured on the host's clock 7. this client has no route: not reattached, no lease outside terminated/expired, no pending kill, and no `expired` lease either — an expired lease is the record of a process deliberately left running, never a licence to kill it 8. every stop is fenced on the incarnation the same listing published, and on the owner identity, both re-checked by the host 9. a pass wanting to stop more than 8 refuses entirely Absence from a client-side set is `unverifiable` by construction (docs/reference/ssh-execution-boundary.md): a second machine attaches to the same relay and displaces the session owner, and its live agents are missing from this client's store for exactly the reason a genuine orphan is. So the host has to attest ownership, and the host has to attest that nothing is running. That second attestation is measured over the pane's whole tty, not its foreground process group. `tpgid == pgid` is foreground-only: on a real `bash -i` on a real pty, a shell holding `sleep 300 &` and a shell holding a Ctrl-Z'd job both read `pgid == tpgid`, `Ss+` — byte-identical to an idle prompt, with only the job's own row differing. A foreground-only gate therefore attests `pnpm build &` and a suspended editor as idle, and the stop that follows SIGKILLs every process group on the tty. `shellOwnsEveryTtyProcessGroup` is measured over that same set of groups, so the evidence and the kill describe the same thing. No new probe: `tpgid` already identifies the terminal, because a process group belongs to one session and a session to at most one controlling terminal. The freshness field is real rather than decorative. `capturedAgeMs` is stamped from when the capture was taken, deliberately as an upper bound since the process table is TTL-shared, and the sweep refuses an observation older than its own pass budget, counting its own elapsed time since the listing arrived. Stale evidence degrades to "do not sweep", never to "sweep". The display consumer of the same measurement keeps no age budget, as a stated decision: a stale pane title costs a redraw and self-corrects. `pty.shutdown` is authorized on the host that owns the process. `pty.spawn` and `pty.attach` both take a request context and check it; the one irreversible call took none, so the rule above lived entirely on the client that decided to make the call. It gains an optional `expectedOwnerClientInstanceId` and refuses unless the connection still authenticates as that identity AND this host recorded it at spawn. Finally, a reattach refusal now says whether it observed the process. Three refusals carry the same `SSH_SESSION_EXPIRED` text and only one is absence; `restoreRequired` means the PTY is live and only its source stream is not. Testing that text with `.includes()` expired the lease and deleted ownership for a running process, erasing this client's only record of it — and a PTY with no record is one the sweep may stop. Wire compatibility: four new optional fields and one new optional param on existing methods, no new method and no new stream opcode (Rule 1, and Rule 2 does not apply). Rule 1's caveat is discharged explicitly — no reader requires any of them, each absence is a named skip reason, and an ordinary pane teardown must omit the owner fence because a revived PTY carries no attested owner at all. New client plus old relay stops zero PTYs; old client plus new relay never reads the fields. Windows relay hosts publish no evidence and therefore never sweep. Verified by joining the real publisher to the real client reader over `ps` captured verbatim from a Linux container, and by driving a real group-for-group SIGKILL against a real pty: backgrounded and suspended jobs survive by pid, and an idle shell is still reclaimed, so the narrowed predicate is not a silent no-op. Squashed deliberately. The sweep is unsafe at every intermediate commit of its own history — before the foreground gate it reaps a hand-launched `claude`, and with a foreground-only gate it reaps a backgrounded build — so this ships as one commit with no bisectable state that kills live work. Refs #9819. Folds in #17939.
7f8a913 to
3a3c6fc
Compare
…testation only (stablyai#17831) * fix(ssh): reclaim relay PTYs the host attests this client orphaned (stablyai#9819) Orca could lose track of terminals running on an SSH relay until the 50-slot cap refused to open any more. This reclaims them, and the whole design is built around the fact that getting it wrong destroys a user's running process on their remote machine: the failure mode is leak, never kill. A stop requires all nine of: 1. the relay published an `ownerClientInstanceId` read from the live authenticated consumer grant of the connection that requested the spawn — never from a spawn parameter, since an echoed claim is no evidence; absent means skip 2. that id equals this client's persisted consumer identity 3. this connection holds the negotiated `session-owner` grant 4. `paneBound === true`, host-published 5. no `agentSessionOwners` — the host still advertises it as adoptable 6. `hostAgeMs >= 30s`, measured on the host's clock 7. this client has no route: not reattached, no lease outside terminated/expired, no pending kill, and no `expired` lease either — an expired lease is the record of a process deliberately left running, never a licence to kill it 8. every stop is fenced on the incarnation the same listing published, and on the owner identity, both re-checked by the host 9. a pass wanting to stop more than 8 refuses entirely Absence from a client-side set is `unverifiable` by construction (docs/reference/ssh-execution-boundary.md): a second machine attaches to the same relay and displaces the session owner, and its live agents are missing from this client's store for exactly the reason a genuine orphan is. So the host has to attest ownership, and the host has to attest that nothing is running. That second attestation is measured over the pane's whole tty, not its foreground process group. `tpgid == pgid` is foreground-only: on a real `bash -i` on a real pty, a shell holding `sleep 300 &` and a shell holding a Ctrl-Z'd job both read `pgid == tpgid`, `Ss+` — byte-identical to an idle prompt, with only the job's own row differing. A foreground-only gate therefore attests `pnpm build &` and a suspended editor as idle, and the stop that follows SIGKILLs every process group on the tty. `shellOwnsEveryTtyProcessGroup` is measured over that same set of groups, so the evidence and the kill describe the same thing. No new probe: `tpgid` already identifies the terminal, because a process group belongs to one session and a session to at most one controlling terminal. The freshness field is real rather than decorative. `capturedAgeMs` is stamped from when the capture was taken, deliberately as an upper bound since the process table is TTL-shared, and the sweep refuses an observation older than its own pass budget, counting its own elapsed time since the listing arrived. Stale evidence degrades to "do not sweep", never to "sweep". The display consumer of the same measurement keeps no age budget, as a stated decision: a stale pane title costs a redraw and self-corrects. `pty.shutdown` is authorized on the host that owns the process. `pty.spawn` and `pty.attach` both take a request context and check it; the one irreversible call took none, so the rule above lived entirely on the client that decided to make the call. It gains an optional `expectedOwnerClientInstanceId` and refuses unless the connection still authenticates as that identity AND this host recorded it at spawn. Finally, a reattach refusal now says whether it observed the process. Three refusals carry the same `SSH_SESSION_EXPIRED` text and only one is absence; `restoreRequired` means the PTY is live and only its source stream is not. Testing that text with `.includes()` expired the lease and deleted ownership for a running process, erasing this client's only record of it — and a PTY with no record is one the sweep may stop. Wire compatibility: four new optional fields and one new optional param on existing methods, no new method and no new stream opcode (Rule 1, and Rule 2 does not apply). Rule 1's caveat is discharged explicitly — no reader requires any of them, each absence is a named skip reason, and an ordinary pane teardown must omit the owner fence because a revived PTY carries no attested owner at all. New client plus old relay stops zero PTYs; old client plus new relay never reads the fields. Windows relay hosts publish no evidence and therefore never sweep. Verified by joining the real publisher to the real client reader over `ps` captured verbatim from a Linux container, and by driving a real group-for-group SIGKILL against a real pty: backgrounded and suspended jobs survive by pid, and an idle shell is still reclaimed, so the narrowed predicate is not a silent no-op. Squashed deliberately. The sweep is unsafe at every intermediate commit of its own history — before the foreground gate it reaps a hand-launched `claude`, and with a foreground-only gate it reaps a backgrounded build — so this ships as one commit with no bisectable state that kills live work. Refs stablyai#9819. Folds in stablyai#17939. * fix(i18n): restore the activity-options key the rebase dropped * fix(i18n): union en.json with main so the rebase cannot drop keys

Two premises this started from were wrong, and both matter
rg "pty.list"misses it: the method ispty.listProcesses(src/relay/pty-handler.ts:984) and the client already calls it (src/main/providers/ssh-pty-provider.ts:280). What was missing was not the RPC but the evidence on it needed to act safely. So this is an additive-field change to an existing method, not a new one — materially lower wire risk.main, by Recover automatically instead of getting stuck on "Multiplexer disposed" when an SSH relay drops #12216 (e233d6a6417). Every path was traced:transport.onCloseandhandleProtocolErrorboth route todispose('connection_lost'),createSshDisposalErroris the single minting site mapping that toCONNECTION_LOST, andwatchMuxForRelayLossfires the bounded backoff. A relay-sidecloseClientdestroys the socket, the--connectbridge exits, the channel closes — that is a peer close, and there is no remaining path from a relay-initiated close to'shutdown'. The relay half moved too:pty.replayno longer ridesnotifyControl's close-on-overflow. Nothing was added here because nothing was left to fix.#9819's paths 1 and 2 were likewise already closed by the pending-kill journal on
main. What remained is the hole this PR closes.The proposed design was unsafe and is not what shipped
#9819 suggests sweeping PTYs that are pane-bound and that "the app no longer owns or leases". Absence from a client-side set is
unverifiableby construction. Concretely: the relay grants exactly onesession-owner, and a second machine on the same build attaches to the same relay and displaces that owner — its live agents are then missing from this client's store for precisely the same reason a genuine orphan is. That design lets one laptop reap another laptop's running agents. The 30s age guard does not help; it only covers a race against this client.The ownership rule that did ship
A stop requires all nine:
ownerClientInstanceIdit read from the live authenticated consumer grant of the connection that requested the spawn — not from a spawn parameter, since an echoed claim is no evidence at all. Absent ⇒ skip.ptyConsumerClientInstanceIdfor the target.session-ownergrant. A subscriber or legacy-fallback client sweeps nothing.paneBound === true, host-published. Bare shells and hosts predating the field are skipped.agentSessionOwners— the host still advertises it as adoptable, so a later spawn can reclaim the running agent. Reaping would convert a recoverable session into a destroyed one. Deliberately stricter than SSH relay leaks orphaned PTY sessions until "Maximum number of PTY sessions reached (50)" #9819.hostAgeMs >= 30_000, measured on the host's clock and published as an age rather than a timestamp, so client clock skew cannot produce a bogus verdict.getPtyIdsForConnection, no lease outsideterminated/expired, nopendingKill, not reattached this pass — and noexpiredlease either, which is its own named skip because an expired lease is the record of a process deliberately left running.Failure mode is leak, never kill. The sweep runs after reattach, is best-effort, and never fails a connect.
Wire compatibility
Four new optional fields on an existing result, plus one new optional param on an existing method — Rule 1 throughout, no new method and no new stream opcode, so Rule 2 does not apply. Rule 1's caveat is the actual risk and is discharged explicitly: no reader requires any of them. Each absence is a named skip reason, tested individually and in combination ("sweeps nothing at all when the whole listing predates the fields"). New client + old relay stops zero PTYs; old client + new relay never reads the fields.
The
pty.shutdownowner fence carries one extra obligation and it is deliberate: an ordinary pane teardown must omit it. A revived PTY carries no attested owner at all, so a host that enforced the fence unconditionally would refuse stops it is obliged to honour. Only the sweep sets it.Worth knowing: the SSH relay is build-id-locked to the client, so skew on this path is not the normal state the doc warns about — but it was built for skew anyway, because the legacy-fallback admission mode is real and lands with
isSessionOwner === false, which alone disables the sweep.The 50 cap: leave it
Raising it defers the leak by exactly the ratio you raise it. #11943's host carried 11-14 orphans, so real panes were far under 50. More importantly the error is currently the only signal a user gets that orphans are accumulating — both reporters found the bug because they hit the wall. The honest lever would be counting only reachable PTYs, but reachability is precisely what cannot be cheaply proven, which is this PR's whole subject.
Honest limits
agentSessionOwnersskip excludes a meaningful slice of real orphans, since agent panes are the common case. Chosen deliberately: losing a running agent beats hitting the cap. It is one branch, tested in isolation, if that trade should go the other way.set +m) puts a background job in the shell's own process group, where the idle predicate cannot see it. Neither canforceKillPosixPtyProcessGroupsdistinguish it — that is the honest limit of what a process table can say, not an oversight.killAllProcessesForWorktreenever sweeping relay PTYs) is not fixed at source; this is a backstop.Refs #9819. #11943 appears already fixed by #12216 and can likely be closed.
ELI5
Orca could lose track of terminals running on the remote, and they piled up until you hit a hard limit of 50 and could not open any more.
User-facing regression risk
listProcessescall per connect.&) or Ctrl-Z'd job is never swept: the host must attest that nothing but the shell's own process group is attached to the pane's terminal.Folded in from #17939: the kill paths, and how they were found
Two paths where the orphan sweep shut down a live user process, plus a third — a harness defect that made six of #17831's seven session-level tests pass for the wrong reason.
Defect 1 — an expired lease licensed the sweep
Rule: an
expiredlease isunverifiable, neverexited. It records that this client lost its handle; it is never host evidence about the process. It now gets its own named skip, deliberately separate fromroutedPtyIdsso the log says why.All four writers of
expireddecline to stop the process on purpose:supersedeSiblingLeasesForPane— "the remote process is deliberately left running"restoreReattachedPtyRuntime→'missing-surface',ssh-relay-session.ts:2717) — a second, independent instance of the same kill, and the worst one, because it is reached only afterpty.attachalready succeeded. The process is not merely unproven there, it is known live. Its own comment says so: "Topology absence alone is not authority to kill a process". The lease is expired, ownership is deleted, and the next connect has no route.handlePtyReattachFailure(ssh-relay-session.ts:2845) — reached only whenisSshPtyNotFoundError(error), i.e. the host itself answered "absent"suppressRetiredReattachedPty, which already routes viapendingKillCorrection to an earlier revision of this description. It claimed
handlePtyReattachFailure("dropStalePty") was reached by a reattach that failed on the transport. It is not::2820early-returns withreattachAttemptsExhaustedfor anything that is notisSshPtyNotFoundError, so a pure transport sever leaves the leaseattached— routed, and never swept. The real live-process path is the missing-surface one above. The code comments that repeated the same mistake are corrected in this PR.terminatedwas checked and is fine: every writer is a host-reported exit, a confirmed ordered stop, or dispose.Defect 2 —
agentSessionOwners≠ "an agent is running here"The sweep now requires the host to positively attest an idle shell, with four gates: field absent → skip;
verdict: 'unverifiable'→ skip; a named foreground process → skip; the host does not attest an idle shell → skip.One correction to my brief. Published
foregroundProcessEvidencealone was not sufficient.processNameis non-null only for a recognized agent, soverdict: 'live', processName: nullcovers both "idle prompt" and "runningvim/npm test/ a build". Gating onprocessNamewould have closed the hand-launched-claudehole and left every unrecognized foreground process sweepable — still a kill.So
shellIsForeground(root.tpgid === root.pgid) was added toForegroundProcessEvidence— a valueresolveAgentForegroundProcessesFromIndexalready computed and threw away. Purely additive optional field: old hosts omit it and the sweep defers, old clients ignore it. Windows relay hosts publish no evidence at all, so they now never sweep — fail-safe, and worth knowing.Defect 3 — the harness hid the other two
This is the most valuable finding, and it is a test defect.
claimSshPtyConsumerRecoverymints a freshrandomUUID()whenever asked for a target it already holds a live in-memory entry for.ssh-relay-session-orphan-sweep.test.tsused one sharedTARGET, so everyestablish()after the first ran under an identity matching no attestation and skipped everything for the wrong reason.Verified directly: with the shared target, an entry with no lease at all produced
{ list: 1, stops: 0 }— the positive control had silently stopped working. Six of seven tests were vacuous.Fixed with one target per test plus two guards inside
establish(): the pass must have run, and no identity-minting warning may have fired. Reinstating the shared target now fails loudly (6 failures).Revert matrix — every gate verified by removing it
Connect budget
One absolute
RELAY_PTY_SWEEP_PASS_BUDGET_MS = 5_000covers the listing and the stops — the brief named onlylistProcesses, but up to eightshutdownRPCs were also untimed on the connect path. Overrun is an empty pass, never a connect failure.clientInstanceIdre-minting: logged, deliberately NOT stabilizedStabilizing it would create a new mass-kill path. The id doubles as the consumer session's ownership identity, and reusing it without the
clientGeneration/ownerGenerationthe same dropped record carried would replay a stale owner generation at the relay. Worse,disposeAndPersistmarks every leaseterminatedwithout ordering any stop — harmless today only because dispose also forgets the recovery record. Stabilizing the id without first fixing that write would turn reconnect into a mass kill. Recorded here so the next person doesn't "fix" the churn into a disaster.Three more blockers, all reproduced rather than reasoned about
Blocker A —
shellIsForegroundcould not see background or stopped worktpgid === pgidis a foreground-only predicate, and the two states it cannot see are the two most expensive to get wrong. Measured on a realbash -ion a real pty indebian:bookworm-slim:psrow3150 1 3150 3150 Ss+ bash -isleep 300 &3152 1 3152 3152 Ss+ bash -isleep 300+ Ctrl-Z3158 1 3158 3158 Ss+ bash -iSame shape in all three: leads its own group, owns the terminal,
Ss+. Only the job's row differs —pgid=3153 tpgid=3152 Sbackgrounded,pgid=3159 tpgid=3158 Tsuspended. Sopnpm build &,npm run dev &and a Ctrl-Z'd editor were each attested idle, andpty.shutdown({immediate:true})→requestForceKill→forceKillPosixPtyProcessGroupsSIGKILLs every process group attached to that tty.Fix: the evidence now measures the same set the kill does.
shellIsForegroundis replaced byshellOwnsEveryTtyProcessGroup— true only when every process group on the pane's terminal is the shell's own and none of them is stopped. No new probe and no newpscolumn:tpgidalready identifies the terminal, because a process group has one session and a session at most one controlling terminal, so two rows reporting the same livetpgidare on the same tty. The index is memoized per capture alongside the existing one.Residual, stated rather than hidden: a shell with job control off (
set +m) puts a background job in the shell's own process group, where this cannot see it — but neither canforceKillPosixPtyProcessGroupsdistinguish it, and that is the honest limit of what a process table can say.Blocker B — the kill authorization was the display signal, with a falsified freshness field
evidenceResults[entryIndex]produced both the pane title andforegroundProcessEvidence, the kill authorization: one computation, two consumers, no separate error budget. And the field that exists to bound it was a hardcoded lie — the snapshot is awaited once, before a loop that may await per entry, and every entry was stampedcapturedAgeMs: 0unconditionally. It had zero readers anywhere in the tree.Fix:
capturedAgeMsis now stamped from when the capture was actually taken. It is a deliberate upper bound:getStrictProcessTableSnapshotserves a TTL-shared table, so a reader can be handed one up toPROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MSolder than its own await, and the producer assumes that worst case. Erring old is the safe direction for the only consumer that acts.RELAY_PTY_SWEEP_MAX_EVIDENCE_AGE_MS, and adds its own elapsed time since the listing arrived, so the gate bounds staleness at the moment of the decision rather than of serialization. Sized to the pass budget, not to the 30s spawn floor — those answer different questions, and the floor's own comment says it guards a concurrent-spawn race.Blocker C — no host-side authorization on the destructive call
pty.spawnandpty.attachboth take a request context and check it.pty.shutdown— the one call that irreversibly destroys a user's running process — took none, so the entire nine-condition ownership rule was enforced client-side only. (CodeRabbit's unaddressed "Moderate" note.)Fix:
pty.shutdowngains an optionalexpectedOwnerClientInstanceId, symmetric with theexpectedIncarnationIdfence already on that call. When present the host refuses unless both halves hold: the requesting connection still authenticates as that consumer identity (so a claim cannot simply be asserted — it is read from the live grant, never from the parameter), and this host recorded that same identity as the PTY's creator at spawn (so a caller cannot reach a PTY it never made). The sweep is the only caller that sets it.Wire compatibility. Rule 1 — a new optional param on an existing method; unknown params are stripped. The obligation Rule 1 attaches is discharged explicitly: no reader requires it. An ordinary pane teardown omits it and must, because a revived PTY carries no attested owner at all and an old host would otherwise refuse stops it is obliged to honour. New client + old host: the field is ignored and the stop behaves exactly as it does today, so this is strictly additive protection, never a new refusal. No new opcode, so Rule 2 does not apply. The relay is build-id-locked to the client, so this skew is not even the normal state — it is handled anyway.
Defect 4 — an
expiredlease written for a PTY known to be aliveFound while closing the layer-4 residual, and it is a fourth independent route to the same kill.
Three different reattach refusals are minted with the same
SSH_SESSION_EXPIREDmessage text, and only one of them observed the process.ssh-pty-errors.tssays so in terms:restoreRequiredmeans "the PTY is live, only its source stream is not". Butspawn-execute.tstested that text with.includes(), so a live-PTYrestoreRequiredrefusal expired the lease and deleted the in-memory ownership — between them this client's only record that the remote process exists.markSshRemotePtyLeasethen no-ops if the row is already gone, leaving no trace at all, and the sweep reads a host-attested, route-less, pane-bound shell it has no record of as one it may stop.Fix: the destructive branch keys on
isSshPtyAbsentFromRelayError— the class that already exists for exactly this distinction and is already used this way inliveness.ts— instead of on the message. Both copies ofspawn-execute.ts(runtime and ipc) are fixed, and both are covered: reverting either one reddens its own test. Being too strict here is self-correcting — a dead lease is retired by the next reattach on real host evidence.How the blockers are pinned
The load-bearing test.
ssh-orphan-sweep-pane-state-verdicts.test.tsis the first test in either PR that spans both halves: it runs the real publisher (resolveAgentForegroundProcessesBatch→toForegroundProcessEvidence) into the real client reader (planRelayPtySweep), overpscaptured verbatim from the container above. Every other test in this feature asserts on hand-written evidence literals, which is exactly how Blocker A survived review — the literals said what the author believed. Reverting the predicate totpgid === pgidfails the backgrounded and suspended rows and nothing else.Interaction with
recoverRemoteTerminalRuntimemainadded a self-driven reconnect on relay node-pty failure since this branch was cut — a new sweep trigger that fires exactly when the host is degraded, exercised by no CI lane. Two things make it safe, and both are now asserted rather than assumed: it only reconnects whenhasLivePtys()is false, and reattach still routes every leased PTY before the sweep runs, so nothing it reclaimed is a candidate. A host too degraded to read its own process table publishesverdict: 'unverifiable', which is its own verdict and never collapses into "idle" — covered by its own row in the verdict test.Why this is one commit
The sweep is unsafe at every intermediate commit of its own history, so there is no
bisectable state that merely leaks:
claude, avim, a running build —agentSessionOwnersis empty for all of them+ shellIsForegroundpnpm build &, a Ctrl-Z'd editorSquashing is therefore not tidiness, it is the safety property: at no point on
main's historydoes a version exist that silently SIGKILLs a user's background job. #17939 is folded in here and
closed rather than merged after this, which also removes the "parent squash-merged, child now
conflicts" window entirely.
Verification on the exact tree that merges
pnpm tcclean.check:code-quality:changed: 0 new findings across 27 files. No lint disables, nomax-linesbump, no@ts-ignore.src/main/ssh+src/relay+src/main/providers+src/main/ipc/pty: 5059 passed, 29 skipped, 0 failed.ORCA_E2E_SSH_DOCKER=1): 6 passed, 2 skipped — both skips are pre-existingtest.fixmein a spec this change does not touch.main.mainand this change have zero overlapping files since the previous base, verified by comparing blob hashes rather than by reading the patch;ssh-relay-deploy.ts(fix(ssh): close the pty master fd leak on relay hosts too #17920) is byte-identical tomain.The decisive experiment, re-run on this tree: a real
bash -ion a real pty, realps, the real predicate, and — when it says idle — a real group-for-group SIGKILL, thenpsby pid again.pgid=3150 tpgid=3150 Ss+Zs)sleep 300 &pgid=3153 tpgid=3153 Ss+sleep 300+ Ctrl-Zpgid=3156 tpgid=3156 Ss+sleep 300foregroundpgid=3159 tpgid=3160 SsThe first three shell rows are the whole point: backgrounded and suspended are byte-identical to
idle. The first row matters as much as the other three — the fix did not turn the feature into
a no-op. The
psbytes the kill decision was made on were then fed back through the realTypeScript predicate, which agreed on all four, so the experiment tested the shipping code and not
a paraphrase of it.
Review record
Substantive review lives on both PRs and neither should be read alone:
expired-writer path map.