Repository navigation
fix(terminal): require a proven exit before retiring a subscription's lease - #15470
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
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: 📥 CommitsReviewing files that changed from the base of the PR and between 1c71a2d9ae657a21fb3cdb3d150e372f18a980a6 and 76bd0b4. 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughPTY exit detection now requires an explicit Merge Risk: 🟠 High · up to The change prevents a relay disconnect from being treated as proof that a terminal exited, but the current head still has runtime paths that can expose stale exit state or strand subscribers after disconnected-record cleanup, along with test subscriptions that may leak across cases. These create concrete correctness and availability risks, so the PR should not merge until they are addressed or explicitly accepted. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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: 702c17fd-5220-41b3-94ea-16a583181950
📒 Files selected for processing (4)
src/main/runtime/rpc/methods/terminal-subscription-exit-release.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/terminal-subscribe-ownership.test.tssrc/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
d3099d7 to
ae2c890
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts (1)
3-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the lifecycle rationale comments.
Keep each rationale comment to one concise line. Move detailed renderer and graph behavior to nearby documentation if it must remain recorded.
As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Also applies to: 68-73, 109-111
Source: Coding guidelines
src/main/runtime/rpc/terminal-subscribe-ownership.test.ts (1)
136-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe 300 ms wait duplicates the helper's backoff constant.
flush(300)must exceed the first retry delay for this assertion to be meaningful. That delay lives interminal-subscription-exit-release.ts. If the base delay grows, this test still passes but no longer proves that the re-arm was cancelled.Export the base delay from the helper and derive the wait from it, or drive the retry with fake timers so the assertion is deterministic.
src/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts (1)
240-285: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winClose the harness in the last three tests.
The tests at Line 240, Line 263, and Line 278 never call
harness.close(). The connection abort signal therefore never fires, so the subscription cleanup and the exit-releasestop()never run. In the re-arm test the stubresolveTerminalExitWatchreturns'pending'forever, so a retry loop can survive into later tests in this file.Add
harness.close()at the end of each test, as the earlier tests do.♻️ Proposed cleanup
await vi.waitFor(() => expect(harness.jsonTypes()).toContain('end')) + harness.close() })src/main/runtime/rpc/methods/terminal-subscription-exit-release.test.ts (1)
42-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRestore mocks before restoring real timers. Because
setTimeoutSpycaptures Vitest’s fake timer, runvi.restoreAllMocks()beforevi.useRealTimers()to prevent the fakesetTimeoutfrom leaking into later tests.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 14e1631b-5d2d-4609-8446-a91e4927430e
📥 Commits
Reviewing files that changed from the base of the PR and between d3099d7 and ae2c89050ef3fb7c0f944b14eea467b4904fd6b5.
📒 Files selected for processing (6)
src/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal-subscription-exit-release.test.tssrc/main/runtime/rpc/methods/terminal-subscription-exit-release.tssrc/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.tssrc/main/runtime/rpc/terminal-subscribe-ownership.test.tssrc/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts (1)
70-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the explanatory comments.
The new comments restate nearby control flow and span multiple lines. Keep only a brief sentence for non-obvious rationale.
src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts#L70-L84: condense the handle-rebinding rationale.src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts#L98-L102: condense the backoff rationale.src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts#L284-L285: remove the explanation of the assertion path.src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts#L292-L294: remove the explanation duplicated by the test setup and name.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5c2236f0-b809-49af-98b9-53197080a83e
📥 Commits
Reviewing files that changed from the base of the PR and between ae2c89050ef3fb7c0f944b14eea467b4904fd6b5 and e7319a1dc8e4ad70ebc89701eb527fd091dce486.
📒 Files selected for processing (6)
src/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal-subscription-exit-release.test.tssrc/main/runtime/rpc/methods/terminal-subscription-exit-release.tssrc/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.tssrc/main/runtime/rpc/terminal-subscribe-ownership.test.tssrc/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
60fe8c9 to
83fbc19
Compare
Review loop — summary (posting for the record; never landed on the PR)This PR went through a high-effort review loop plus an adversarial pass. The findings materially changed it, and finally superseded its original approach entirely. Three defects found in the original fix
Then main superseded the whole approach#15463 landed and fixes the same defect by a better mechanism — What this PR is nowReshaped to the residual defect #15463 shipped with. Now 4 production lines, with both directions pinned against the real runtime. Evidence is unit-level; no hardware QA had been possible at the time. Being addressed separately. |
QA evidence for PR #15470Frame-level capture of Isolation (required)Two isolated
BEFORE boot (empty profile): AFTER boot (empty profile): What was staged vs observedStaged (said so): after creating a real PTY through Observed: a mobile-style lease-only This is the subscribe-time fast path inside Defect (BEFORE, unfixed main)Workspace Injected drop, then subscribe. First (and only) frame at 21ms was {
"runtimeId": "13cbb9da-4bf3-4f04-8928-85b8e9cbfb49",
"handle": "term_191cc7e7-8c93-47d4-bd01-a841ec0f9b73",
"types": ["end"],
"emittedSubscribed": false,
"emittedEnd": true,
"t_ms": 21
}That matches the 0.0.44 lock mechanism: mobile treats Fix (AFTER, this PR)Same injection on Hold 1 — drop only, 8s, no {
"runtimeId": "bb697e1b-47e5-44bb-9c32-4951b7780dc1",
"handle": "term_a8df3308-9fc0-4711-97d2-cae0bfc72664",
"types": ["subscribed"],
"emittedSubscribed": true,
"emittedEnd": false,
"hold_ms": 8000
}Hold 2 — same drop, then genuine {
"types": ["subscribed", "end"],
"emittedSubscribed": true,
"emittedEnd": true,
"t_subscribed_ms": 48,
"t_end_ms": 1757,
"lastExitCode_after_onPtyExit": 0
}The lease survives the inferred disconnect. A proven host exit still retires it. Side-by-sideWhat this run did not capture
Method notes
|
83fbc19 to
1c71a2d
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/main/runtime/orca-runtime.ts (3)
35321-35340: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
dropDisconnectedPtyRecordnever notifiessubscribeToPtyExitlisteners, so a pruned disconnected PTY can strand its subscription forever.
dropDisconnectedPtyRecord(called frompruneDisconnectedPtyRecordswhen more thanDISCONNECTED_PTY_RECORD_MAXdisconnected records accumulate) callsthis.advancePtyLifecycleGeneration(ptyId)but does not callthis.notifyPtyExitListeners(ptyId). After pruning,this.ptysById.get(ptyId)returnsundefinedandthis.getLeavesForPty(ptyId)returns an empty array, soisPtyKnownExited(ptyId)returnsfalseforever for that id — the PTY record is gone, but the runtime never proves it exited.
subscribeToPtyExit's post-registration recheck only compares the lifecycle generation snapshot taken at call time; it does not subscribe to future generation changes, so bumping the generation indropDisconnectedPtyRecorddoes not itself wake any listener already registered. Any consumer with noAbortSignal(for examplewatchSubscriptionLifetimeinterminal.ts, whose only teardown path besides the signal is this exit callback) keeps its subscription registered indefinitely once its PTY is pruned this way.Call
this.notifyPtyExitListeners(ptyId)insidedropDisconnectedPtyRecord, alongside the existingadvancePtyLifecycleGeneration(ptyId)call, so listeners waiting on a since-pruned PTY are released.🔒️ Proposed fix
private dropDisconnectedPtyRecord(ptyId: string): void { // Why: pruning can remove a PTY without the normal exit callback. this.advancePtyLifecycleGeneration(ptyId) + this.notifyPtyExitListeners(ptyId) this.pairedRendererSessionOwnedPtyIds.delete(ptyId) this.ptysById.delete(ptyId) ...
15183-15183: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winMove
notifyPtyExitListenersafter the PTY record is marked exited.
this.notifyPtyExitListeners(ptyId)runs immediately afteradvancePtyLifecycleGeneration(ptyId), butpty.connected = falseandpty.lastExitCode = exitCodeare not set until much later inonPtyExit(in theif (pty) { ... }block near the end of the function). Between these two points,isPtyKnownExited(ptyId)still returnsfalsefor this PTY.A listener registered through
subscribeToPtyExitis documented and expected to fire only when the exit is confirmed. If a listener callback queries PTY state synchronously (directly or through a nested call), it observes the PTY as still connected and not exited, even though the exit notification just fired. Move thenotifyPtyExitListeners(ptyId)call to after the block that setspty.connected,pty.lastExitCode, andpty.lastExitCause, so the invariant "exit notified impliesisPtyKnownExitedis true" holds for every current and future consumer ofsubscribeToPtyExit.🐛 Proposed fix outline
this.advancePtyLifecycleGeneration(ptyId) - this.notifyPtyExitListeners(ptyId) const exactSurfaceByKey = new Map<...>() ... if (pty) { pty.connected = false pty.runtimeSessionOwned = false this.setPairedRendererSessionOwnership(pty.ptyId, false) pty.disconnectedAt = Date.now() pty.lastExitCode = exitCode pty.lastExitCause = exitCause + this.notifyPtyExitListeners(ptyId) ... }
7621-7713: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winTreat a missing
tabsByWorktree[worktreeId]entry as an empty list. The close helper writes[], but hydration and session cleanup can delete the entry. Returning early can retain ownership for retired renderer tabs.
🧹 Nitpick comments (2)
src/main/runtime/terminal-pty-exit-waiter.test.ts (1)
61-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce this comment to one sentence.
Keep the reason for the test. Remove the phone retry and UI behavior details.
As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.
Proposed change
-// Why: the liveness sweep clears `connected` with no exit code for every PTY behind a -// dropped relay, so a record in that state is a lost connection to a process that may -// still be running. Reading it as an exit retires a live lease and emits `end`, which the -// phone rearms against three times and then locks the composer on "Waiting for terminal…". +// A disconnected PTY has no confirmed exit, so its subscription must remain active.Source: Coding guidelines
src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts (1)
1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce this comment to one sentence.
State only why this test uses the real PTY exit predicate.
As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.
Proposed change
-// Why: the stale-handle survival suite doubles subscribeToPtyExit, so it pins the wiring but -// not the predicate that decides whether a PTY counts as exited. This wires that one call to -// a real OrcaRuntimeService, because a relay drop reaches the phone through the predicate. +// Use the real PTY exit predicate because relay loss reaches `terminal.subscribe` through it.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d3ff371b-871d-4f87-a683-32505d9901b1
📥 Commits
Reviewing files that changed from the base of the PR and between e7319a1dc8e4ad70ebc89701eb527fd091dce486 and 1c71a2d9ae657a21fb3cdb3d150e372f18a980a6.
📒 Files selected for processing (3)
src/main/runtime/orca-runtime.tssrc/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.tssrc/main/runtime/terminal-pty-exit-waiter.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
… lease
isPtyKnownExited read a PTY record as exited whenever `connected` was false:
if (pty) { return !pty.connected }
Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited',
which is only true once lastExitCode is set. So the same function proves absence on
one path and infers it on the other, and the inferring path is the one that runs
whenever a record exists.
onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected`
with no exit code for every PTY behind a dropped relay, so that state is a lost
connection to a process that may still be running on the host — not an exit. Reading
it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time,
which retires the lease and emits `end` for a live terminal. Mobile reads `end` as
"PTY gone" and rearms; after three attempts it stops and leaves the composer on
"Waiting for terminal…", which is where the 0.0.44 permanent lock comes from.
Use the runtime's existing three-valued discriminator so both paths demand the same
proof. 'unknown' now keeps watching, and the later real exit still fires the listener;
a subscription that outlives its PTY is still bounded by the connection abort.
Both callers are in subscribeToPtyExit — the subscribe-time fast path and the
registration-race re-check — and both want proven-exited, so neither changes shape.
1c71a2d to
76bd0b4
Compare
… lease (stablyai#15470) isPtyKnownExited read a PTY record as exited whenever `connected` was false: if (pty) { return !pty.connected } Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited', which is only true once lastExitCode is set. So the same function proves absence on one path and infers it on the other, and the inferring path is the one that runs whenever a record exists. onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected` with no exit code for every PTY behind a dropped relay, so that state is a lost connection to a process that may still be running on the host — not an exit. Reading it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time, which retires the lease and emits `end` for a live terminal. Mobile reads `end` as "PTY gone" and rearms; after three attempts it stops and leaves the composer on "Waiting for terminal…", which is where the 0.0.44 permanent lock comes from. Use the runtime's existing three-valued discriminator so both paths demand the same proof. 'unknown' now keeps watching, and the later real exit still fires the listener; a subscription that outlives its PTY is still bounded by the connection abort. Both callers are in subscribeToPtyExit — the subscribe-time fast path and the registration-race re-check — and both want proven-exited, so neither changes shape.
… lease (stablyai#15470) isPtyKnownExited read a PTY record as exited whenever `connected` was false: if (pty) { return !pty.connected } Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited', which is only true once lastExitCode is set. So the same function proves absence on one path and infers it on the other, and the inferring path is the one that runs whenever a record exists. onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected` with no exit code for every PTY behind a dropped relay, so that state is a lost connection to a process that may still be running on the host — not an exit. Reading it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time, which retires the lease and emits `end` for a live terminal. Mobile reads `end` as "PTY gone" and rearms; after three attempts it stops and leaves the composer on "Waiting for terminal…", which is where the 0.0.44 permanent lock comes from. Use the runtime's existing three-valued discriminator so both paths demand the same proof. 'unknown' now keeps watching, and the later real exit still fires the listener; a subscription that outlives its PTY is still bounded by the connection abort. Both callers are in subscribeToPtyExit — the subscribe-time fast path and the registration-race re-check — and both want proven-exited, so neither changes shape.
… lease (stablyai#15470) isPtyKnownExited read a PTY record as exited whenever `connected` was false: if (pty) { return !pty.connected } Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited', which is only true once lastExitCode is set. So the same function proves absence on one path and infers it on the other, and the inferring path is the one that runs whenever a record exists. onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected` with no exit code for every PTY behind a dropped relay, so that state is a lost connection to a process that may still be running on the host — not an exit. Reading it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time, which retires the lease and emits `end` for a live terminal. Mobile reads `end` as "PTY gone" and rearms; after three attempts it stops and leaves the composer on "Waiting for terminal…", which is where the 0.0.44 permanent lock comes from. Use the runtime's existing three-valued discriminator so both paths demand the same proof. 'unknown' now keeps watching, and the later real exit still fires the listener; a subscription that outlives its PTY is still bounded by the connection abort. Both callers are in subscribeToPtyExit — the subscribe-time fast path and the registration-race re-check — and both want proven-exited, so neither changes shape.





What changed
One predicate.
isPtyKnownExitedtreated a PTY record as exited wheneverconnectedwas false:The leaf fallback demands proof —
getTerminalStatereturns'exited'only oncelastExitCodeis set. The PTY path infers it from disconnection, and that is the path that runs whenever a record exists. This makes both demand the same proof, reusing the runtime's existing three-valued discriminator.Why it matters
onPtyExitis the only writer oflastExitCode. The liveness sweep clearsconnectedwith no exit code for every PTY behind a dropped relay, so that state means "lost the connection to a process that may still be running on the host" — not "the process exited".Reading it as an exit makes
subscribeToPtyExitfire its listener synchronously at subscribe time.watchSubscriptionLifetimethen retires the lease and emitsendfor a live terminal. Mobile readsendas "PTY gone" and rearms; afterMAX_REARM_ATTEMPTS = 3it stops and leaves the composer on "Waiting for terminal…", recovering only when a replacement handle arrives — which never comes, because the PTY is alive and its handle is unchanged.This is the residual cause of the 0.0.44 permanent composer lock. A separate session reproduced that symptom independently, and the mechanism matches exactly: lease retired,
endemitted, three rearms, locked.After the change
'unknown'keeps watching, the later real exit still fires the listener, and a subscription that outlives its PTY stays bounded by the connection abort thatwatchSubscriptionLifetimealready registers.Scope
Both callers are inside
subscribeToPtyExit— the subscribe-time fast path and the registration-race re-check. Both want proven-exited, so neither changes shape, and the predicate is private with no other callers. Nothing in #15463 is reverted or restructured.Retraction of the original framing
This PR previously proposed a different fix: a re-arm loop with 250ms→30s backoff wrapped around
waitForTerminal(..., { condition: 'exit' }), plus handle rebinding through a newresolveTerminalExitWatch. That approach is withdrawn.#15463 landed on
mainduring review and fixes the same underlying defect by a better mechanism —watchSubscriptionLifetimesubscribing on the stableptyIdand notified fromonPtyExit, with no polling, no backoff, and no handle re-resolution. It deleted all threewaitForTerminal(params.terminal, { condition: 'exit' }).then/.catch(releaseIfCurrent)call sites this PR used to rewrite, so the original change targeted code that no longer exists; carrying it forward would have reverted the better fix.What survives is the one finding #15463 did not cover: that
!connectedis not proof of exit. #15463's own commit message states "absence must be proven, never inferred" — this completes that principle on the path it missed.Tests
Three new cases in
terminal-pty-exit-waiter.test.tsagainst the real runtime, pinning both directions:lastExitCodestill null — the listener must not fire, and the subscription stays registeredonPtyExitlands — the listener does fire, so subscribing during the outage costs nothingBoth must-change cases fail against unfixed
main(2 failed | 4 passed); the third passes either way as a regression guard.terminal-subscribe-relay-drop-lease-survival.test.tscarries it to the wire across all threeterminal.subscribebranches (lease-only, legacy JSON, binary). The existing stale-handle suite doublessubscribeToPtyExit, so it pins the wiring but not the predicate; this one delegates that single call to a realOrcaRuntimeServiceand asserts noendis emitted for a relay-dropped PTY, then thatenddoes arrive once the real exit lands.Verification
src/main/runtime— 370 files, 4664 passed, 9 skipped, 0 failedtypecheck:node— exit 0, proven non-vacuous (injected aTS2322into the new test file, exit 1 naming that file, restored, exit 0)oxfmtandoxlint— clean