Repository navigation
fix(pty): key buffered pre-attach PTY exits on the incarnation, not a sequence fence - #17010
Conversation
… clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. #16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk #16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep #16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now.
A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard.
It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (9)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe PTY preload and renderer APIs now carry optional incarnation identifiers on spawn replies and exit events. The pre-handler buffer validates and stores these identifiers, then filters buffered exits from different PTY lifetimes. The IPC connection and background launch flows pass incarnation identifiers during registration and attachment. Tests cover foreign, matching, missing, and malformed identifiers. Merge Risk: 🟡 Moderate · up to The PR prevents many stale exit notifications from killing replacement terminals, but some direct-delivery and early-reattachment paths still match only the reusable PTY ID. A delayed exit from an older terminal lifetime could still make a healthy replacement session appear exited, so merge should wait for this lifecycle check to be addressed or explicitly accepted. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 34.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 14 files. (1 skipped: 1 unsupported.) Full details: Description checkExplanation The description gives a detailed explanation of the problem, implementation, compatibility behavior, scope, and test evidence. However, it does not complete required template sections, including the mandatory linked issue and visual proof or an explicit N/A statement. Resolution Add the issue reference after “Fixes #”. Add the required visual proof, or write
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 92550e06-7532-4a53-89fa-b6cd1b0942cb
📒 Files selected for processing (10)
src/preload/api/pty-api.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/ipc-pty-connect.tssrc/renderer/src/components/terminal-pane/ipc-pty-spawn-request.tssrc/renderer/src/components/terminal-pane/pty-dispatcher.tssrc/renderer/src/components/terminal-pane/pty-exit-delivery.tssrc/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.tssrc/renderer/src/components/terminal-pane/pty-pre-handler-buffer.tssrc/renderer/src/components/terminal-pane/pty-transport-recycled-pty-incarnation.test.tssrc/renderer/src/components/terminal-pane/pty-transport-test-harness.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
…ust the check
Review caught a swallowed exit. Keying only the comparison on the incarnation
while the storage stayed one slot per pty id left the two races this buffer
exists for able to cancel each other out:
1. the freshly spawned shell dies before the pane attaches -> its exit (X) is
buffered;
2. the relay flushes the previous owner's exit for the same recycled id (W),
which OVERWRITES X in the single slot;
3. the spawn reply names X, so the identity discard drops W -- the only
record left.
registerExit then finds nothing and the pane binds to a PTY that is dead and
will never be reported dead: a hang instead of the blank tab #16970 fixed.
Store one record per lifetime, capped at 4 per id, so W can never evict X. A
duplicate exit for a lifetime replaces that lifetime's record rather than
crowding out another's; drain still delivers the newest survivor, preserving
the last-write-wins behaviour a single slot always had.
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9fffc6bd-8b4e-40bc-bd90-d3faf0a682ba
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.tssrc/renderer/src/components/terminal-pane/pty-pre-handler-buffer.tssrc/renderer/src/components/terminal-pane/pty-transport-recycled-pty-incarnation.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/terminal-pane/pty-transport-recycled-pty-incarnation.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| const sameLifetime = exits.findIndex((entry) => entry.incarnationId === exit.incarnationId) | ||
| if (sameLifetime !== -1) { | ||
| exits[sameLifetime] = exit | ||
| return | ||
| } | ||
| exits.push(exit) | ||
| if (exits.length > PRE_HANDLER_PTY_EXIT_MAX_INCARNATIONS_PER_PTY) { | ||
| exits.shift() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Evict the oldest sequence, not the first array entry.
After A, B, C, D, a duplicate A, then E, Line 220 keeps newest A in place and Line 225 removes it. Foreign-incarnation filtering can then leave the current lifetime with no exit. Move replacements to the tail, or evict the lowest sequence. Add this capacity regression.
Proposed fix
if (sameLifetime !== -1) {
- exits[sameLifetime] = exit
+ exits.splice(sameLifetime, 1)
+ exits.push(exit)
return
}📝 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.
| const sameLifetime = exits.findIndex((entry) => entry.incarnationId === exit.incarnationId) | |
| if (sameLifetime !== -1) { | |
| exits[sameLifetime] = exit | |
| return | |
| } | |
| exits.push(exit) | |
| if (exits.length > PRE_HANDLER_PTY_EXIT_MAX_INCARNATIONS_PER_PTY) { | |
| exits.shift() | |
| const sameLifetime = exits.findIndex((entry) => entry.incarnationId === exit.incarnationId) | |
| if (sameLifetime !== -1) { | |
| exits.splice(sameLifetime, 1) | |
| exits.push(exit) | |
| return | |
| } | |
| exits.push(exit) | |
| if (exits.length > PRE_HANDLER_PTY_EXIT_MAX_INCARNATIONS_PER_PTY) { | |
| exits.shift() |
… call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover.
Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work.
… sequence fence (stablyai#17010) * fix(pty): key buffered pre-attach exits on the PTY incarnation, not a clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. stablyai#16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk stablyai#16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep stablyai#16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now. * fix(pty): read the incarnation through the shared guard, not truthiness A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard. * refactor(pty): name the bounded-map helper after what it does It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change. * fix(pty): key the buffered-exit STORAGE on the incarnation too, not just the check Review caught a swallowed exit. Keying only the comparison on the incarnation while the storage stayed one slot per pty id left the two races this buffer exists for able to cancel each other out: 1. the freshly spawned shell dies before the pane attaches -> its exit (X) is buffered; 2. the relay flushes the previous owner's exit for the same recycled id (W), which OVERWRITES X in the single slot; 3. the spawn reply names X, so the identity discard drops W -- the only record left. registerExit then finds nothing and the pane binds to a PTY that is dead and will never be reported dead: a hang instead of the blank tab stablyai#16970 fixed. Store one record per lifetime, capped at 4 per id, so W can never evict X. A duplicate exit for a lifetime replaces that lifetime's record rather than crowding out another's; drain still delivers the newest survivor, preserving the last-write-wins behaviour a single slot always had. * fix(pty): filter buffered exits by lifetime inside the buffer, not at call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover. * chore: drop unrelated formatter churn in reliability-gates.jsonc Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work. (cherry picked from commit a907dd2)
… sequence fence (stablyai#17010) * fix(pty): key buffered pre-attach exits on the PTY incarnation, not a clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. stablyai#16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk stablyai#16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep stablyai#16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now. * fix(pty): read the incarnation through the shared guard, not truthiness A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard. * refactor(pty): name the bounded-map helper after what it does It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change. * fix(pty): key the buffered-exit STORAGE on the incarnation too, not just the check Review caught a swallowed exit. Keying only the comparison on the incarnation while the storage stayed one slot per pty id left the two races this buffer exists for able to cancel each other out: 1. the freshly spawned shell dies before the pane attaches -> its exit (X) is buffered; 2. the relay flushes the previous owner's exit for the same recycled id (W), which OVERWRITES X in the single slot; 3. the spawn reply names X, so the identity discard drops W -- the only record left. registerExit then finds nothing and the pane binds to a PTY that is dead and will never be reported dead: a hang instead of the blank tab stablyai#16970 fixed. Store one record per lifetime, capped at 4 per id, so W can never evict X. A duplicate exit for a lifetime replaces that lifetime's record rather than crowding out another's; drain still delivers the newest survivor, preserving the last-write-wins behaviour a single slot always had. * fix(pty): filter buffered exits by lifetime inside the buffer, not at call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover. * chore: drop unrelated formatter churn in reliability-gates.jsonc Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work.
ELI5
Terminals get numbered names like
pty-1. When the SSH relay restarts it starts counting frompty-1again, so a brand-new terminal can be handed the exact name a terminal that just died was using.The renderer keeps a small holding area for "the shell died" messages that arrive a split second before a tab is ready to listen. The bug was that this holding area filed those messages under the terminal's name only. A death notice for the old
pty-1got handed to the newpty-1, which then reported itself dead on arrival: blank tab, forever, with a perfectly healthy shell running on the host.#16970 fixed the common case by timestamping every message and throwing away anything older than the moment the tab asked for a new terminal. But a timestamp only says when a message showed up, not who it was about — a late death notice arriving a moment after the request still looks new enough to keep.
This PR files those messages under who they are actually about. Every terminal already has an incarnation id: a unique tag for one lifetime of one name. A death notice now carries that tag, and a notice tagged for a different lifetime than the terminal you just attached to is dropped — no matter when it arrived.
What #16970 left open, and how this closes it
#16970 shipped a monotonic renderer-local sequence fence: every buffered record is dated, and a fresh spawn drops anything dated at or below the sequence read just before its request left. Its own text names the residual risk:
That is exactly the window a restarting relay lands in. The relay dies, the tab is closed, the relay returns and renumbers from
pty-1, and the old PTY's exit is flushed late — while the replacement spawn is still in flight. It is newer than the fence, so the fence keeps it,registerExitdrains it, and connect returnsexitedBeforeAttach: truefor a shell that is alive.The right key is the incarnation id, and it is not a new concept:
src/shared/pty-incarnation.tsalready definesPtyIncarnationId/isPtyIncarnationId, the local provider mints one per spawn, the relay publishes one onpty.exit, andpersistPtyBindingalready keys on it. No twelfth identity concept was introduced.Keyed on
(ptyId, incarnationId)— storage and readsTwo things had to change, and review caught that doing only the first is worse than doing neither:
preHandlerPtyExitis nowMap<string, BufferedPreHandlerPtyExit[]>— one record per lifetime, capped at 4 per id.admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction, not because each caller remembered to call a discard first.The one invariant everything rests on
Only a positive disagreement excludes a record. Both sides must name a well-formed incarnation, validated with the existing
isPtyIncarnationId. Absence reads as unknown, never as a mismatch — the same ruledocs/reference/remote-wire-compatibility.mdstates foragentWait, where collapsing "absent" into a definite answer is the named failure mode.The fence is kept, deliberately
Two cases have no incarnation to compare and rest on the fence alone:
pty:datacarries no incarnation at all (makePtyDataPayload){ id, code: -1 }(ssh-relay-session.ts:2723)Not keyed on the wrong identifier
The SSH path carries two similar fields.
ptyIncarnationis transport/provider-generation scoped, always present, and synthesized aslegacy:${providerGeneration}:${serial}:${relayPtyId}when the wire omits one (ssh-pty-provider-output-state.ts:131-139) — it can be permanently pinned to alegacy:string that never equals a real incarnation.incarnationIdis the semantic identity, optional, only attached when wire-validated. This PR readsincarnationIdonly;git diffcontains zero occurrences ofptyIncarnation. PTYs with no semantic incarnation fall back to the sequence fence, which is exactly why it is retained.Which hops the incarnation traverses
No wire change. Nothing new crosses a versioned boundary. Every hop already carried the field; it was dropped at the preload type boundary and never read.
pty.exitnotificationsrc/relay/pty-handler.ts:865-870)RELAY_EXIT_CODE_VERSION_MISMATCH = 42). Unchanged — no field added.pty.spawnreplyspawnFreshSshPty)pty:exitIPCdelivery/exit.ts:148,ssh-relay-session.ts:2237)pty:spawnreplyipc/spawn-commit.ts:195)Both remote flavors
ssh:direct relay — gains the identity rule.remote:runtime — provably unaffected. Runtime PTYs never reach this buffer: their exit is the multiplex stream's{ type: 'end', streamId }→onEnd→ a syntheticonExit(0)(remote-runtime-pty-transport.ts:1897). They never traversewindow.api.pty.onExit. The id-agnostic fence is untouched for them.local-pty-provider.ts:482mints one per spawn.Coverage — what this does and does not reach
preHandlerPtyExithas several consumers. Being explicit, because accuracy beats apparent completeness:connectIpcPty, where the spawn resolvesregisterExitregisterEagerPtyBuffer(both background launchers)ipc-pty-connect.ts:45-53attachIpcPtyterminal-parked-pty-watcher.ts:46,terminal-parked-watcher-registry.ts:105)live/unverifiable/exitedvocabulary. Changing them is a behavioural change to liveness, not a bug fix. Flagged for separate triage.spawnIpcPtythrow pathFix evidence
Tests fail without the fix, pass with it — verified by reverting
1. The case #16970 could not cover (stale exit strictly after the spawn request; the exit is fired from inside the spawn mock, so "after the request left" is definitional, not microtask-scheduled). Reverting the dispatcher's incarnation forwarding:
2. The buffer keying. Reverting the record of the incarnation:
3. The swallowed exit that keying only the comparison would have introduced (found in review). Both races together — our own shell dies pre-attach, then the stranger's exit lands on the same id and, with one slot per id, overwrites it; the identity discard then removes the only survivor and the pane hangs on a dead PTY:
4. Reads filtered inside the buffer (the eager-buffer/background-launch hole). Reverting the read filter:
The suite also pins what must not change: a post-fence exit from the incarnation actually attaching is still delivered, an unnamed incarnation still falls back to the fence, a malformed one reads as unknown, a reader that names no lifetime still sees everything, and the discard leaves buffered bytes alone.
E2E — original bug stays fixed, three consecutive runs against real Docker
tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts,ORCA_E2E_SSH_DOCKER=1,--workers=1, against the final code:Both specs green every run — "does not resurrect tabs whose kill was lost to a killed relay daemon" and "does not resurrect tabs closed while the host is disconnected".
Gates
pnpm tcoxlint(full)pnpm test src/renderer/src/{components/terminal-pane,lib,store}cross-version-terminal-wire.unit.test.tscheck:code-quality:changedcheck:max-lines-ratchetcheck:reliability-gatesNo
max-linesdisable was added —git diffcontains zero occurrences. Both background launchers crossed the 300-line cap while threading the incarnation, so the additions were made leaner instead:launch-agent-background-session.tsnow holds the spawn result once (spawned) rather than two parallel variables for the two things it needed from it.Review notes
Four review seats ran against this branch. One found a swallowed-exit regression (fix 3 above) and a second independently reproduced the same sequence; a later audit found the eager-buffer/background-launch hole (fix 4). Both are fixed here with failing-first tests. Two seats cleared the areas they covered: the span between the discard and
registerExitis one synchronous run so no IPC push can land inside it, and the bounded-map eviction helper is provably equivalent to the inline code it replaced.Note on the red
package (windows)checkNot caused by this PR. It fails in the
Test Windows-specific boundariesstep, on:Evidence it is unrelated:
fix/ssh-replay-undelivered-pty-kill) and fix(relay): stop advertising an agent session for a pane whose tab is gone (#12447) #17012 (nwparker/relay-retire-closed-pane-agent-session), both unrelated branches. The quoted failure above is read from fix(relay): stop advertising an agent session for a pane whose tab is gone (#12447) #17012's completed log.node:fs,node:os,node:path,node:child_process,vitestandnode-pty; it spawns a real process tree and asserts Windows reaped a detached grandchild.src/main/windows/contains no import of renderer or preload code, and this PR touches onlysrc/preload/**andsrc/renderer/**.caef20fec8d).The assertion is a timing-sensitive check that an asynchronous detached-grandchild reap has completed, so this is either a recent regression on
mainor runner-load flake. Either way it needs its own triage and is out of scope for this change.