Skip to content

fix(ssh): reclaim relay PTYs the client has provably lost, on host attestation only - #17831

Merged
nwparker merged 3 commits into
mainfrom
fix/ssh-relay-orphan-pty-sweep
Sep 2, 2026
Merged

nwparker merged 3 commits into
mainfrom
fix/ssh-relay-orphan-pty-sweep

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1697 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1676
Prod 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​678 $\color{#cf222e}{\Huge{\mathbf{−}}}$​16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​662

Two premises this started from were wrong, and both matter

  1. A reconciliation RPC already exists. rg "pty.list" misses it: the method is pty.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.
  2. [Bug]: Accumulated orphaned relay PTYs cause 'Relay control publication capacity exceeded' on reconnect; client permanently disposes multiplexer instead of reconnecting #11943's client half is already fixed on main, by Recover automatically instead of getting stuck on "Multiplexer disposed" when an SSH relay drops #12216 (e233d6a6417). Every path was traced: transport.onClose and handleProtocolError both route to dispose('connection_lost'), createSshDisposalError is the single minting site mapping that to CONNECTION_LOST, and watchMuxForRelayLoss fires the bounded backoff. A relay-side closeClient destroys the socket, the --connect bridge 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.replay no longer rides notifyControl'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 unverifiable by construction. Concretely: the relay grants exactly one session-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:

  1. The relay published an ownerClientInstanceId it 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.
  2. That id equals this client's persisted ptyConsumerClientInstanceId for the target.
  3. This connection holds the negotiated session-owner grant. A subscriber or legacy-fallback client sweeps nothing.
  4. paneBound === true, host-published. Bare shells and hosts predating the field are skipped.
  5. No 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.
  6. 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.
  7. This client has no route: not in getPtyIdsForConnection, no lease outside terminated/expired, no pendingKill, not reattached this pass — and no expired lease either, which is its own named skip because an expired lease is the record of a process deliberately left running.
  8. Every stop is fenced on the incarnation the same listing published and on the owner identity, both re-checked by the host rather than trusted from the client.
  9. A pass wanting to stop more than 8 refuses entirely rather than truncating — at that size the disagreement is about ownership, not slots.

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.shutdown owner 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

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

  • A stop now requires nine independent proofs including host attestation, so the failure mode is leak, never kill. If the attestation is wrong we skip; we do not guess.
  • Adds one listProcesses call per connect.
  • Does not clean up existing orphan piles — attestation is only stamped on PTYs spawned after this ships. Those still need a one-time Reset Relay.
  • Agent panes are deliberately never swept (the host still advertises them as adoptable), so a real orphan running an agent is retained rather than reclaimed.
  • A pane with a backgrounded (&) 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.
  • The stop is now refused by the host unless it recorded this client as the PTY's creator, so a client-side bug alone cannot destroy a process.

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 expired lease is unverifiable, never exited. 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 from routedPtyIds so the log says why.

All four writers of expired decline to stop the process on purpose:

  • supersedeSiblingLeasesForPane — "the remote process is deliberately left running"
  • the missing-surface refusal (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 after pty.attach already 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 when isSshPtyNotFoundError(error), i.e. the host itself answered "absent"
  • suppressRetiredReattachedPty, which already routes via pendingKill

Correction to an earlier revision of this description. It claimed handlePtyReattachFailure ("dropStalePty") was reached by a reattach that failed on the transport. It is not: :2820 early-returns with reattachAttemptsExhausted for anything that is not isSshPtyNotFoundError, so a pure transport sever leaves the lease attached — 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.

terminated was 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 foregroundProcessEvidence alone was not sufficient. processName is non-null only for a recognized agent, so verdict: 'live', processName: null covers both "idle prompt" and "running vim / npm test / a build". Gating on processName would have closed the hand-launched-claude hole and left every unrecognized foreground process sweepable — still a kill.

So shellIsForeground (root.tpgid === root.pgid) was added to ForegroundProcessEvidence — a value resolveAgentForegroundProcessesFromIndex already 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.

claimSshPtyConsumerRecovery mints a fresh randomUUID() whenever asked for a target it already holds a live in-memory entry for. ssh-relay-session-orphan-sweep.test.ts used one shared TARGET, so every establish() 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

DEFECT 1 REVERTED   4 failed | 37 passed
DEFECT 2 REVERTED   8 failed | 33 passed
HARNESS REVERTED    6 failed |  1 passed
BUDGET REVERTED     1 failed | 14 passed
MINT-LOG REVERTED   1 failed |  1 passed
RESTORED            41 passed (3 files)

Connect budget

One absolute RELAY_PTY_SWEEP_PASS_BUDGET_MS = 5_000 covers the listing and the stops — the brief named only listProcesses, but up to eight shutdown RPCs were also untimed on the connect path. Overrun is an empty pass, never a connect failure.

clientInstanceId re-minting: logged, deliberately NOT stabilized

Stabilizing it would create a new mass-kill path. The id doubles as the consumer session's ownership identity, and reusing it without the clientGeneration/ownerGeneration the same dropped record carried would replay a stale owner generation at the relay. Worse, disposeAndPersist marks every lease terminated without 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 — shellIsForeground could not see background or stopped work

tpgid === pgid is a foreground-only predicate, and the two states it cannot see are the two most expensive to get wrong. Measured on a real bash -i on a real pty in debian:bookworm-slim:

pane state shell's own ps row
idle 3150 1 3150 3150 Ss+ bash -i
sleep 300 & 3152 1 3152 3152 Ss+ bash -i
sleep 300 + Ctrl-Z 3158 1 3158 3158 Ss+ bash -i

Same shape in all three: leads its own group, owns the terminal, Ss+. Only the job's row differs — pgid=3153 tpgid=3152 S backgrounded, pgid=3159 tpgid=3158 T suspended. So pnpm build &, npm run dev & and a Ctrl-Z'd editor were each attested idle, and pty.shutdown({immediate:true}) → requestForceKill → forceKillPosixPtyProcessGroups SIGKILLs every process group attached to that tty.

Fix: the evidence now measures the same set the kill does. shellIsForeground is replaced by shellOwnsEveryTtyProcessGroup — 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 new ps column: tpgid already identifies the terminal, because a process group has one session and a session at most one controlling terminal, so two rows reporting the same live tpgid are 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 can forceKillPosixPtyProcessGroups distinguish 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 and foregroundProcessEvidence, 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 stamped capturedAgeMs: 0 unconditionally. It had zero readers anywhere in the tree.

Fix:

  • capturedAgeMs is now stamped from when the capture was actually taken. It is a deliberate upper bound: getStrictProcessTableSnapshot serves a TTL-shared table, so a reader can be handed one up to PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS older than its own await, and the producer assumes that worst case. Erring old is the safe direction for the only consumer that acts.
  • The consumer enforces 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.
  • Stale evidence degrades to do not sweep, never to sweep.
  • The display path keeps no age budget, now as an explicit decision rather than an accident: a stale pane title costs a redraw and self-corrects on the next poll. One truthful measurement, two stated budgets.

Blocker C — no host-side authorization on the destructive call

pty.spawn and pty.attach both 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.shutdown gains an optional expectedOwnerClientInstanceId, symmetric with the expectedIncarnationId fence 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 expired lease written for a PTY known to be alive

Found 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_EXPIRED message text, and only one of them observed the process. ssh-pty-errors.ts says so in terms: restoreRequired means "the PTY is live, only its source stream is not". But spawn-execute.ts tested that text with .includes(), so a live-PTY restoreRequired refusal expired the lease and deleted the in-memory ownership — between them this client's only record that the remote process exists. markSshRemotePtyLease then 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 in liveness.ts — instead of on the message. Both copies of spawn-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.ts is the first test in either PR that spans both halves: it runs the real publisher (resolveAgentForegroundProcessesBatch → toForegroundProcessEvidence) into the real client reader (planRelayPtySweep), over ps captured 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 to tpgid === pgid fails the backgrounded and suspended rows and nothing else.

Interaction with recoverRemoteTerminalRuntime

main added 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 when hasLivePtys() 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 publishes verdict: '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:

commit foreground gate what it reaps
the original sweep none at all a hand-launched claude, a vim, a running build — agentSessionOwners is empty for all of them
+ shellIsForeground foreground-only pnpm build &, a Ctrl-Z'd editor
this commit whole-tty nothing that is running

Squashing is therefore not tidiness, it is the safety property: at no point on main's history
does 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 tc clean. check:code-quality:changed: 0 new findings across 27 files. No lint disables, no max-lines bump, no @ts-ignore.
  • src/main/ssh + src/relay + src/main/providers + src/main/ipc/pty: 5059 passed, 29 skipped, 0 failed.
  • SSH docker e2e (ORCA_E2E_SSH_DOCKER=1): 6 passed, 2 skipped — both skips are pre-existing test.fixme in a spec this change does not touch.
  • Rebased onto current main. main and 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 to main.

The decisive experiment, re-run on this tree: a real bash -i on a real pty, real ps, the real predicate, and — when it says idle — a real group-for-group SIGKILL, then ps by pid again.

scenario shell's own row verdict SIGKILL issued job pid after
idle shell pgid=3150 tpgid=3150 Ss+ idle yes shell reclaimed (Zs)
sleep 300 & pgid=3153 tpgid=3153 Ss+ busy no alive
sleep 300 + Ctrl-Z pgid=3156 tpgid=3156 Ss+ busy no alive
sleep 300 foreground pgid=3159 tpgid=3160 Ss busy no alive

The 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 ps bytes the kill decision was made on were then fed back through the real
TypeScript 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:

@greptile-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Greptile Summary

The PR adds host-attested ownership metadata to relay PTY inventory and performs conservative orphan cleanup after SSH reattachment.

  • Records the authenticated spawning client, host-relative PTY age, and pane binding on newly spawned relay PTYs.
  • Plans cleanup only for sufficiently old, same-client pane PTYs without live routes, pending kills, or adoptable agent sessions.
  • Fences shutdown by PTY incarnation, limits each pass, and treats listing and shutdown failures as best-effort cleanup failures.
  • Adds unit and session-level coverage for ownership, compatibility, routing, age, and safety gates.

Confidence Score: 5/5

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

Important Files Changed

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
Loading

Reviews (1): Last reviewed commit: "fix(ssh): reap relay PTYs the host attes..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: ce06332e-50ad-4fc6-ab03-f0c0200368e5

📥 Commits

Reviewing files that changed from the base of the PR and between d8ca420 and 7f8a9131d5c3e901b821f04adcaca6cdb4538931.

📒 Files selected for processing (27)
  • src/main/ipc/pty-daemon-spawn-session-identity.test.ts
  • src/main/ipc/pty-runtime-ssh-binding-persistence.test.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/providers/agent-foreground-process-batch.test.ts
  • src/main/providers/agent-foreground-process-batch.ts
  • src/main/providers/pty-process-info.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/providers/ssh-pty-reattach-absence-discrimination.test.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.test.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.ts
  • src/main/ssh/ssh-orphan-sweep-pane-state-verdicts.test.ts
  • src/main/ssh/ssh-pty-consumer-recovery.test.ts
  • src/main/ssh/ssh-pty-consumer-recovery.ts
  • src/main/ssh/ssh-relay-session-orphan-sweep.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler-inventory-process-evidence.test.ts
  • src/relay/pty-handler-ownership-attestation.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-runtime-services.ts
  • src/relay/ssh-pty-consumer-session-adapter.ts
  • src/shared/foreground-process-evidence.ts
  • src/shared/process-table-snapshot.ts
  • src/shared/pty-consumer-session.ts
  • src/shared/ssh-relay-pty-ownership-proof.test.ts
  • src/shared/ssh-relay-pty-ownership-proof.ts
🚧 Files skipped from review as they are similar to previous changes (26)
  • src/relay/relay-runtime-services.ts
  • src/shared/pty-consumer-session.ts
  • src/relay/pty-handler-inventory-process-evidence.test.ts
  • src/main/ipc/pty-runtime-ssh-binding-persistence.test.ts
  • src/main/providers/pty-process-info.ts
  • src/relay/ssh-pty-consumer-session-adapter.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/ssh/ssh-pty-consumer-recovery.test.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/providers/agent-foreground-process-batch.test.ts
  • src/main/ssh/ssh-relay-session-orphan-sweep.test.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ssh/ssh-pty-consumer-recovery.ts
  • src/shared/ssh-relay-pty-ownership-proof.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/shared/ssh-relay-pty-ownership-proof.ts
  • src/shared/foreground-process-evidence.ts
  • src/main/providers/ssh-pty-reattach-absence-discrimination.test.ts
  • src/main/providers/agent-foreground-process-batch.ts
  • src/relay/pty-handler.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.ts
  • src/main/ssh/ssh-orphan-sweep-pane-state-verdicts.test.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.test.ts
  • src/relay/pty-handler-ownership-attestation.test.ts
  • src/main/ipc/pty-daemon-spawn-session-identity.test.ts

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


📝 Walkthrough

Walkthrough

The 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 7f8a9

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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,… 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 …
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 38 functions across 27 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: safely reclaiming orphaned relay PTYs using host attestation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description 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 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 705a1f65-72f7-4b4a-9f18-766bbea850a2

📥 Commits

Reviewing files that changed from the base of the PR and between d4db524 and aa0d6c9.

📒 Files selected for processing (12)
  • src/main/providers/pty-process-info.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.test.ts
  • src/main/ssh/ssh-orphan-relay-pty-sweep.ts
  • src/main/ssh/ssh-relay-session-orphan-sweep.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler-ownership-attestation.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-runtime-services.ts
  • src/relay/ssh-pty-consumer-session-adapter.ts
  • src/shared/pty-consumer-session.ts
  • src/shared/ssh-relay-pty-ownership-proof.test.ts
  • src/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) {

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.

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

Suggested change
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) {

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

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Host-side ownership attestation — pty.listProcesses gains 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 planRelayPtySweep rule plus sweepOrphanedRelayPtys, run once per connect after reattach and gated on the negotiated session-owner grant.
  • Session wiring — SshRelaySession invokes the sweep after reattachKnownPtys on both establish and reconnect.
  • Tests — 31 tests across the rule, client half, session end-to-end, and host attestation; all pass locally.

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

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

ℹ️ No new issues in this delta. The added regression test is correct and pins a load-bearing invariant. The prior deadlineMs suggestion 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.ts asserting a revived PTY lists with paneBound: true but no ownerClientInstanceId, so a relay restart can never make a restored session sweepable.

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

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Independent audit confirms the kill path, and names the precise inversion

The 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

sweepOrphanedRelayPtys calls provider.shutdown(..., { immediate: true, expectedIncarnationId }), driven from reattachKnownPtys at the end of every connect. Membership in plan.sweep is decided by skipReason, whose gates are: host published an incarnationId; ownerClientInstanceId === clientInstanceId; paneBound === true; agentSessionOwners empty; hostAgeMs >= 30_000; !routedPtyIds.has(ptyId).

None of those gates observes whether anything is running in the PTY. agentSessionOwners covers only sessions Orca itself registered — a claude or codex the user typed by hand, a pnpm build, a pytest run, a tail -f register nothing there.

The inversion is here:

if (lease.state !== 'terminated' && lease.state !== 'expired') {
  routed.add(lease.ptyId)
}

expired is excluded from "routed", i.e. treated as evidence of orphanhood — but every production writer of expired writes it precisely because it is declining to stop the remote process:

  • ssh-relay-session.ts:2845 — reattach failed on the transport. Logs "Dropping stale PTY … after relay reattach failed", deletes ownership, marks expired. The remote process is untouched and still running.
  • ssh-relay-session.ts:2717 (restoreReattachedPtyRuntime → missing-surface) — reached only after pty.attach succeeded, so the host has just proven the PTY alive. This branch's own comment reads: "Topology absence alone is not authority to kill a process…" — and then writes expired, which this PR's sweep converts into authority to kill.
  • expireSupersededLeasesForPane — a pane re-leasing under a new relay id expires the predecessor and leaves its process running.
  • suppressRetiredReattachedPty — the one benign writer; it does order a stop.

Exact reaching sequence

Connect N: attachPtyWithRetry fails on a flaky mux round trip → lease expired, ownership deleted. The remote PTY keeps running the user's build or agent.

Connect N+1: the PTY is absent from getPtyIdsForConnection (ownership deleted) and absent from activeLeases (expired), so it is in neither ptyIds nor routedIds. The host still attests this client as owner, paneBound: true, hostAgeMs past 30s, and — because the agent was hand-launched or it is just a build — no agentSessionOwners. skipReason returns null. The plan sweeps it. shutdown({ immediate: true }) kills it.

What this changes about the merge requirement

I had recorded "land #17831 with #17939". That is not sufficient. The sweep's orphan test rests on expired meaning "no longer routed", and expired does not mean that — it is the marker for "we lost contact and declined to act", the exact population that must never be swept.

The dependency is on the lease-vocabulary work:

With those, routedIds can be computed from something that actually means "this lease is not a live orphan" rather than from the absence of a state that means the opposite.

Recommendation: hold this PR until #17965 and #17966 land, then revisit the routedIds predicate directly — do not merge on the strength of #17939 alone.

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

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 — reproduced

Driving the real sweepOrphanedRelayPtys with the state production writes:

#17831 alone:      shutdown calls: [["ssh:prod-host@@pty-build",{"immediate":true,"expectedIncarnationId":"inc-build"}]]
#17831 + #17939:   shutdown calls: []          <- skipped, correctly

So the pairing requirement is real and #17939 does its job.

But the reaching sequence is not the one described. dropStalePty (ssh-relay-session.ts:2818-2850) does not expire a lease on transport failure — it early-returns with reattachAttemptsExhausted unless isSshPtyNotFoundError(error). The reachable path is restoreReattachedPtyRuntime -> 'missing-surface' (:2717), which runs only after pty.attach succeeded — i.e. the host has just proven the PTY alive on that same connect — and then writes expired + deletePtyOwnership. Its own comment reads "Topology absence alone is not authority to kill a process." On the next connect, #17831 converts exactly that into authority to kill.

2. The surviving kill — measured, and one step past where #17939 fixed it

Joining the real relay publisher (resolveAgentForegroundProcessesBatch -> toForegroundProcessEvidence) to the real client reader (planRelayPtySweep), with /proc rows measured in a Linux container:

pane state shellIsForeground verdict
idle shell true SWEPT — correct
foreground job false skipped — this is what #17939 fixed
backgrounded job (sleep 300 &) true SWEPT — wrong
Ctrl-Z suspended job true SWEPT — wrong

Container evidence: with sleep 300 &, the shell reads pgrp=7 tpgid=7 while the job sits in pgrp=8. After Ctrl-Z, the shell returns to pgrp=7 tpgid=7 with the job at state=T pgrp=8.

tpgid == pgid is a foreground-only predicate — it cannot see background or stopped work. And forceKillPosixPtyProcessGroups (src/main/pty/posix-pty-process-groups.ts:89) SIGKILLs every process group attached to that tty, not just the shell. So pnpm build &, npm run dev &, or a Ctrl-Z'd editor are each attested "idle" and killed.

leak, never kill still fails — one step over from where #17939 fixed it.

3. Two structural findings

pty.shutdown has no host-side authorization. this.dispatcher.onRequest('pty.shutdown', (p) => this.shutdown(p)) (src/relay/pty-handler.ts:992) takes no context, unlike pty.spawn and pty.attach. It checks only expectedIncarnationId. The entire nine-condition ownership rule is enforced client-side only, on the one call that irreversibly destroys user work. That is CodeRabbit's unaddressed "Moderate" risk.

#17939's expiredLeasePtyIds guard is a lease-row lookup, and markSshRemotePtyLease returns early when no row exists (ssh-pty-lease-operations.ts:235-238). A PTY tracked only by in-memory ownership leaves no trace for the guard to find.

4. What is verified sound

Credit where due: the attestation is minted only in spawn from the live consumer grant (pty-handler.ts:1872); revive deliberately omits it (:2635); terminated writers really are host-evidence-backed or paired with a pendingKill; and expired pane-bound leases are never pruned. #17939 is genuinely good work.

5. Harness: #17939 fixes one file of nine

claimSshPtyConsumerRecovery mints a fresh randomUUID() and drops owner/serverBuildId when a non-detached entry exists. Stack-attributed probe across src/main/ssh: 73 mints across 9 files — ssh-relay-session.test.ts (27), -reconnect-incarnation (14), -rejected-delivery (12), -data-delivery (7), and five more. #17939 did not touch ssh-relay-session-test-fixtures.ts; its two guards live in its own local establish() helper. A counterfactual run with stable identity still passes, so current assertions don't discriminate — but those eight files silently exercise the fresh-consumer path instead of resume, and any future identity- or resume-dependent assertion there is vacuous with nothing to catch it.

Six further harness gaps make the sweep's session-level coverage structurally incomplete — getPtyIdsForConnection hard-mocked to []; attachForReconnect always resolving so dropStalePty cannot run; persistPtyBinding never returning false so the actual reaching path is unreachable; createMockDeps's store having a no-op markSshRemotePtyLease so no write-then-read (hence no two-connect test) is possible; openSshPtyConsumerSession always negotiated; and the mux stubbed, so nothing joins publisher to reader — which is precisely where the surviving kill in §2 lives.

OSS precedent

No system with this shape reclaims processes on client-side evidence. tmux's only path to session_destroy is gated on destroy-unattached, default off; mosh defaults to "wait indefinitely for a client to reappear"; zed's remote_server does exit after a 10-minute idle, but that is the execution host deciding about itself, not a client reaping the host's processes. VS Code's _isOrphaned() feeds listProcesses() and never shutdown() — the exact inversion this PR performs.

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

  • Greptile "5/5, safe to merge" — wrong; a kill was reproduced.
  • CodeRabbit, reject missing agentSessionOwners — valid concern, but the literal fix would break the feature: pty-handler.ts:2462 omits the key when the list is empty, so requiring Array.isArray would make the sweep a permanent no-op against Orca's own relay. fix(ssh): close two sweep kill paths, and a test harness that hid them #17939's foreground gate is the stronger answer.
  • CodeRabbit, shutdown may land after ownership moves — valid, unaddressed, confirmed in §3.
  • pullfrog, untimed listProcesses on connect — addressed via RELAY_PTY_SWEEP_PASS_BUDGET_MS = 5_000; the pending-kill replay's listing on the same path remains untimed.

Also note the branch is 156 commits behind main, and main has since added recoverRemoteTerminalRuntime — a self-driven reconnect on node-pty failure, i.e. a new trigger for this sweep that CI has never exercised.

To lift the hold

Gate on evidence that can see background and stopped work (session/process-group membership, not tpgid == pgid), and move the ownership check host-side onto pty.shutdown so the irreversible call is authorized where the processes actually live.

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

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:

  • src/relay/pty-handler.ts:2431-2435 — evidenceResults[entryIndex]?.processName produces the pane title.
  • :2436-2450 — the same array element becomes foregroundProcessEvidence, the kill authorization.

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:

  • The snapshot is awaited once at :2413, before a loop that may await per entry.
  • Every entry is then stamped capturedAgeMs: 0 at :2447, unconditionally.
  • capturedAgeMs has zero readers anywhere in the tree (verified). The type validates it (foreground-process-evidence.ts:33-36); the producer hardcodes a value that is false for every entry after the first.

So the authorization is a snapshot of unbounded, unrepresentable age. RELAY_PTY_SWEEP_PASS_BUDGET_MS = 5_000 bounds the RPC, not the evidence. The only time gate that acts, RELAY_PTY_SWEEP_MIN_AGE_MS = 30_000, is sized by its own comment against a concurrent-spawn race — "longer than any single connect round trip" — not against evidence staleness.

This is precisely the inversion the VS Code precedent warns about. isOrphaned() there is deliberately best-effort — a 500ms reply window behind a 4s barrier — and is safe because it feeds listProcesses() and never shutdown(). Those tolerances were sized for "might mis-populate a picker." Reusing that grade of signal to authorize an irreversible kill changes what a false positive costs, and nothing in this design re-sizes for it.

Also correcting both PR bodies: #17939's Defect 1 says dropStalePty is reached by "a reattach that failed on the transport." It is not — ssh-relay-session.ts:2820 early-returns with reattachAttemptsExhausted unless isSshPtyNotFoundError(error). A pure transport sever leaves the lease attached, routed, and never swept, even on #17831 alone. Anyone testing this by severing the transport would see the work survive and conclude wrongly that the path is safe.

Two further items:

  • Layer-4 residual the expired fix doesn't reach: markSshRemotePtyLease returns early when no lease row exists (ssh-pty-lease-operations.ts:236), and both expired writers also call deletePtyOwnership. A PTY with in-memory ownership but no durable lease leaves no trace at all for fix(ssh): close two sweep kill paths, and a test harness that hid them #17939's expiredLeasePtyIds guard, and is swept next connect.
  • e2e is deliberately not in verify.needs (pr.yml:905). For a change that destroys remote processes, the only blocking coverage is the unit layer — which the harness inventory above shows is partly vacuous.

Branch is 156 commits behind main, and main has since added recoverRemoteTerminalRuntime, a self-driven reconnect on node-pty failure. That is a new sweep trigger that fires exactly when the host is degraded, and CI has never exercised it.

@nwparker
nwparker force-pushed the fix/ssh-relay-orphan-pty-sweep branch from aaa3933 to 89161bc Compare September 2, 2026 09:15
@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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.

@nwparker
nwparker force-pushed the fix/ssh-relay-orphan-pty-sweep branch from 89161bc to c28cb74 Compare September 2, 2026 12:11
@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

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 main directly, so there is no parent/child merge ordering to get right and no "parent squash-merged, child now conflicts" window.

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 claude, and with the foreground-only tpgid == pgid gate it takes a pnpm build & or a Ctrl-Z'd editor. Squashing is the safety property, not housekeeping: there is no commit anyone can bisect onto that silently SIGKILLs a user's background job.

Re-verified on this exact tree (not inherited from the earlier run): pnpm tc clean, 5059 tests passed across src/main/ssh + src/relay + src/main/providers + src/main/ipc/pty, SSH docker e2e 6 passed / 2 pre-existing test.fixme skips (exit 0), 0 new code-quality findings across 27 files. The decisive experiment was re-run and the ps bytes its kill decision was made on were fed back through the real TypeScript predicate, which agreed on all four scenarios — backgrounded and Ctrl-Z'd jobs survive by pid, and an idle shell is still reclaimed.

Rebased onto current main (e5a1e79e8e4). main and 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 (#17920) is byte-identical to main.

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

✅ No new issues found.

Reviewed changes

  • Host-side shutdown fence — pty.shutdown gains an optional expectedOwnerClientInstanceId, and assertShutdownOwnership re-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 — shellIsForeground is replaced by shellOwnsEveryTtyProcessGroup, computed in getTtyOccupancy over the same process-group set forceKillPosixPtyProcessGroups would SIGKILL, so backgrounded and Ctrl-Z'd work is attested as busy.
  • expired lease named skip — the sweep now tracks expiredLeasePtyIds separately from routedPtyIds, so a process a writer deliberately left running is never reaped.
  • Class-based absence discrimination — both spawn-execute.ts copies key the destructive lease-expiry branch on isSshPtyAbsentFromRelayError rather than the shared SSH_SESSION_EXPIRED message, so a live restoreRequired PTY no longer has its lease and ownership erased.
  • Truthful evidence age + connect budget — capturedAgeMs is stamped from the actual (worst-case) capture time, RELAY_PTY_SWEEP_MAX_EVIDENCE_AGE_MS bounds staleness at the decision, and RELAY_PTY_SWEEP_PASS_BUDGET_MS covers 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/ssh-relay-orphan-pty-sweep branch from c28cb74 to 806800e Compare September 2, 2026 20:28

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

✅ No new issues found.

Reviewed changes

  • Unified foreground-candidate selection — resolveAgentForegroundProcessesFromIndex now delegates candidate choice to the shared selectForegroundProcessCandidate instead 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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.
@nwparker
nwparker force-pushed the fix/ssh-relay-orphan-pty-sweep branch from 7f8a913 to 3a3c6fc Compare September 2, 2026 21:13
@nwparker
nwparker merged commit 31007c0 into main Sep 2, 2026
4 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant