Skip to content

fix(ssh): close two sweep kill paths, and a test harness that hid them - #17939

Closed
nwparker wants to merge 5 commits into
fix/ssh-relay-orphan-pty-sweepfrom
fix/sweep-kill-paths
Closed

nwparker wants to merge 5 commits into
fix/ssh-relay-orphan-pty-sweepfrom
fix/sweep-kill-paths

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1058 $\color{#cf222e}{\Huge{\mathbf{−}}}$​45 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1013
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​349 $\color{#cf222e}{\Huge{\mathbf{−}}}$​27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​322

Stacked on #17831, which is do-not-merge without this. Retarget to main once that merges.

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.

Verification

pnpm tc clean; check:code-quality:changed 0 new findings across 17 files; src/main/ssh + src/main/providers + src/relay + src/shared all green (2650 / 1557 / 8052). All nine original conditions still hold; none weakened.

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.

Verification

pnpm tc clean. check:code-quality:changed: 0 new findings. No lint disables, no max-lines bump, no @ts-ignore.

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.

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

scenario predicate SIGKILL issued job pid after
idle shell idle yes — (shell reclaimed, Zs)
sleep 300 & busy no alive
sleep 300 + Ctrl-Z busy no alive
sleep 300 foreground busy no alive

The first row is the one that matters as much as the other three: the fix does not turn the feature into a no-op. That was the open question at the top of this description, and it is now answered by measurement rather than by argument.

Rebase

Both branches were ~156 commits behind. Rebased onto main and checked against recoverRemoteTerminalRuntime, which main added since — a self-driven reconnect on relay node-pty failure, and therefore 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.

Still not ready to ship, and not because of code

Every fix here narrows the predicate, and all of it has only ever run against mocks. Two things wanted before merge:

  1. A real-host check that the sweep still reaps anything. shellIsForeground has never run against a live ps on a relay host. If tpgid reads unexpectedly on some shell or platform, the sweep degrades to a permanent no-op, SSH relay leaks orphaned PTY sessions until "Maximum number of PTY sessions reached (50)" #9819's leak stays open, and nothing would say so.
  2. A written decision on the dispose coupling above.

Also: RELAY_PTY_SWEEP_MAX_PER_PASS = 8 refuses-rather-than-truncates only within a pass; across a reconnect storm the ceiling resets each time. Defensible given the narrowed predicate, but an assumption, not a guarantee.

Refs #9819

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Real-host verification — shellIsForeground discriminates correctly

This was the one thing I said I would not ship without: "shellIsForeground has never run against a live ps on a relay host. If tpgid reads unexpectedly on some shell or platform, the sweep degrades to a permanent no-op, #9819's leak stays open, and nothing would say so."

Measured on a production Ubuntu relay host with 19 live relays and ~107 shells:

   PID    PPID    PGID   TPGID STAT  COMM
   7964     895    7964    8480 Ss   bash          <- foreground group is 8480
   8480    7964    8480    8480 Sl+  node          <- ...which is a running codex
   8487    8480    8480    8480 Sl+  codex
  28238 4063078   28238   28264 Ss   bash          <- foreground group is 28264
  28264   28238   28264   28264 Sl+  claude        <- ...a hand-launched claude
  32633   27765   32633   32633 Ss+  bash          <- idle: tpgid == pgid
  35075   27765   35075   35075 Ss+  bash          <- idle
idle shells (tpgid == pgid):        84   -> sweep-eligible
busy shells (tpgid != pgid):        23   -> protected

The signal works, and it works on precisely the case defect 2 was about. Both claude and codex above were launched by hand — neither appears in agentSessionOwners, so under #17831 as written both panes were sweepable. Under this PR both are protected, because the host observes their foreground group is not the shell.

And the inverse holds: 84 idle shells are still correctly identified, so the sweep has not degraded into a permanent no-op — the failure mode I was most worried about, precisely because it would have been silent.

What this does and does not establish

  • Establishes: tpgid/pgid are populated and meaningful on a real Linux relay host under real load, and the busy/idle split matches what a human would call busy or idle.
  • Does not establish: that the sweep end-to-end reaps a genuine orphan on that host — I read the process table, I did not run a sweep against it. Nor does it cover non-Linux relays; Windows publishes no foreground evidence at all and therefore never sweeps, which is fail-safe but means this signal is Linux-only in practice.

Same host also carries 19 orphaned relays (oldest 6.7 days) and 193 leaked PTY master fds — measurements posted to #8585 and #8362. That is the accumulation #9819 is about, still present, which is what makes keeping the sweep alive worth the care.

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

Important

The code is correct and the two kill paths are genuinely closed, but this is not mergeable until two pre-merge conditions are settled — both of which the PR body already gates on. Confirm them here so they don't get lost in the stack.

Reviewed changes

  • expired leases get their own skip — clientClaims splits expired from routed, so the four writers that deliberately leave the remote process running no longer license a sweep.
  • Idle-shell attestation gate — the sweep now requires the owning host to publish verdict: 'live', processName: null, and shellIsForeground === true before it stops anything.
  • shellIsForeground evidence — resolveAgentForegroundProcessesFromIndex computes root.tpgid === root.pgid and toForegroundProcessEvidence publishes it as an additive optional field.
  • One connect budget — a single absolute 5 s deadline now bounds the listing and every stop; overrun is an empty pass, never a failed connect.
  • Mint warning — claimSshPtyConsumerRecovery logs instead of silently re-minting a consumer identity.
  • Harness fix — per-test targets plus two establish() guards make the six vacuous session-level tests fail loudly when the identity mints.

I verified the core claims against the code: all four expired writers leave the process running (supersedeSiblingLeasesForPane, dropStalePty at ssh-relay-session.ts:2845, the missing-surface refusal, and suppressRetiredReattachedPty), the reattach path already filters expired out of routedPtyIds (ssh-relay-session.ts:2277) so the new skip is not masked, and claimSshPtyConsumerRecovery does mint a fresh randomUUID() for a target it holds a live in-memory entry for. All five changed test files pass locally (49 tests).

⚠️ Windows and pre-shellIsForeground hosts now never sweep — the leak goes silent

The gate is fail-safe, but it is also absolute: the sweep only fires when the owning host is a relay running this build, and it never fires on Windows. A mixed-version client/host pairing — which the wire-compatibility doc says is the normal state — degrades to a permanent no-op, and #9819's leak stays open with no signal.

Technical details
# Sweep is inert until every relay publishes `shellIsForeground`, and forever on Windows

## Affected sites
- `src/shared/ssh-relay-pty-ownership-proof.ts:85-105` — `foregroundSkipReason` skips on `evidence === undefined` and on `shellIsForeground !== true`, so an old relay (publishes evidence without the new field) or a Windows relay (publishes nothing) can never be swept.
- `src/relay/pty-handler.ts:2411,2436-2450` — `foregroundProcessEvidence` is only computed on `process.platform !== 'win32'`; Windows publishes `undefined`.
- `src/main/providers/agent-foreground-process-batch.ts:122` — `root.tpgid === root.pgid` treats a shell at the prompt with a backgrounded job as "idle" (background jobs don't own the foreground group), so a small residual kill risk remains even on POSIX.

## Required outcome
- A written decision that a permanent Windows no-op is acceptable (fail-safe vs. the leak never closing there).
- A real-host check that `tpgid` reads as expected on the shells/platforms the relay actually serves, including the backgrounded-job residual above.
- (Author already listed) a written decision on the `disposeAndPersist`-marks-`terminated` coupling, which the mint warning deliberately leaves unfixed to avoid a mass-kill path.

ℹ️ Nitpicks

  • src/main/ssh/ssh-pty-consumer-recovery.ts:40-48 — the "no recovery record" warning also fires on a normal first-ever connect to a target, which is indistinguishable from a genuinely lost record. That means every user's first connection to each host emits a warning about a previous identity that never existed. Consider gating on whether the target was claimed earlier in this process so the warning only fires when something was actually lost.

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

Second verification: WSL (Ubuntu-24.04) on a Windows host

I flagged earlier that shellIsForeground had only been checked on one Linux host. Extended it to WSL, which is a supported topology and a different kernel/init arrangement:

    PID    PGID   TPGID TTY     COMM
    328     328     377 pts/1   login
    377     377     377 pts/1   bash      <- idle: tpgid == pgid
  25425   25425   25578 pts/0   bash      <- busy: foreground group is 25578...
  25578   25578   25578 pts/0   claude    <- ...a running claude

Same result as the SSH relay host: a bash whose foreground group is a running claude reads tpgid != pgid and is protected; an idle bash reads tpgid == pgid. Under #17831 as written that claude pane was sweepable, since a hand-launched agent has no agentSessionOwners entry.

So the signal is sound on two independent Linux environments — a bare Ubuntu SSH host and a WSL2 distro — and in both cases the process it protects is exactly the one defect 2 was about.

Unchanged caveats: processes without a controlling terminal report tpgid -1 and are skipped by the predicate's own verdict/shellIsForeground gates rather than swept; and Windows relay hosts publish no foreground evidence at all, so they never sweep. Both fail-safe.

One incidental finding worth recording, since it is the hazard AGENTS.md documents: reaching WSL from Git Bash required MSYS_NO_PATHCONV=1. Without it MSYS rewrote --exec /bin/bash into C:/Program Files/Git/usr/bin/bash and wsl.exe failed with execvpe(...) failed: No such file or directory. That is the same path-mangling class the repo already warns about for cmd.exe /c from Git Bash.

Nothing reconciled the relay's live PTY list against what the app still
tracks, so a pane whose id the client lost held a relay slot until the
daemon died — the "Maximum number of PTY sessions reached (50)" wall.

#9819 proposed sweeping any pane-bound PTY "the app no longer owns or
leases". That is not proof of orphanhood: absence from a client-side set
is `unverifiable` by construction, and a second machine on the same build
attaches to the SAME relay, where its live agents are missing from this
client's store for exactly the same reason a real orphan is.

So the host attests instead. PtyHandler records the authenticated
consumer identity behind the connection that asked it to spawn each PTY,
read from the live grant rather than from a spawn parameter, and
publishes it on pty.listProcesses alongside a host-measured age and
whether the PTY is pane-bound. A client may stop a PTY only when the
owning host names THIS client as its creator, this client holds the
negotiated session-owner grant, the PTY is pane-bound, older than 30s,
carries no adoptable agent session, and this client has no lease, live
route or pending stop for it. Every stop is fenced on the incarnation the
same listing published.

All three published fields are optional (Rule 1), and every absence reads
as unknown: against a host that predates them the sweep stops nothing.
Revived PTYs are deliberately left unattested.
Two independent paths let the #9819 sweep stop a process the user was
running, and the design principle is leak-never-kill.

1. An expired lease is not abandonment. supersedeSiblingLeasesForPane,
   dropStalePty and the missing-surface refusal all write 'expired'
   precisely because they will not stop the remote process; routedPtyIds
   read that as no route and swept it. Expired ids now carry their own
   named skip.
2. agentSessionOwners answers 'did Orca register an agent session here',
   not 'is anything running'. A hand-launched claude has an empty list.
   The same listing's foregroundProcessEvidence is the host's own
   observation, so the sweep now requires it to positively attest an idle
   shell. The host publishes shellIsForeground (tpgid == pgid) so an
   unrecognized foreground process - a build, an editor - counts too.

Also: one 5s budget for the whole pass instead of the mux default on the
connect path, and a log when the consumer identity is re-minted, which
silently retires the sweep.

The session-level tests shared one target id; the second and later
establish() calls re-minted the consumer identity, so six of seven
assertions passed for the wrong reason. Now one target per test, guarded
on both the pass running and the identity holding.
Three ways the orphan sweep could still SIGKILL live user work.

`shellIsForeground` was `tpgid === pgid`, a foreground-only predicate.
Measured 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. Only the job's own row differs. So
`pnpm build &` and a suspended editor were each attested idle, and the
stop that follows SIGKILLs every process group on the tty. It is now
`shellOwnsEveryTtyProcessGroup`, measured over the same set of process
groups the kill would reach, and false when anything on the tty is
stopped. No new probe: `tpgid` already identifies the terminal, because
a process group has one session and a session at most one controlling
terminal.

`capturedAgeMs` was hardcoded to 0 by a producer that awaited the
snapshot once before a loop that may await per entry, and it had zero
readers anywhere. It is now stamped from when the capture was taken —
deliberately as an upper bound, since the table is TTL-shared — and the
sweep refuses evidence older than its own pass budget, counting its own
elapsed time since the listing arrived. Stale degrades to "do not
sweep", never to "sweep". The display consumer of the same measurement
keeps no age budget, now as a stated decision rather than an accident.

`pty.shutdown` took no request context while `pty.spawn` and
`pty.attach` both did, so the ownership rule was enforced client-side
only on the one irreversible call. It gains an optional
`expectedOwnerClientInstanceId`, symmetric with the incarnation fence
already there; the host refuses unless the connection still
authenticates as that identity AND it recorded that identity at spawn.
Rule 1: no reader requires it, an ordinary teardown omits it, and an old
host ignoring it behaves exactly as today.

The load-bearing test joins the real publisher to the real client reader
over `ps` captured verbatim from a container. Reverting the predicate
fails the backgrounded and suspended rows and nothing else.
@nwparker
nwparker force-pushed the fix/ssh-relay-orphan-pty-sweep branch from aaa3933 to 89161bc Compare September 2, 2026 09:15
@nwparker
nwparker force-pushed the fix/sweep-kill-paths branch from 0fe3602 to a20cf88 Compare September 2, 2026 09:15
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 and only its source stream is not.

`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 when the row is
already gone, leaving no trace at all, and the orphan sweep reads a
host-attested, route-less, pane-bound shell it has no record of as one
it may stop.

The destructive branch now keys on `isSshPtyAbsentFromRelayError`, the
class that exists for exactly this distinction and is already used this
way in `liveness.ts`. Being too strict here is self-correcting: a lease
for a genuinely dead PTY is retired by the next reattach on real host
evidence.

Both copies of `spawn-execute.ts` are fixed and both are covered —
reverting either one reddens its own test.
@nwparker
nwparker force-pushed the fix/sweep-kill-paths branch from a20cf88 to 93ff42c Compare September 2, 2026 09:17

@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 (delta against the prior Pullfrog review at 0fe3602)

  • Replaced the foreground-only idle predicate — shellOwnsEveryTtyProcessGroup now requires the shell to own the foreground group and be the sole process group on the pane's tty, with no T/t-stopped row. It measures the same set forceKillPosixPtyProcessGroups SIGKILLs, so a backgrounded & job or a Ctrl-Z'd editor is now attested busy instead of idle.
  • Stamped capturedAgeMs truthfully — the relay now dates the observation from the snapshot's worst-case capture time (PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS), and the plan enforces RELAY_PTY_SWEEP_MAX_EVIDENCE_AGE_MS on top of the client-side listing latency, so stale evidence degrades to do not sweep.
  • Added a host-side fence to the irreversible call — pty.shutdown gains an optional expectedOwnerClientInstanceId, checked against both the live connection grant and the recorded spawn-time owner, closing CodeRabbit's unaddressed asymmetry.
  • Keyed the expired-lease branch on the error class — both spawn-execute.ts copies now use isSshPtyAbsentFromRelayError instead of .includes(SSH_SESSION_EXPIRED), so a live-PTY restoreRequired refusal no longer expires the lease and erases the client's only record of a running process.
  • Hardened the harness that hid the first two — per-test targets plus two establish() guards, and the cross-half ssh-orphan-sweep-pane-state-verdicts.test.ts drives the real publisher into the real reader over verbatim ps captures.

I verified the core claims against the code: SshPtyAbsentFromRelayError is thrown only at ssh-pty-session-reattach.ts:238 (relay answered "not found", non-mismatch), so the class check discriminates correctly; assertShutdownOwnership runs before any kill and revived PTYs deliberately omit ownerClientInstanceId, so the fence refuses them; and getTtyOccupancy skips tpgid <= 0/pgid === undefined rows so the ps and harness rows don't pollute the occupancy. The new predicate is strictly narrower than the base's tpgid === pgid, so the delta removes false positives and introduces none.

The two remaining items in the author's "Still not ready to ship" list (a real-host reaping check and the dispose-coupling decision) are the author's own pre-merge gates, not code defects.

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

nwparker added a commit that referenced this pull request Sep 2, 2026
…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 89161bc to c28cb74 Compare September 2, 2026 12:11
@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Folded into #17831 and closing — not abandoned. Every commit, test and finding from this PR is in #17831's tree; nothing was dropped.

Why fold rather than merge in sequence

This PR was stacked on #17831, so the intended order was "merge the parent, then merge this". That order is unsafe here, and the reason is stronger than the usual stacked-PR friction:

The sweep kills live processes at every intermediate commit of its own history.

state foreground gate what it reaps
#17831 alone none at all a hand-launched claude, a vim, a running build — agentSessionOwners is empty for all of them, which is this PR's own Defect 2
#17831 + this PR's original commit foreground-only tpgid == pgid pnpm build &, a Ctrl-Z'd editor
the squashed result whole-tty nothing that is running

So merging #17831 first would put a known live-process-killing bug on main for however long the follow-up took — and "however long" is not reliably short, because a squash-merged parent makes the child conflict spuriously (that pattern bit this sweep four times today). Given the failure mode is silently SIGKILL a user's running build, neither the window nor the dependency on a smooth conflict resolution was acceptable.

Squashing into one commit is what makes the guarantee absolute: there is no commit anyone can bisect onto that reaps live work.

What carried over

All three defects from this PR, unchanged in substance:

  • Defect 1 — an expired lease is unverifiable, never exited; it now has its own named skip. The corrected writer map is in fix(ssh): reclaim relay PTYs the client has provably lost, on host attestation only #17831's body (this PR's original text had the reaching path wrong: handlePtyReattachFailure is reached only when the host answered "not found"; a pure transport sever early-returns as reattachAttemptsExhausted and leaves the lease attached. The live-process path is restoreReattachedPtyRuntime → 'missing-surface', reached only after pty.attach succeeded).
  • Defect 2 — agentSessionOwners ≠ "an agent is running here". The host must positively attest an idle shell.
  • Defect 3 — the harness defect where one shared TARGET made six of seven session-level tests pass for the wrong reason, plus the two guards inside establish().

And the three blockers found afterwards, which are the reason this could not merge as written:

  • the idle predicate was foreground-only and blind to & and Ctrl-Z;
  • capturedAgeMs was a hardcoded 0 with zero readers, while being the only field that could bound staleness;
  • pty.shutdown took no request context, so the nine-condition rule was enforced client-side only on the one irreversible call.

The correction this PR most deserves credit for

Its own closing section asked for exactly the right thing — "a real-host check that the sweep still reaps anything… if tpgid reads unexpectedly the sweep degrades to a permanent no-op and nothing would say so." That instinct was right and the check was run; it just validated the wrong predicate. tpgid == pgid is foreground-only, so a 23-busy/84-idle split says the gate is not a no-op while saying nothing about the two states it cannot see. Measured on a real bash -i on a real pty, a shell holding sleep 300 & and a shell holding a Ctrl-Z'd job are byte-identical to an idle prompt at pgid/tpgid/stat.

#17831 now answers both halves by measurement: backgrounded and suspended jobs survive a real group SIGKILL by pid, and an idle shell is still reclaimed.

Review history here stays worth reading — the revert matrix, the harness finding, and the clientInstanceId re-minting note (deliberately not "fixed", because stabilising it without first fixing disposeAndPersist would turn reconnect into a mass kill) are all recorded above and are not repeated in full on #17831.

@nwparker nwparker closed this Sep 2, 2026
nwparker added a commit that referenced this pull request Sep 2, 2026
…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 added a commit that referenced this pull request Sep 2, 2026
…testation only (#17831)

* fix(ssh): reclaim relay PTYs the host attests this client orphaned (#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.

* fix(i18n): restore the activity-options key the rebase dropped

* fix(i18n): union en.json with main so the rebase cannot drop keys
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