Skip to content

fix(pty): key buffered pre-attach PTY exits on the incarnation, not a sequence fence - #17010

Merged
nwparker merged 6 commits into
mainfrom
worktree-agent-a468854db46dda527
Aug 28, 2026
Merged

nwparker merged 6 commits into
mainfrom
worktree-agent-a468854db46dda527

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​225 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​224
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​239 $\color{#cf222e}{\Huge{\mathbf{−}}}$​59 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​180

ELI5

Terminals get numbered names like pty-1. When the SSH relay restarts it starts counting from pty-1 again, 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-1 got handed to the new pty-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:

a stale exit arriving after the spawn request was sent still passes the fence, because the fence is a clock, not an identity.

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, registerExit drains it, and connect returns exitedBeforeAttach: true for a shell that is alive.

The right key is the incarnation id, and it is not a new concept: src/shared/pty-incarnation.ts already defines PtyIncarnationId/isPtyIncarnationId, the local provider mints one per spawn, the relay publishes one on pty.exit, and persistPtyBinding already keys on it. No twelfth identity concept was introduced.

Keyed on (ptyId, incarnationId) — storage and reads

Two things had to change, and review caught that doing only the first is worse than doing neither:

  1. Storage. preHandlerPtyExit is now Map<string, BufferedPreHandlerPtyExit[]> — one record per lifetime, capped at 4 per id.
  2. Reads. Every read goes through 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 rule docs/reference/remote-wire-compatibility.md states for agentWait, 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:

Case Why the incarnation cannot help
Buffered bytes pty:data carries no incarnation at all (makePtyDataPayload)
Unnamed exits a host predating the field, or a main-side path that synthesizes one without it — the relay's stale-PTY drop sends { id, code: -1 } (ssh-relay-session.ts:2723)

Not keyed on the wrong identifier

The SSH path carries two similar fields. ptyIncarnation is transport/provider-generation scoped, always present, and synthesized as legacy:${providerGeneration}:${serial}:${relayPtyId} when the wire omits one (ssh-pty-provider-output-state.ts:131-139) — it can be permanently pinned to a legacy: string that never equals a real incarnation. incarnationId is the semantic identity, optional, only attached when wire-validated. This PR reads incarnationId only; git diff contains zero occurrences of ptyIncarnation. 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.

Hop Already carried it? Versioned boundary?
Relay host → client, pty.exit notification Yes (src/relay/pty-handler.ts:865-870) Relay wire, but version-locked (RELAY_EXIT_CODE_VERSION_MISMATCH = 42). Unchanged — no field added.
Relay host → client, pty.spawn reply Yes (spawnFreshSshPty) Same; unchanged.
main → renderer, pty:exit IPC Yes (delivery/exit.ts:148, ssh-relay-session.ts:2237) No — in-process
main → renderer, pty:spawn reply Yes (ipc/spawn-commit.ts:195) No — in-process
preload types + renderer readers No — the only actual change No

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 synthetic onExit(0) (remote-runtime-pty-transport.ts:1897). They never traverse window.api.pty.onExit. The id-agnostic fence is untouched for them.
  • local (macOS/Windows/Linux) — also gains it; local-pty-provider.ts:482 mints one per spawn.

Coverage — what this does and does not reach

preHandlerPtyExit has several consumers. Being explicit, because accuracy beats apparent completeness:

Consumer Covered?
connectIpcPty, where the spawn resolves Yes — identity discard + lifetime-scoped registerExit
registerEagerPtyBuffer (both background launchers) Yes — each passes the incarnation its own spawn returned
Pre-spawn fast path, ipc-pty-connect.ts:45-53 No — and not fixable here. It fires before any spawn/attach round trip, so the renderer holds no incarnation for that session id and has nothing to compare. It behaves exactly as it does today. Pre-existing; #16970 did not cover it either.
attachIpcPty No — same reason: no incarnation in hand at that point.
Parked-watcher liveness gates (terminal-parked-pty-watcher.ts:46, terminal-parked-watcher-registry.ts:105) No — deliberately untouched. These feed liveness publication, and the SSH execution boundary has a strict live/unverifiable/exited vocabulary. Changing them is a behavioural change to liveness, not a bug fix. Flagged for separate triage.
The spawnIpcPty throw path No — neither discard runs when spawn rejects. Nothing binds in that round; the record is judged by the next connect.

Fix 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:

 FAIL  pty-transport-recycled-pty-incarnation.test.ts > does not report a fresh shell as exited when the id’s previous incarnation exits mid-spawn
AssertionError: expected { id: 'ssh:target@@pty-1', …(1) } to be 'ssh:target@@pty-1' // Object.is equality

- Expected:
"ssh:target@@pty-1"

+ Received:
{
  "exitedBeforeAttach": true,
  "id": "ssh:target@@pty-1",
}

2. The buffer keying. Reverting the record of the incarnation:

 FAIL  pty-pre-handler-buffer.test.ts > drops a recycled id's exit that arrived after the spawn request, on incarnation alone
AssertionError: expected true to be false // Object.is equality

- Expected
+ Received

- false
+ true

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:

 FAIL  pty-pre-handler-buffer.test.ts > keeps our own pre-attach exit when a late stranger's exit lands on the same recycled id
AssertionError: expected false to be true // Object.is equality
 ❯ expect(hasPreHandlerPtyExit(RECYCLED_PTY_ID)).toBe(true)

 FAIL  pty-pre-handler-buffer.test.ts > replaces a duplicate exit for the same lifetime instead of crowding out another lifetime
AssertionError: expected "vi.fn()" to be called with arguments: [ 9 ]
Number of calls: 0

4. Reads filtered inside the buffer (the eager-buffer/background-launch hole). Reverting the read filter:

 FAIL  pty-pre-handler-buffer.test.ts > never reports or delivers a foreign exit to a reader that names its lifetime
AssertionError: expected true to be false // Object.is equality
 ❯ expect(hasPreHandlerPtyExit(RECYCLED_PTY_ID, FRESH_INCARNATION_ID)).toBe(false)

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:

Run Result Duration
1 2 passed 1.5m
2 2 passed 2.2m
3 2 passed 2.2m

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

Gate Result
pnpm tc clean
oxlint (full) clean
pnpm test src/renderer/src/{components/terminal-pane,lib,store} 1182 files, 11429 passed
cross-version-terminal-wire.unit.test.ts 5 passed (both skew directions)
check:code-quality:changed 0 new findings across 14 files
check:max-lines-ratchet OK — no new bypasses
check:reliability-gates 99 gates passed

No max-lines disable was added — git diff contains 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.ts now 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 registerExit is 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) check

Not caused by this PR. It fails in the Test Windows-specific boundaries step, on:

FAIL src/main/windows/windows-host-job.win32.test.ts > host job reaps the tree when the host dies
     > kills a pty and its detached grandchild when the host is force-killed
AssertionError: expected true to be false
 ❯ src/main/windows/windows-host-job.win32.test.ts:90:38   expect(isAlive(grandchildPid)).toBe(false)

Evidence it is unrelated:

The assertion is a timing-sensitive check that an asynchronous detached-grandchild reap has completed, so this is either a recent regression on main or runner-load flake. Either way it needs its own triage and is out of scope for this change.

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

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 87a6340f-c6b3-4762-b976-e020f859c9dd

📥 Commits

Reviewing files that changed from the base of the PR and between 0d18648 and 6cb28c0.

📒 Files selected for processing (9)
  • config/reliability-gates.jsonc
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-session-handlers.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
  • src/renderer/src/lib/launch-agent-background-session.test.ts
  • src/renderer/src/lib/launch-agent-background-session.ts
  • src/renderer/src/lib/launch-worktree-background-terminals.ts

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


📝 Walkthrough

Walkthrough

The 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 6cb28

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 m… Add the issue reference after “Fixes #”. Add the required visual proof, or write N/A with a brief reason if there is no visual or interaction change. Complete or explicitly address the remaining template sections, including AI Disclosure,…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: keying buffered pre-attach PTY exits by incarnation instead of a sequence fence.
Full details: Docstring Coverage

Explanation

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 check

Explanation

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 N/A with a brief reason if there is no visual or interaction change. Complete or explicitly address the remaining template sections, including AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist items.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92550e06-7532-4a53-89fa-b6cd1b0942cb

📥 Commits

Reviewing files that changed from the base of the PR and between 65dd06a and bfb1cad.

📒 Files selected for processing (10)
  • src/preload/api/pty-api.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-exit-delivery.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport-recycled-pty-incarnation.test.ts
  • src/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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9fffc6bd-8b4e-40bc-bd90-d3faf0a682ba

📥 Commits

Reviewing files that changed from the base of the PR and between bfb1cad and 0d18648.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
  • src/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.

Comment on lines +218 to +225
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()

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.

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

Suggested change
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.
@nwparker
nwparker merged commit a907dd2 into main Aug 28, 2026
53 of 55 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
… 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)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
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