You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(server): keep websocket subscriptions owned through setup and cleanup - #7704
The v11 WebSocket adapter registered a subscription only after its setup, so a stop or disconnect during setup was missed, and cleanup raced with id reuse.
A subscription is registered before any await, and a duplicate id is rejected right away.
A stop or disconnect during setup skips the procedure, or disposes its iterator unread, and replies stopped.
On an iteration error, the signal aborts before disposal.
Protocol-visible: terminal messages go out after iterator cleanup, a failed cleanup goes to onError only, and a duplicate id's errorFormatter and onError may get ctx: undefined.
Clients 11.0.0, 11.6.0 and 11.23.0 get no new messages or errors. Cost: about 6% CPU and 2.1 KB per active subscription.
Reviewing files that changed from the base of the PR and between 10c47ed and 10c47ed.
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
Walkthrough
The WebSocket adapter now registers subscriptions before context and procedure setup completes, handles cancellation during setup and iteration, and separates iteration errors from iterator-disposal errors. New lifecycle and memory tests cover cancellation, duplicate IDs, cleanup, and signal collection.
Changes: WebSocket subscription lifecycle
Layer / File(s)
Summary
Subscription admission and cancellation packages/server/src/adapters/ws.ts, packages/tests/server/websocketsLifecycle.test.ts, packages/tests/server/websockets.memory.test.ts
The adapter registers subscription controllers before awaiting setup and rejects duplicate active IDs. Tests cover cancellation during setup, shared context creation, duplicate IDs, admission errors, and signal collection.
Iterator cleanup and terminal responses packages/server/src/adapters/ws.ts, packages/tests/server/websocketsLifecycle.test.ts
The adapter handles iterator completion, cancellation, and cleanup errors during request settlement. Tests cover cleanup timing, iterator failures, and client response ordering.
sequenceDiagram
participant Client as WebSocket client
participant Adapter as ws adapter
participant Setup as Context and middleware
participant Resolver as Subscription resolver
Client->>Adapter: Send subscription request
Adapter->>Setup: Register controller and await setup
Client->>Adapter: Send stop request
Adapter->>Setup: Abort setup signal
Setup-->>Adapter: Settle setup
Adapter-->>Client: Send stopped response
Loading
Suggested reviewers:juliusmarminge, nick-lucas
Merge Risk: Low · up to 10c47
The subscription lifecycle changes have no established merge-blocking behavioral defect. Align the new tests with the required shared setup helper; the throwing-onError concern is pre-existing.
Pre-merge checks: 4 · 1
Failed checks: 1 warning
Check name
Status
Explanation
Resolution
Docstring Coverage
Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta…
Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed checks: 4 passed
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title clearly identifies the main change: preserving WebSocket subscription ownership through setup and cleanup.
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage
Explanation
Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 7 functions across 3 files.
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
Finishing Touches
Generate docstrings
Commit to this branch
Create a new PR
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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.
Reviewing files that changed from the base of the PR and between 53a07cd and 10c47ed.
Files selected for processing: 3
packages/server/src/adapters/ws.ts
packages/tests/server/websockets.memory.test.ts
packages/tests/server/websocketsLifecycle.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
🤖 Refactored the subscription lifecycle in ws.ts to use explicit resource management (b6ced7887):
The admission function now starts with a using release resource that frees the id, but only if this request still owns it. It also awaits the iteration, so the id stays reserved until the iterator's await using disposal has settled.
The terminal stopped/error is sent once that scope has been disposed, so the order is: iterator disposed → error reported → id freed → stopped.
This replaces the releaseSubscription/stopSubscription closures and their five call sites; early exits are now plain returns.
The abort-before-disposal on iteration failure stays a small try/catch, because it only applies when iteration fails, which a disposer can't detect without a flag. DisposableStack isn't used because the node18 build target doesn't have it.
Behaviour is unchanged: the 19 lifecycle tests pass unmodified, and swapping await iteration for void iteration makes 6 of them fail, so they do pin this. The ws/subscription files (394 tests), the server/client/tests projects (833 tests), the build, and a Bun smoke test against the ws adapter all pass. The one red check, Vercel trpc-v12, is a project misconfiguration (next/www doesn't exist on main) and unrelated.
🤖 Follow-ups from @KATT's review of the using refactor:
Ownership check (deefe9e): it wasn't needed. Duplicate ids are rejected before registering, subscription.stop only aborts, and a disconnect clears the map with no messages arriving afterwards. The check only existed because the old release also ran for queries. Registration is now a resource: using _subscription = registerSubscription(id, controller) sets the entry on creation and deletes it on dispose, and queries bind null. A new lifecycle test pins that a query reusing an active subscription's id leaves it registered.
The try (deefe9e): gone. An abort disposable declared after the iterator's await using is disposed first, so the signal is aborted before return() on every failure path. It skips a natural done on purpose: main and SSE don't abort on completion, and fix(server): only abort node-http requests when the connection closes early #7664 just fixed that for HTTP. A new test pins that a completed subscription doesn't abort its signal.
The .then (d63ee5e): gone. handleRequest is async, its using scope is an inner execute(), and after const outcome = await settle(execute()) it sends the error or stopped with plain control flow. The AbortError classification is a named isCancelledSetup(error, signal). It's a function rather than a try block because the scope's early returns still need to end in stopped.
No behaviour change; stopped and error replies go out about a microtask later, with unchanged order per id. The lifecycle suite (now 21 tests), the ws/subscription files (396 tests), the server/client/tests projects (835 tests), the build and Bun all pass. CI is green apart from the unrelated Vercel trpc-v12 project setting (next/www doesn't exist).
Drop the automaticallyWrappedError marker from getTRPCErrorFromUnknown.
A subscription cancelled during setup now reports `stopped` when setup
rejects with an INTERNAL_SERVER_ERROR caused by an AbortError; any other
cause or explicit code is still reported as an error. The check lives in
the setup catch so `const result = await callTRPCProcedure(...)` stays
as on main.
Also reject duplicate ids before registering instead of tracking
registration with a flag, drop the redundant readyState checks (a
disconnect aborts every registered subscription), and keep sending
`stopped` after an iteration error as main does.
Co-authored-by: Alex / KATT <[email protected]>
Replace `as` casts and non-null assertions with assert() narrowing, a
response type guard and small typed helpers.
Co-authored-by: Alex / KATT <[email protected]>
Removes the `ctxPromise!` non-null assertion: handleRequest is only
called once the context promise exists, so pass it in already narrowed.
Co-authored-by: Alex / KATT <[email protected]>
… interop handler
A subscription stopped before it starts gets no terminal message, so
wsLink can't tell its id is free. These tests expect `stopped`, as
v11's adapter sends since #7704.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
wsLink holds a subscription's id until its `stopped`. A
`subscription.stop` that interrupted the call before `started` sent
nothing, so the id was never released, unlike v11's adapter since
#7704. A closed socket's calls still send nothing, so
dispose() keeps leaving wsLink to resend its subscriptions.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…ate (port of #7704)
Interrupting a call (a stop, an abort or a closed socket) while its
resolver's promise is pending abandons the promise. When it later
resolved with an async iterable, nothing called its `return()`, so
whatever the procedure had opened for it stayed open; when it rejected,
the error vanished. v11's adapter disposes that iterable without
reading it, and reports the rejection, since #7704.
The resolver's promise is now awaited through `Effect.callback`: once
the call is interrupted, an iterable it resolves with is disposed with
`return()`, and a rejection other than an `AbortError` goes to the
call's `CurrentLateErrors`, so `onError` hears it.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…l (port of #7704)
A subscription's signal aborted only when its call was interrupted. When
its iterator's `next()` failed instead, the iterator's `return()` ran
with the signal still live, so a cleanup that waits for it never
finished. v11's adapter aborts the signal whenever iteration ends other
than by `done`, before the iterator's cleanup, since #7704.
`interruptSignal()` gets `abortUnlessDone`, which aborts when a stream
fails as well as when it's interrupted, and the v11 interop socket and
the native socket wrap a subscription's events in it. A subscription
that completes still keeps its signal; `abortOnInterrupt` is unchanged.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
… interop handler
A subscription stopped before it starts gets no terminal message, so
wsLink can't tell its id is free. These tests expect `stopped`, as
v11's adapter sends since #7704.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
wsLink holds a subscription's id until its `stopped`. A
`subscription.stop` that interrupted the call before `started` sent
nothing, so the id was never released, unlike v11's adapter since
#7704. A closed socket's calls still send nothing, so
dispose() keeps leaving wsLink to resend its subscriptions.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…ate (port of #7704)
Interrupting a call (a stop, an abort or a closed socket) while its
resolver's promise is pending abandons the promise. When it later
resolved with an async iterable, nothing called its `return()`, so
whatever the procedure had opened for it stayed open; when it rejected,
the error vanished. v11's adapter disposes that iterable without
reading it, and reports the rejection, since #7704.
The resolver's promise is now awaited through `Effect.callback`: once
the call is interrupted, an iterable it resolves with is disposed with
`return()`, and a rejection other than an `AbortError` goes to the
call's `CurrentLateErrors`, so `onError` hears it.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…l (port of #7704)
A subscription's signal aborted only when its call was interrupted. When
its iterator's `next()` failed instead, the iterator's `return()` ran
with the signal still live, so a cleanup that waits for it never
finished. v11's adapter aborts the signal whenever iteration ends other
than by `done`, before the iterator's cleanup, since #7704.
`interruptSignal()` gets `abortUnlessDone`, which aborts when a stream
fails as well as when it's interrupted, and the v11 interop socket and
the native socket wrap a subscription's events in it. A subscription
that completes still keeps its signal; `abortOnInterrupt` is unchanged.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
… interop handler
A subscription stopped before it starts gets no terminal message, so
wsLink can't tell its id is free. These tests expect `stopped`, as
v11's adapter sends since #7704.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
wsLink holds a subscription's id until its `stopped`. A
`subscription.stop` that interrupted the call before `started` sent
nothing, so the id was never released, unlike v11's adapter since
#7704. A closed socket's calls still send nothing, so
dispose() keeps leaving wsLink to resend its subscriptions.
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…ate (port of #7704)
Interrupting a call (a stop, an abort or a closed socket) while its
resolver's promise is pending abandons the promise. When it later
resolved with an async iterable, nothing called its `return()`, so
whatever the procedure had opened for it stayed open; when it rejected,
the error vanished. v11's adapter disposes that iterable without
reading it, and reports the rejection, since #7704.
The resolver's promise is now awaited through `Effect.callback`: once
the call is interrupted, an iterable it resolves with is disposed with
`return()`, and what that or the rejection fails with goes to the call's
`SubscriptionTeardown`, so a subscription's `onError` hears it (an
`AbortError` excepted).
Co-authored-by: Alex / KATT <[email protected]>
cursorBot
pushed a commit
that referenced
this pull request
Nov 4, 2026
…l (port of #7704)
A subscription's signal aborted only when its call was interrupted. When
its iterator's `next()` failed instead, the iterator's `return()` ran
with the signal still live, so a cleanup that waits for it never
finished. v11's adapter aborts the signal whenever iteration ends other
than by `done`, before the iterator's cleanup, since #7704.
`interruptSignal()` gets `abortUnlessDone`, which aborts when a stream
fails as well as when it's interrupted, and the v11 interop socket and
the native socket wrap a subscription's events in it. A subscription
that completes still keeps its signal; `abortOnInterrupt` is unchanged.
Co-authored-by: Alex / KATT <[email protected]>
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
The v11 WebSocket adapter registered a subscription only after its setup, so a stop or disconnect during setup was missed, and cleanup raced with id reuse.
What
await, and a duplicate id is rejected right away.stopped.onErroronly, and a duplicate id'serrorFormatterandonErrormay getctx: undefined.Links
None
Alternatives considered
Testing
With
main'sws.ts, 20 of 24 tests inwebsocketsLifecycle.test.tsfail.AI model
Claude Opus 5.5
Co-authored-by: Tiscs [email protected]
Need help on this PR? Tag
@codesmith-botwith what you need.Summary by CodeRabbit