Skip to content

fix(runtime): release terminal.subscribe exit-waiters on teardown - #7490

Merged
nwparker merged 1 commit into
mainfrom
nwparker/fix-terminal-subscribe-waiter-leak
Jul 6, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/fix-terminal-subscribe-waiter-leak

Conversation

@nwparker

@nwparker nwparker commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Every terminal.subscribe / terminal.multiplex slot registers a runtime exit-waiter via waitForTerminal(request.terminal, { condition: 'exit' }) with no AbortSignal.

That waiter is stored in waitersByHandle and is only ever removed by:

  • a real PTY exit, or
  • a desktop renderer graph reload (markRendererReloading / markGraphUnavailable).

Agent terminals routinely never exit for the whole session, and a remote/mobile WebSocket reconnect does not trigger the renderer graph lifecycle. So on long SSH/mobile sessions:

  • every reconnect re-subscribes → one leaked waiter per terminal, forever;
  • every tab-switch re-subscribe within a live connection → another leaked waiter.

Each leaked waiter's .then/.catch closures capture the (now dead) streaming handler context — including the closed ws — so host-process memory climbs monotonically and never releases. Confirmed against the code by the audit (waitersByHandle add at orca-runtime.ts:9142; removal only via resolvePtyExitWaiters / rejectAllWaiters).

Fix

Give every teardown path a signal so the waiter is removed when the slot goes away:

  • multiplex (terminal.ts:1663): each stream gets an AbortController; detachStream aborts it. detachStream is the single teardown point — reached on slot Unsubscribe, re-subscribe pre-detach, and connection close (closeMultiplex loops every stream through it). Passing stream.exitWaiterAbort.signal to waitForTerminal removes the waiter at detach; the existing .catch no-ops because the stream is already deleted (streams.get(streamId) !== stream).
  • legacy json/binary subscribe (terminal.ts:1801, 1851): pass the per-connection dispatch signal, so the waiter is removed on socket close/error.

No behavior change on real exit: abort after resolve is a no-op, and once a slot is detached there is no client to notify, so dropping the waiter loses no signal.

Evidence

New terminal-subscribe-exit-waiter-leak.test.ts:

  • a signalled exit-waiter is released when its signal aborts (waitersByHandle 1 → 0);
  • 25 reconnect churns with signals leave zero waiters;
  • unsignalled exit-waiters accumulate (3 subscribes → 3 waiters) — the pre-fix behavior the fix prevents.

298 subscribe/rpc/pty tests pass (mobile-subscribe-integration, runtime-rpc, pty). Typecheck + lint clean.

Made with Orca 🐋


Description

Every terminal.subscribe and terminal.multiplex slot arms a runtime exit-waiter via waitForTerminal(..., { condition: 'exit' }). That waiter was created with no AbortSignal, so it was only ever removed from the runtime's waitersByHandle set on a real PTY exit (resolveExitWaiters) or a desktop renderer graph reload (rejectAllWaiters on markRendererReloading/markGraphUnavailable) — neither of which a remote/mobile WebSocket reconnect or tab-switch re-subscribe triggers. On a long-lived, never-exiting agent terminal, every reconnect/re-subscribe therefore leaked one waiter, each pinning its now-dead per-slot handler context — on the multiplex path the stranded waiter also retains the slot's stream and emit/sendBinary closures, which reference the closed connection's send path (the two legacy paths retain only a lighter cleanupSubscription continuation). The fix threads an AbortSignal into each exit-waiter: the multiplex path gets a per-stream AbortController (exitWaiterAbort) aborted in detachStream — the single teardown point hit on unsubscribe, re-subscribe, and connection close (via closeMultiplex); the two legacy terminal.subscribe paths bind to the connection dispatch signal, which aborts on socket close/error. Aborting removes the waiter from the runtime set immediately instead of retaining it until real exit.

Undeniable evidence + measured improvement

Measured (benchmark: 200 subscribe/reconnect cycles on one never-exiting terminal):

  • Retained runtime exit-waiters before: 200 (grows +1 per reconnect, never freed short of real PTY exit).
  • After: peak 1, final 0 — each slot's waiter is released the moment its stream detaches.

Correctness (new src/main/runtime/terminal-subscribe-exit-waiter-leak.test.ts, driving the real OrcaRuntimeService; verified passing 3/3):

  • releases a signalled exit-waiter when the signal aborts — registers a live connected PTY so waitForTerminal({condition:'exit'}) parks a pending waiter, asserts waiterCount === 1, calls controller.abort() (simulating detachStream/connection close), and asserts the wait rejects and waiterCount === 0.
  • leaks an unsignalled exit-waiter across reconnects (documents the bug the fix prevents) — pins the pre-fix behavior: 3 unsignalled subscribes leave waiterCount === 3 with nothing to free them short of real exit.
  • does not leak when many signalled subscribes churn (reconnect simulation) — 25 signalled subscribe→abort reconnect cycles end at waiterCount === 0.

The assertions read the runtime's private waitersByHandle set directly, so they measure the leaked object itself, not a proxy metric.

ELI5

Imagine every time you open a video call with a friend, a receptionist writes a sticky note that says "wait for this call to end, then clean up the room." The only thing that removes the note is the call actually ending normally. But on a phone with a shaky signal, the call keeps dropping and reconnecting — and each reconnect adds a new sticky note, while the old ones (each still clutching a dead phone line) are never thrown away. After a few hundred reconnects the wall is buried in stale notes, and the app is holding a pile of dead connections in memory. This change gives each note a self-destruct tab that fires the instant that particular connection tears down (hang-up, reconnect, or tab switch), so the wall stays clean instead of one note per reconnect forever.

Trade-offs that could regress the end experience

Honest search of ways this could regress the experience:

  • Legacy subscribe now cleans up on connection close, not only on exit. The two terminal.subscribe paths' .catch(() => cleanupSubscription(id)) now also fires when the dispatch signal aborts. This is the intended behavior, but it means cleanupSubscription must tolerate running on close as well as on real exit; on a normal WS close it is now invoked both by this .catch and by the connection-close sweep (cleanupSubscriptionsForConnection), so it will run twice. This leans on that method being idempotent — verified: it deletes from subscriptionCleanups before invoking the cleanup, so the second call no-ops (and the pre-fix code already double-called it via .then/.catch). Low risk, but it is the one behavior change to watch.
  • Exit-at-detach race: if a PTY genuinely exits at the same instant a multiplex slot detaches, the abort (fired from inside detachStream, after streams.delete) may win and reject the waiter. The .catch then no-ops because streams.get(streamId) === stream is already false, so no spurious end frame is sent — but a client that unsubscribed at that exact moment relies on its own teardown rather than the exit notification. Acceptable: an unsubscribing client no longer needs the exit signal. (On a real exit while the connection is still open, the waiter still resolves normally and the live client still gets its end frame — the signal only aborts on teardown, so no exit notification is lost for a connected client.)
  • Legacy path coverage is narrower than multiplex (pre-existing residual, not a new regression). The multiplex exitWaiterAbort is released on unsubscribe, re-subscribe, and close; the legacy terminal.subscribe waiter is bound to the dispatch signal, which aborts only on socket close/error — NOT on a same-id re-subscribe that evicts the old subscription (registerSubscriptionCleanup resolves the old dispatch, and dispatch dispose() removes the abort controller without aborting it). So an evicted legacy subscription can still strand its waiter until real exit. This is unchanged from before and effectively inert for current clients (the desktop/mobile remote path uses terminal.multiplex, which detachStream fully covers; terminal.subscribe remains only for back-compat).
  • No retention/history/scrollback impact and no added latency: the change only affects when a bookkeeping waiter is removed; terminal output, scrollback, and reconnect timing are untouched.
  • Not locally reproducible via /electron: the leak only manifests over many real remote/mobile WS reconnects on a long-lived session, so verification rests on the benchmark numbers and the runtime-level regression test rather than a desktop repro.

Every terminal.subscribe / terminal.multiplex slot registers a runtime
exit-waiter via waitForTerminal(condition:'exit'). With no AbortSignal that
waiter sits in waitersByHandle until the PTY actually exits — but agent
terminals routinely never exit for the life of a session. It is only ever
cleared by real exit or a desktop renderer graph reload (markRendererReloading
/ markGraphUnavailable), neither of which a remote/mobile WebSocket reconnect
triggers. So on long SSH/mobile sessions every reconnect and tab-switch
re-subscribe leaked a waiter, and each captured its closed-connection handler
context (including the dead ws), growing host-process memory monotonically.

- multiplex: give each stream an AbortController and abort it in detachStream
  (the single teardown point, reached on slot unsubscribe, re-subscribe
  pre-detach, and connection close via closeMultiplex). Passing its signal to
  waitForTerminal removes the waiter at detach. The existing .catch no-ops
  because the stream is already deleted (streams.get(streamId) !== stream).
- legacy json/binary subscribe: pass the per-connection dispatch signal so the
  waiter is removed on socket close/error.

Regression test proves a signalled exit-waiter is released when its signal
aborts (and 25 reconnect churns leave zero waiters), while an unsignalled one
accumulates — the pre-fix behavior.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds an AbortController (exitWaiterAbort) to each multiplexed terminal stream slot, aborting it during detachStream and passing its signal into runtime.waitForTerminal(..., { condition: 'exit' }). Both the legacy and binary code paths of terminal.subscribe are updated to pass the RPC handler's connection-lifecycle signal into their respective waitForTerminal exit-wait calls. A new regression test suite validates that exit waiters are released when aborted, accumulate without a signal (documenting prior behavior), and leave no residuals under repeated signalled churn.

Changes

Cohort / File(s) Summary
src/main/runtime/rpc/methods/terminal.ts Adds exitWaiterAbort AbortController to multiplex stream state; aborts it in detachStream; wires its signal into waitForTerminal for multiplex exit handling; passes handler signal into waitForTerminal in both terminal.subscribe cleanup paths (legacy and binary).
src/main/runtime/terminal-subscribe-exit-waiter-leak.test.ts New Vitest suite with helper utilities and three tests covering waiter release on abort, waiter accumulation without a signal, and absence of leaks under repeated signalled churn.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TerminalMultiplex
  participant TerminalSubscribe
  participant Runtime

  Client->>TerminalMultiplex: attach stream
  TerminalMultiplex->>TerminalMultiplex: create exitWaiterAbort
  TerminalMultiplex->>Runtime: waitForTerminal(condition: exit, signal)
  Client->>TerminalMultiplex: detachStream
  TerminalMultiplex->>TerminalMultiplex: exitWaiterAbort.abort()
  TerminalMultiplex-->>Runtime: waiter released

  Client->>TerminalSubscribe: subscribe(signal)
  TerminalSubscribe->>Runtime: waitForTerminal(condition: exit, signal)
  Client--)TerminalSubscribe: connection close/error
  TerminalSubscribe-->>Runtime: waiter released
Loading

Related issues: None referenced in the provided context.

Related PRs: None referenced in the provided context.

Suggested labels: bug, runtime, terminal

Suggested reviewers: None determinable from the provided context.

Poem
A rabbit hopped through terminal code,
found waiters piling up their load.
With AbortController in its paw,
it snipped each leak it saw and clawed.
Now signals close the door just right —
no ghost of PTY haunts the night. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template and omits the Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Rewrite the description to match the template with all required headings, a short Summary, Screenshots or 'No visual change', Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 describes the runtime exit-waiter teardown fix, which matches the main change, though it omits multiplex.
✨ Finishing Touches
📝 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.

@nwparker
nwparker merged commit fe3fd94 into main Jul 6, 2026
2 checks passed
@nwparker
nwparker deleted the nwparker/fix-terminal-subscribe-waiter-leak branch July 6, 2026 06:08
brennanb2025 added a commit that referenced this pull request Aug 17, 2026
…ing registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; #7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.
brennanb2025 added a commit that referenced this pull request Aug 17, 2026
…ing registration (#14992)

* fix(runtime): tear down terminal subscriptions only through their owning registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; #7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.

* test(runtime): migrate the remaining subscription stubs to the faithful registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.

* fix(runtime): guard the lease-only presence release and use the shared registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.

* fix(runtime): drop the lease-only presence guard; it disabled a real compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.

* fix(runtime): make the unsubscribe refusal observable and restore test-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.

* fix(runtime): report an unsubscribe refusal without masking a real teardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…ing registration (stablyai#14992)

* fix(runtime): tear down terminal subscriptions only through their owning registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; stablyai#7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.

* test(runtime): migrate the remaining subscription stubs to the faithful registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.

* fix(runtime): guard the lease-only presence release and use the shared registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.

* fix(runtime): drop the lease-only presence guard; it disabled a real compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.

* fix(runtime): make the unsubscribe refusal observable and restore test-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.

* fix(runtime): report an unsubscribe refusal without masking a real teardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ablyai#7490)

Every terminal.subscribe / terminal.multiplex slot registers a runtime
exit-waiter via waitForTerminal(condition:'exit'). With no AbortSignal that
waiter sits in waitersByHandle until the PTY actually exits — but agent
terminals routinely never exit for the life of a session. It is only ever
cleared by real exit or a desktop renderer graph reload (markRendererReloading
/ markGraphUnavailable), neither of which a remote/mobile WebSocket reconnect
triggers. So on long SSH/mobile sessions every reconnect and tab-switch
re-subscribe leaked a waiter, and each captured its closed-connection handler
context (including the dead ws), growing host-process memory monotonically.

- multiplex: give each stream an AbortController and abort it in detachStream
  (the single teardown point, reached on slot unsubscribe, re-subscribe
  pre-detach, and connection close via closeMultiplex). Passing its signal to
  waitForTerminal removes the waiter at detach. The existing .catch no-ops
  because the stream is already deleted (streams.get(streamId) !== stream).
- legacy json/binary subscribe: pass the per-connection dispatch signal so the
  waiter is removed on socket close/error.

Regression test proves a signalled exit-waiter is released when its signal
aborts (and 25 reconnect churns leave zero waiters), while an unsignalled one
accumulates — the pre-fix behavior.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ing registration (stablyai#14992)

* fix(runtime): tear down terminal subscriptions only through their owning registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; stablyai#7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.

* test(runtime): migrate the remaining subscription stubs to the faithful registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.

* fix(runtime): guard the lease-only presence release and use the shared registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.

* fix(runtime): drop the lease-only presence guard; it disabled a real compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.

* fix(runtime): make the unsubscribe refusal observable and restore test-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.

* fix(runtime): report an unsubscribe refusal without masking a real teardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
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