Skip to content

fix(ssh): give supersession and id-recycling their own lease marks - #17966

Merged
nwparker merged 1 commit into
mainfrom
fix/superseded-lease-marker
Sep 3, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/superseded-lease-marker

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​253 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​242
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​73

Stacked on #17965 — review that first. Closes the last conflation in the SSH lease vocabulary, and unblocks the two readers #17965 had to leave alone.

ELI5

The lease state 'expired' was one word doing three unrelated jobs:

  1. "reattach gave up / we lost contact" — the genuine orphan, which we want to reattach.
  2. "superseded by a newer lease for the same pane" — must never be reattached, or you get the 2→19→20 lease fan-out.
  3. "the relay recycled this id onto a different shell" — must never be reattached, or the user's old pane is handed to whatever process now holds pty-1.

Because those are indistinguishable, ssh-relay-session.ts:1985/:2272 had to exclude all expired leases from bulk reattach — so genuine orphans were never bulk-reattached either. This gives jobs 2 and 3 their own marks, so job 1 can finally be reattached.

field sole writer meaning
supersededBy?: string supersedeSiblingLeasesForPane winner's stored-form ptyId
relayIdRecycled?: true pending-stop replay relay-id-recycled host lists this id under a different incarnation

One predicate, sshRemotePtyLeaseAllowsReattach (src/shared/ssh-types.ts), is now used by both call sites. terminated still returns false unconditionally.

The third job was not in the brief and would have been a silent regression

I briefed this as a two-way split. It isn't. ssh-pending-pty-kill-replay.ts:50-58 writes expired for a third reason, and its comment says the write exists solely to be filtered out by the reattach one step later:

"the reattach one step later filters on lease state and fences only on paneKey/tabId, never on incarnation. Leaving this lease active hands the user's old pane to whatever process now holds the recycled id."

A supersededBy-only change would have reopened that hole, and the paneKey fence cannot catch it — which is exactly why the state was used. Hence two marks, not one.

STA-3077 was not the blocker

#17965 concluded this needed relay-start identity per the STA-3077 note. That note (ssh-pty-lease-operations.ts:118-122) guards upsertSshRemotePtyLease's (targetId, ptyId) match against a recycled pty-N — a different path. supersedeSiblingLeasesForPane already holds winner.ptyId at line 63. Recording the winner needed nothing new.

Recycled ids cannot inherit a stale mark

Both marks are deleted in upsertSshRemotePtyLease when the merged lease lands attached/detached. A restarted relay handing pty-1 to a new shell produces a live upsert, which clears the predecessor's mark before supersession re-derives anything. If a mark ever did leak, the failure direction is exclusion — today's behavior — never fan-out.

Supersession also stamps already-expired predecessors for the same pane (supersededBy only; state and updatedAt untouched, since bumping updatedAt would make a stale row look fresh to getRecentExpiredSshLease, which #17958 owns). Without that, every past orphan for a pane stays in the reattach set forever and each reconnect adds another pty.attach. The invariant is now at most one non-superseded expired lease per pane — the newest, i.e. the actual orphan.

Persistence and wire

normalizeSshRemotePtyLease is a strict whitelist, so both fields are named there or they'd be stripped on every launch (ssh-pending-pty-kill.ts:25-27 records that failure having shipped once). Rule 1 holds both directions: an older build's row carries neither mark and reads as orphan — the only thing that build could have meant — and an older build ignores keys it never heard of. Mistyped values are dropped rather than trusted. cross-version-terminal-wire.unit.test.ts: 10 passed.

User-facing regressions

One accepted cost, stated plainly: leases expired by Reset Relay now enter the bulk set. A reset relay is fresh, so pty.attach answers not-found and ssh-relay-session.ts:2838 re-expires it — the same convergence adoptStablePane already reaches after #17965, just earlier. The stamping above bounds it to one stale row per pane until that pane next spawns.

Otherwise none. Negative controls pin every exclusion: superseded siblings, recycled ids, and terminated leases are all still excluded from bulk reattach, and the cardinality suite stays flat.

Testing

Before (source reverted, new tests in place):

 ❯ src/main/ssh/ssh-pending-pty-kill-replay.test.ts (15 tests | 1 failed)
     × refuses to kill a recycled relay id and expires the lease that named it
 ❯ src/main/persistence-ssh-remote-pty-leases.test.ts (20 tests | 2 failed)
     × salvages both marks rather than stripping them
     × reads a row written before the marks existed as a reattachable orphan
 ❯ src/main/ssh-reattach-pane-cardinality.test.ts (20 tests | 7 failed)
     × never bulk-reattaches a superseded sibling
     × holds the bulk reattach set flat across ten reconnects of one pane
     × bulk-reattaches an expired lease whose reattach only lost contact
     × marks an already-expired orphan superseded once a newer lease wins the pane
     × clears the supersession mark when the id is re-upserted as a live lease
     × never bulk-reattaches a lease whose relay id was recycled
     × never bulk-reattaches a terminated lease, marked or not
 Test Files  3 failed (3)
      Tests  10 failed | 45 passed (55)

After: Test Files 4 passed (4) / Tests 90 passed (90).

Regression sweep across src/main/ssh, persistence, ipc, providers, runtime, src/relay: 14602 passed | 44 skipped. tc:node / tc:web / tc:cli clean. check:code-quality:changed: 0 new findings across 31 files.

Toward consolidation

This is the vocabulary prerequisite for merging SSH into the orca remote: every lease state now means exactly one thing, so the two subsystems can share one predicate instead of each re-deriving intent from an overloaded enum. Several bugs in this sweep (#17957, #17962, #17965) had the same root cause — one path guarding a hazard its twin did not.

@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

Reviewed the full diff (10 files, 1 commit) that separates the three meanings of the expired SSH lease state so genuine orphans can reattach while superseded and recycled-id leases stay excluded.

  • New lease marks and a shared predicate — supersededBy and relayIdRecycled fields added to SshRemotePtyLease, with sshRemotePtyLeaseAllowsReattach as the single decision point (src/shared/ssh-types.ts).
  • Supersession stamps already-expired predecessors — supersedeSiblingLeasesForPane now marks them supersededBy while leaving state/updatedAt untouched, bounding the reattach set to one orphan per pane.
  • Recycled-id retirement records its own mark — the pending-stop replay passes { relayIdRecycled: true } so the reattach fence no longer relies on expired alone.
  • Live re-upsert clears both marks — a restarted relay claiming pty-1 for a new shell drops the predecessor's marks before supersession re-derives anything.
  • Persistence round trip — normalizeSshRemotePtyLease whitelists both fields with strict type checks; both reattach call sites in ssh-relay-session.ts switch to the shared predicate.

I traced the state machine against the readers of expired (getRecentExpiredSshLease, terminateSessions, recoverTerminalPane) and the pre-existing markSshRemotePtyLeasesAttachedAsync behavior that leaves expired leases expired after a successful reattach — the design is internally consistent and the new tests use exact, fail-able assertions rather than snapshots.

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

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Verified correction: relayIdRecycled is unnecessary by construction for current relays

I justified this mark by saying a restarted relay renumbers from pty-1, so an id can be recycled onto a different shell. That is no longer true, and I verified it directly on origin/main:

// src/relay/pty-handler.ts:1743-1746
let id: string
do {
  id = `pty2:${encodeURIComponent(this.ptyIdMintEpoch)}:${this.nextId++}`
} while (this.ptys.has(id) || this.pendingReviveIds.has(id))

ptyIdMintEpoch is private readonly, defaulted in the constructor to randomUUID(), and production constructs PtyHandler with no argument (src/relay/relay-runtime-services.ts:40). Every relay start gets a fresh UUID epoch and embeds it in every id it mints. A restarted relay therefore cannot reissue a predecessor's id, and revive() re-using a serialized pty2:<oldEpoch>:N is safe precisely because it can never collide with a freshly minted pty2:<newEpoch>:1.

pty-N is the legacy format, and both compensating sites say so:

  • pty-handler.ts:426 — "Rejects legacy cross-relay-generation id collisions (a reset relay reused pty-N)."
  • pty-handler.ts:1947 — "Why: legacy pty-N ids repeated across relay generations…"

So relayIdRecycled is reachable only against a stale relay bundle still minting legacy ids. It is not wrong to carry it — mixed bundles are real — but the PR body overstates its necessity, and the STA-3077 note it leans on is now half-false: "needs a relay-start identity the lease does not carry" is true for legacy ids and false for pty2: ids, where the identity is sitting inside the string the lease already stores, unparsed.

The sharper framing: the mint was fixed; the lease was never told. upsertSshRemotePtyLease still keys on a bare (targetId, ptyId) pair and has no idea the id may already carry an epoch. Parsing it would make the mark redundant for all non-legacy hosts.

What survives, and is genuinely independent

supersededBy is not solved by the id scheme and remains the real finding. Its root cause is stated in the lease module itself:

Superseded leases are marked expired, never terminated: losing a lease is not evidence the shell died, so the remote process is deliberately left running.

So expired carries both "a sibling won this pane" and "the grace window ran out," and ssh-relay-session.ts:2273-2275 filters both away identically. That is the defect this PR actually fixes, and it stands on its own.

Design note worth recording for the consolidation

A four-value enum with no evidence field cannot carry why, so every new distinction has to become another optional mark beside the enum — and every reader must independently know to consult it. The terminal daemon rejected that shape: DaemonProcessEvidence puts reason and evidenceSources inside the discriminated arm, so a reader cannot consume a state without also seeing what produced it.

That is the structurally better design, and it is the one the consolidated path should adopt. Recording it here rather than reworking this PR, which is a correct narrowing of a real bug.

…tell them apart

`expired` was one word doing two unrelated jobs — "a newer lease won this pane"
and "reattach lost contact" — so `reattachKnownPtys` had to exclude all of them.
That kept the 2 -> 19 -> 20 fan-out fixed at the cost of never bulk-reattaching a
genuine orphan; those recovered only through the slower `adoptStablePane` path.

The blocker cited in #17965 does not apply. The STA-3077 note guards
`upsertSshRemotePtyLease`'s match against a RECYCLED `pty-N` after a relay
restart. `supersedeSiblingLeasesForPane` is a different path and already holds
`winner.ptyId` when it expires a predecessor, so recording which lease won needs
no relay-start identity.

`SshRemotePtyLease` gains two optional marks, each meaning exactly one thing:

- `supersededBy` — the winner's stored-form ptyId, written only by supersession.
- `relayIdRecycled` — written only by the pending-stop replay's
  `relay-id-recycled` retirement. That retirement wrote `expired` *purely* to
  keep the lease out of the reattach that runs one step later ("hands the user's
  old pane to whatever process now holds the recycled id"), and the reattach
  fences on paneKey/tabId, never on incarnation. Relaxing the filter without
  this would have silently reopened that hole.

Bulk reattach now skips a lease carrying either mark and re-adopts the rest, via
one shared `sshRemotePtyLeaseAllowsReattach`. `terminated` is untouched.

Recycled-id safety: both marks are dropped whenever the id is re-upserted
`attached`/`detached`, so a relay that renumbered onto a new shell cannot inherit
its predecessor's mark. Supersession also stamps an ALREADY-expired predecessor
for the same pane — same evidence, and it is what bounds the reattach set, since
otherwise every past orphan for that pane would stay reattachable forever. Its
`updatedAt` deliberately stays put: bumping it would make a stale lease look
recent to `getRecentExpiredSshLease`.

Persistence: the lease loader is a strict whitelist, so both fields are named in
`normalizeSshRemotePtyLease` or they would be stripped on every launch. Absence
reads as "orphan", which is the only thing an older build could have meant, and
an older build ignores keys it has never heard of (remote-wire Rule 1).
@nwparker
nwparker force-pushed the fix/superseded-lease-marker branch from db53b3e to a913860 Compare September 3, 2026 04:37
@nwparker
nwparker changed the base branch from fix/expired-lease-permits-reattach to main September 3, 2026 04:38
@nwparker
nwparker merged commit f2e95e7 into main Sep 3, 2026
1 check failed
nwparker added a commit that referenced this pull request Sep 3, 2026
`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of #17957 (respawn gated on the
runtime liveness verdict), #17965 (`expired` no longer withdraws bindings)
and #17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
nwparker added a commit that referenced this pull request Sep 3, 2026
…17969)

`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of #17957 (respawn gated on the
runtime liveness verdict), #17965 (`expired` no longer withdraws bindings)
and #17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tell them apart (stablyai#17966)

`expired` was one word doing two unrelated jobs — "a newer lease won this pane"
and "reattach lost contact" — so `reattachKnownPtys` had to exclude all of them.
That kept the 2 -> 19 -> 20 fan-out fixed at the cost of never bulk-reattaching a
genuine orphan; those recovered only through the slower `adoptStablePane` path.

The blocker cited in stablyai#17965 does not apply. The STA-3077 note guards
`upsertSshRemotePtyLease`'s match against a RECYCLED `pty-N` after a relay
restart. `supersedeSiblingLeasesForPane` is a different path and already holds
`winner.ptyId` when it expires a predecessor, so recording which lease won needs
no relay-start identity.

`SshRemotePtyLease` gains two optional marks, each meaning exactly one thing:

- `supersededBy` — the winner's stored-form ptyId, written only by supersession.
- `relayIdRecycled` — written only by the pending-stop replay's
  `relay-id-recycled` retirement. That retirement wrote `expired` *purely* to
  keep the lease out of the reattach that runs one step later ("hands the user's
  old pane to whatever process now holds the recycled id"), and the reattach
  fences on paneKey/tabId, never on incarnation. Relaxing the filter without
  this would have silently reopened that hole.

Bulk reattach now skips a lease carrying either mark and re-adopts the rest, via
one shared `sshRemotePtyLeaseAllowsReattach`. `terminated` is untouched.

Recycled-id safety: both marks are dropped whenever the id is re-upserted
`attached`/`detached`, so a relay that renumbered onto a new shell cannot inherit
its predecessor's mark. Supersession also stamps an ALREADY-expired predecessor
for the same pane — same evidence, and it is what bounds the reattach set, since
otherwise every past orphan for that pane would stay reattachable forever. Its
`updatedAt` deliberately stays put: bumping it would make a stale lease look
recent to `getRecentExpiredSshLease`.

Persistence: the lease loader is a strict whitelist, so both fields are named in
`normalizeSshRemotePtyLease` or they would be stripped on every launch. Absence
reads as "orphan", which is the only thing an older build could have meant, and
an older build ignores keys it has never heard of (remote-wire Rule 1).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#17969)

`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of stablyai#17957 (respawn gated on the
runtime liveness verdict), stablyai#17965 (`expired` no longer withdraws bindings)
and stablyai#17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
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