Skip to content

fix(server): preserve websocket subscription ownership - #7654

Closed
Tiscs wants to merge 2 commits into
trpc:mainfrom
Tiscs:fix/ws-subscription-lifecycle
Closed

Tiscs wants to merge 2 commits into
trpc:mainfrom
Tiscs:fix/ws-subscription-lifecycle

Conversation

@Tiscs

@Tiscs Tiscs commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Changes

WebSocket subscriptions currently register only after context and procedure initialization. Stop/disconnect during admission can miss the operation, and an ID released before asynchronous disposal settles can receive an old subscription's late error.

This fix keeps each subscription's controller registered through admission, iteration, and disposal:

  • Register before admission awaits; reject duplicate IDs without replacing or canceling the original owner.
  • Cancel pending admission on stop/disconnect and dispose late iterators without consuming them, through either return() or Symbol.asyncDispose.
  • On synchronous or asynchronous iteration failure, abort the operation before awaiting disposal, allowing signal-aware background work to stop and drain.
  • Send terminal responses and release the ID only after disposal settles. Check ownership for responses and deletion, and suppress responses on closed sockets.
  • Normalize canceled admission to stopped only for automatically wrapped AbortErrors. Explicit tRPC errors remain errors, including INTERNAL_SERVER_ERROR with an inherited or identical message. Internal, non-enumerable Symbol provenance supports ESM/CJS interop without changing serialized errors or public exports.

Public APIs and wire messages remain unchanged. An ID remains reserved until cleanup settles; cancellation cannot force an uncooperative resolver or disposer to finish.

Related: #7400 and #7480. This addresses server-side admission and disposal races independently of the client AbortSignal and HTTP request-body changes in #7480.

Separate Bun CI fix

A separate commit makes the Bun example build/test scripts select their own tsconfig, so workspace aliases do not redirect dependency imports to library TypeScript sources. Bun 1.4.2 rejects a using declaration inside an async function nested in a switch case; the same failure reproduces on the unchanged PR base. This CI fix is independent of the WebSocket change.

Validation

Rebased onto upstream main 83391b53288250e14311e9c9d34949c9365556ac. Conflict resolution preserves upstream WebSocket types/documentation, batch-size enforcement, late next() error reporting after stop/disconnect, and the oxlint migration. The independent Bun commit retains only its three tsconfig-resolution script changes.

Added 21 lifecycle cases using real loopback WebSockets and deferred admission/disposal gates. Coverage includes shared-context cancellation, delayed admission, both disposal mechanisms, duplicate IDs, deferred cleanup success/failure, immediate ID reuse after iteration errors, abort-dependent cleanup for synchronous/asynchronous iteration failure, and preservation of explicit error codes and inherited/matching messages.

The original 10 cases expose 9 failures on the unchanged base (d756e59). The four latest cases fail on the preceding PR head (fa493ff) and pass after this fix.

  • Existing WebSocket, lifecycle, stop-teardown, localLink, TRPCError, and issue-3351 regression suites: 99 tests passed, retries disabled, official Vitest configuration.
  • Typechecks: @trpc/server, @trpc/client, and @trpc/tests.
  • Package lint: @trpc/server, @trpc/tests, and examples-bun; current upstream oxfmt check for all changed files.
  • Server/client ESM and CJS builds.
  • Bun 1.4.2: build, typecheck, test-dev, and test-start.

Existing test listeners were restricted to loopback with process-local validation harnesses; new tests explicitly bind to 127.0.0.1. No validation harness is committed.

Checklist

  • I have followed the relevant steps in the Contributing guide.
  • Documentation considered; no public API or configuration change.
  • I have added tests related to the changes.

Summary by CodeRabbit

  • Bug Fixes
    • WebSocket subscriptions now handle cancellation and disconnection more reliably, including while setup is in progress.
    • Canceled subscriptions report their stopped status when the connection is available.
    • Subscription IDs remain unavailable until iterator cleanup completes, and duplicate active IDs are rejected.
    • Responses are suppressed when the WebSocket connection is closed.
    • Subscription errors now abort the operation and are reported to the error handler; iterator errors are reported after cleanup.

Copilot AI balanced review requested due to automatic review settings October 5, 2026 17:52
@Tiscs
Tiscs requested a review from a team as a code owner October 5, 2026 17:52
@vercel

vercel Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
examples-todomvc Ready Ready Preview Nov 4, 2026 1:15pm UTC
next-prisma-starter Ready Ready Preview Nov 4, 2026 1:15pm UTC
og-image Ready Ready Preview Nov 4, 2026 1:15pm UTC
trpc-next-app-dir Ready Ready Preview Nov 4, 2026 1:15pm UTC
www Ready Ready Preview Nov 4, 2026 1:15pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The WebSocket adapter tracks subscription IDs, guards responses, and handles cancellation, errors, and iterator cleanup. New error helpers mark automatically wrapped errors. Lifecycle tests cover admission and disposal cases. Bun build and test commands pass a TypeScript configuration override.

Changes: WebSocket subscription lifecycle

Layer / File(s) Summary
Wrapped error marking
packages/server/src/unstable-core-do-not-import/error/wrappedErrors.ts, packages/server/src/unstable-core-do-not-import/error/TRPCError.ts
The error helpers mark and detect errors with a shared symbol. Newly constructed TRPCError instances are marked automatically wrapped.
Operation admission and ID ownership
packages/server/src/adapters/ws.ts, packages/tests/server/websocketsLifecycle.test.ts
The adapter registers subscription IDs before procedure execution, rejects duplicate IDs, and guards responses. Tests cover shared context creation, cancellation during admission, duplicate IDs, and admission errors.
Iterator disposal and completion
packages/server/src/adapters/ws.ts, packages/tests/server/websocketsLifecycle.test.ts
The adapter disposes iterators after cancellation and releases IDs after cleanup settles. Tests cover active iterator disposal, cleanup resolution or rejection, and iteration errors.

Bun example scripts

Layer / File(s) Summary
TypeScript configuration override
examples/bun/package.json
The build, development-test, and start-test commands pass ./tsconfig.json using --tsconfig-override.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant WebSocketAdapter
  participant AsyncIterator
  Client->>WebSocketAdapter: Stop subscription or close connection
  WebSocketAdapter->>AsyncIterator: Dispose iterator after cancellation
  AsyncIterator-->>WebSocketAdapter: Resolve or reject cleanup
  WebSocketAdapter->>Client: Send eligible stopped or error response
Loading

Suggested reviewers: nick-lucas

Merge Risk: Minimal · up to 8b925

The change tightens WebSocket subscription lifecycle handling, covering duplicate IDs, cancellation, and iterator cleanup, and keeps public APIs unchanged. No concrete merge-blocking issue was identified. Regression tests cover the targeted races.

Architecture risk: Low · up to 343ac

The change affects 3 systems.

Changed systems: examples, packages/server, packages/tests

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — examples (service) was modified; 1 changed file maps to changed impact.
  • observed — packages/server (library) was modified; 1 changed file maps to changed impact.
  • observed — packages/tests (library) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in packages/server/src/adapters/ws.ts: respond now returns without sending when the WebSocket is not open.
  • observed — Modified behavior in packages/server/src/adapters/ws.ts: Each operation now creates its abort controller before asynchronous work and defines guarded response, error, and cleanup handlers. Subscription responses are ignored if the ID no longer maps to that operation’s controller; errors abort the controller and release the ID. Cleanup deletes the ID only when its current mapping is the same controller.
  • observed — Modified behavior in packages/server/src/adapters/ws.ts: Subscription IDs are checked for duplicates and registered before awaiting context initialization; previously registration and duplicate checking occurred later, after the procedure returned an iterable. After context resolves, an aborted or disconnected subscription sends stopped through the guarded response path and releases its ID.
  • observed — Modified behavior in packages/server/src/adapters/ws.ts: Non-subscription data responses now use the operation-guarded response handler.
Pre-merge checks: Passed 4
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: preserving WebSocket subscription ownership during lifecycle races.
Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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
ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: trpc/trpc/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3091c1c1-98f9-42bd-99e7-e62d1044d565
📥 Commits

Reviewing files that changed from the base of the PR and between fa493ff and 8b92555.

📒 Files selected for processing (4)
  • packages/server/src/adapters/ws.ts
  • packages/server/src/unstable-core-do-not-import/error/TRPCError.ts
  • packages/server/src/unstable-core-do-not-import/error/wrappedErrors.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; 9 remain after this review.

Copilot AI 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.

Copilot review overview

🟡 Changes recommended

Iteration errors remain terminally reported before disposal settles, contrary to the intended ownership ordering.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
What changed in this PR

Preserves WebSocket subscription ownership across admission, iteration, and asynchronous disposal.

Changes:

  • Registers subscriptions before asynchronous admission and guards ownership.
  • Aborts and disposes canceled subscriptions safely.
  • Adds 10 lifecycle race regression tests.
File Description
packages/​server/​src/​adapters/​ws.ts Revises subscription lifecycle and ownership handling.
packages/​tests/​server/​websocketsLifecycle.test.ts Tests cancellation, duplicate IDs, and disposal races.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread packages/server/src/adapters/ws.ts Resolved
@pkg-pr-new

pkg-pr-new Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/@trpc/client@7654

@trpc/next

npm i https://pkg.pr.new/@trpc/next@7654

@trpc/openapi

npm i https://pkg.pr.new/@trpc/openapi@7654

@trpc/react-query

npm i https://pkg.pr.new/@trpc/react-query@7654

@trpc/server

npm i https://pkg.pr.new/@trpc/server@7654

@trpc/tanstack-react-query

npm i https://pkg.pr.new/@trpc/tanstack-react-query@7654

@trpc/upgrade

npm i https://pkg.pr.new/@trpc/upgrade@7654

commit: b08af1c

Copilot AI 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.

Copilot review overview

🟡 Changes recommended

Admission-time abort errors need cancellation handling, and unrelated Bun changes should be removed or documented.

Review effort: Balanced
Findings: 1 Medium severity · 1 Low severity

Open (2)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Handle admission aborts as stopped subscriptions

packages/​server/​src/​adapters/​ws.ts:325

An admission-time cancellation can still surface as an operation error. If the resolver is awaiting an abort-aware API such as fetch, subscription.stop aborts this signal and callTRPCProcedure rejects with AbortError; the outer catch then sends an error instead of the expected stopped terminal response. Handle an abort rejection from procedure admission as cancellation (send stopped and release ownership), while preserving genuine procedure and disposal failures as errors.

Comment thread examples/bun/package.json Resolved
@Tiscs

Tiscs commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Added a separate CI fix in 343acec. The Bun 1.4.2 failure also reproduces on the base commit: workspace tsconfig aliases cause Bun to load library TypeScript sources, triggering its using parsing issue. The Bun example's test/build scripts now explicitly use its own tsconfig and resolve the built packages. The WebSocket lifecycle patch is unchanged, and all four Bun CI steps now pass (run).

Copilot AI 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.

Copilot review overview

🟡 Changes recommended

Admission cancellation can incorrectly suppress an explicitly thrown tRPC error whose cause is an AbortError.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
Resolved since last review (2)

Comment thread packages/server/src/adapters/ws.ts Resolved

Copilot AI 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.

Copilot review overview

🔵 Needs a closer look

The concurrency-sensitive lifecycle changes are well tested, but final human review is warranted for cancellation and disposal ordering.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@Tiscs

Tiscs commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up lifecycle review found two additional edge cases, now fixed in the amended WebSocket commit:

  • Iteration failures abort before awaiting disposal, preventing cleanup from waiting on a signal that would otherwise abort only after cleanup.
  • Explicit tRPC errors with inherited or matching AbortError messages remain errors. Internal provenance is shared across ESM/CJS without changing serialized error fields.

Four new regression cases reproduce both issues on the previous head. All 92 related tests, typechecks, lint, server/client builds, and the four Bun checks pass locally. The PR still contains exactly two commits, with the independent Bun CI fix preserved.

Copilot AI 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.

🟢 Approval recommended

The ownership guards, disposal ordering, error handling, and regression coverage consistently address the identified races.

0 open findings

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

Tiscs added 2 commits November 4, 2026 21:06
Explicitly use the Bun example tsconfig for E2E execution and bundling so workspace path aliases do not redirect package imports to library TypeScript sources. Bun 1.4.2 rejects using declarations nested in async functions within switch cases when loading those sources. The failure also reproduces on the PR base commit.

Validated Bun 1.4.2 test-dev, build, typecheck, and test-start; localLink and websocket lifecycle regressions pass (21 tests).
@Tiscs
Tiscs force-pushed the fix/ws-subscription-lifecycle branch from 8b92555 to b08af1c Compare November 4, 2026 13:12
@vercel

vercel Bot commented Nov 4, 2026

Copy link
Copy Markdown

@Tiscs is attempting to deploy a commit to the trpc Team on Vercel.

A member of the Team first needs to authorize it.

@Tiscs

Tiscs commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased the two commits onto main at 83391b5 and resolved both conflicts. The WebSocket integration keeps upstream batch-size enforcement and late next() error reporting after cancellation, and the separate Bun commit preserves upstream oxlint configuration.

Local validation passed: 99 related tests, the upstream WebSocket batch-size regression suite, server/client/tests typechecks, affected package lint, oxfmt, server/client ESM/CJS builds, and all four Bun checks. The PR still contains exactly two commits and GitHub reports it mergeable. Fresh Actions checks are queued/running.

Three Vercel previews currently report "Authorization required to deploy." These are deployment-authorization gates; no deployment or CI infrastructure configuration was changed.

@Tiscs

Tiscs commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Closing this PR as superseded by #7704, which has been merged into main as b135fde.

#7704 builds on the original fix and tests from this PR, preserves authorship, and includes further lifecycle and compatibility improvements. Its merge also explains the new conflicts here, so there is no need to rebase this parallel implementation again.

Thanks for incorporating the fix and the follow-up work!

@Tiscs Tiscs closed this Nov 4, 2026
meefs pushed a commit to meefs/trpc that referenced this pull request Nov 4, 2026
…anup (trpc#7704)

<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
🤖 Ready for a trpc-core review: CI green on `10c47edee`; older clients
unaffected (11.0.0, 11.6.0 and 11.23.0 checked), a small perf cost, and
v12 brought in line on a separate branch.

Stack (#7893, bottom to top): trpc#7704 → trpc#7892 → trpc#7891.

## Why

- Refs trpc#7400. That issue's bug, a stale `clientSubscriptions` entry when
the subscription task rejects, was fixed on `main` by trpc#7401 on 12 Sep.
This PR fixes the races that remained in the same code.
- Supersedes trpc#7654. Thanks @Tiscs for finding these races and for the
original fix and tests. This branch starts from trpc#7654's fix commit and
keeps its authorship. The follow-ups are separate commits on top.
- In `packages/server/src/adapters/ws.ts`, a subscription went into
`clientSubscriptions` only after its context resolved and its procedure
returned an iterable. Until then:
- `subscription.stop` and disconnects couldn't find it, so a
subscription stopped during setup started anyway and ran until
disconnect. The official `wsLink` hits this: it sends
`subscription.stop` on `unsubscribe()`, and since trpc#7434 also when the
operation's signal aborts. A new test reproduces it with `wsLink`: on
`main` the resolver's body runs after the unsubscribe; here it never
starts.
- If the client disconnected during setup, the iterable the procedure
returned was never disposed.
- The duplicate-id check ran after setup, so two concurrent requests
with the same id could both pass it. The second overwrote the first's
`AbortController`, and the first could then no longer be stopped.
- The id was freed and `stopped` was sent before iterator disposal
finished. A late cleanup error could then go out under an id the client
had already reused.
- If `next()` threw, the subscription hung whenever its disposal waited
for the abort signal, because the signal was aborted only after
disposal.

## What

### Fix

- A subscription is registered before any `await`. A duplicate id is
rejected right away and never touches the original's entry.
- If the subscription is aborted (stop or disconnect) while its context
is being created, the procedure isn't called. If it's aborted while the
procedure runs, the returned iterator is disposed without being
consumed. Either way the reply is `stopped`.
- If iteration fails, the signal is aborted before disposal, so a
cleanup that waits for the signal can finish. A subscription that
completes normally still doesn't abort its signal, as on `main` and in
SSE.
- The id is freed, and the terminal message sent, only after iterator
disposal settles.
- Registration, abort-on-exit and iterator disposal use explicit
resource management (`using` / `await using`). Request outcomes are
settled into a result instead of chained with `.then()`.

### Protocol-visible changes

1. **Terminal messages are sent after iterator cleanup, not before.** On
`main`, a completed subscription sent `stopped` before its iterator was
disposed, and an iteration error sent `error` + `stopped` before
disposal. Both now go out once disposal settles. These messages tell the
client the id is free. Sent earlier, they cause either a spurious
`Duplicate id` error when the client reuses the id, or a late cleanup
error under the reused id. (Stopping an active subscription already
waited for `iterator.return()` on `main`.)
2. **A failed iterator cleanup goes to `onError` only.** The client
still gets `stopped` after a completion or a stop. When iteration and
cleanup both fail, the client gets the iteration error with its code,
and `onError` gets both. On `main` the cleanup error went out after
`stopped`, where `wsLink` ignored it. So clients see what they saw on
`main`, and a completed subscription doesn't turn into a failed one,
which would trip `retryLink`.
3. **`stopped` is sent when `subscription.stop` cancels setup.** On
`main` the stop was ignored and the subscription started anyway. A
client that sent `stop` needs a terminal message to know its id is free.
After a disconnect nothing reaches the client, because the socket is
closed.
4. **A duplicate id is rejected before the context resolves.** It gets
the same `BAD_REQUEST` `Duplicate id …` error, and the duplicate's
resolver is no longer called. One side effect: `errorFormatter` and
`onError` may now get `ctx: undefined` for that error.

The official `wsLink` drops its request before sending
`subscription.stop`, so change 3 doesn't reach it. The compatibility
matrix in Testing checks all four against published clients.

### Follow-ups from review (each a failing test, then the fix)

- **The iteration error was lost when cleanup also failed.** The `await
using` disposal wrapped both in a `SuppressedError`, so the client got
an empty `INTERNAL_SERVER_ERROR` instead of, say, `UNAUTHORIZED`. Fixed:
the client gets the iteration error, and `onError` gets both.
- **A cleanup failure after completion became a client error.** With
cleanup now awaited, a rejecting `return()` sent an `error` that old
clients turned into `onError` instead of `onComplete`. Fixed by change
2.
- **Perf:**
- An `abort()` on a signal that was already aborted still built an
`AbortError` with a stack trace, about 9% of CPU on subscribe/stop
churn. It's now skipped.
- The iteration loop ran in a settled closure, with extra suspended
frames for each subscription. It now runs inline.
- **Tests:**
  - `wsLink` unsubscribing during middleware.
  - Iteration errors keep their code.
  - Cleanup failures after a stop and after a stop during setup.
- A memory test that subscriptions stopped while active or during setup
are freed. It fails on `main`.

### Changes compared with trpc#7654

- **No global error marker.** The
`Symbol.for('trpc.automaticallyWrappedError')` helper and its use in
`getTRPCErrorFromUnknown` are reverted. One rule replaces the
five-condition check: if the subscription was aborted and the error is
an `INTERNAL_SERVER_ERROR` caused by an `AbortError`, report `stopped`.
That's how a resolver's `AbortError` arrives, since `callTRPCProcedure`
wraps everything. Errors with other causes or explicit codes are still
reported. One difference from trpc#7654: a deliberate `TRPCError({ code:
'INTERNAL_SERVER_ERROR', cause: abortError })` thrown after a stop now
counts as `stopped`.
- **Main's wire sequence for iteration errors is kept.** trpc#7654 dropped
the trailing `stopped` after an iteration `error`. This PR still sends
`error` then `stopped`, now after cleanup.
- **Less state.** Duplicates return early, so the
`subscriptionRegistered` flag and the owner-checked `respondToOperation`
wrapper are gone. So are the extra `client.readyState` checks and the
new guard in `respond()`. A disconnect aborts every registered
subscription, and `ws.send` is already a no-op on a closed socket.
- **No non-null assertion on the context promise.** The narrowed promise
is passed into `handleRequest`.
- **Tests without `as` casts or `!` assertions.**

### Unchanged

- Keepalive (trpc#7529), the `id: null` error when `createContext` throws
(trpc#7833), the encoder and the transformer paths.
- Queries and mutations: no duplicate-id check, as on `main`.

### Known edge cases

- An iterator whose `return()` never settles keeps its id reserved and
never sends `stopped`. That follows from freeing the id only after
cleanup. `main` behaves the same on a stop, and so does trpc#7654.
- An `onError` that throws still causes an unhandled rejection, as on
`main`.

## Links

None. This PR changes only `packages/server/src/adapters/ws.ts` and two
test files. It touches no docs pages or example routes.

## Alternatives considered

- **trpc#7654 as-is:** a global
`Symbol.for('trpc.automaticallyWrappedError')` marker in
`getTRPCErrorFromUnknown`, a five-condition cancellation check, extra
registration state, and no trailing `stopped` after an iteration
`error`. Replaced by the single abort-cause rule and the early duplicate
return, keeping main's wire sequence.
- **A minimal fix without the `using` refactor:** smaller, but the
disposal order would be hand-written in each path. The refactor costs
about 0.9 KB of heap per active subscription (see Testing), which we
judged worth it.
- **Send terminal messages before iterator cleanup (as on `main`):**
this causes either a spurious `Duplicate id` error when the client
reuses the id, or a late cleanup error under the reused id.
- **Send a failed cleanup to the client as an `error`:** this changes a
completion into a failure for clients that saw `stopped` on `main`.
- **Ignore `subscription.stop` during setup (as on `main`):** the
subscription starts anyway and runs until disconnect, and the client
never learns the id is free.
- **Leave it to v12:** v12 avoids most of these races by design, but
it's unreleased with no ETA, and v11 stays maintained until 12.0.0.

## Testing

All runs on Node 24.

- **Lifecycle tests.**
`packages/tests/server/websocketsLifecycle.test.ts`, 24 tests, all pass.
With `origin/main`'s `ws.ts` swapped in, 20 fail. The 4 that pass on
`main` guard against regressions:
  - stopping an active `asyncDispose` iterator;
  - a query reusing an active subscription's id;
  - a completed subscription not aborting its signal;
  - an `AbortError` without cancellation staying an error.
- **Memory test.** `websockets.memory.test.ts`'s new "frees
subscriptions stopped while active or during setup" runs 50
subscriptions stopped while active and 20 stopped during setup. It
checks that abort listeners drop to 0 and all 70 signals are collected.
It fails on `main` and passes here.
- **WebSocket and subscription files.** All 30, including
`websockets.test.ts`, `websockets.encoder.test.ts`,
`httpSubscriptionLink*.test.ts`, the trpc#7833 regression test and
`adapters/fastify.test.ts` (trpc#7529): 427 tests pass.
- **Package tests.** `pnpm exec vitest run --project @trpc/server
--project @trpc/client --project @trpc/tests`: 114 files, 881 tests
pass.
- **Gates.** `pnpm build`, `pnpm typecheck-packages`, `pnpm lint`
(oxlint) and `pnpm format` (`oxfmt --check`) pass.

### Perf and memory, `main` vs this PR

One connection, 10,000 subscriptions, built `dist`, `node --expose-gc`.
Each number is the median of 7 interleaved runs.

| Scenario | `main` | this PR |
| --- | --- | --- |
| 10k active: CPU | 3,402 ms | 3,601 ms (+5.9%) |
| 10k active: subscribe all / fan out / stop all | 544 / 165 / 792 ms |
607 / 163 / 801 ms |
| 10k active: heap while active | 411.5 MB | 432.2 MB (+2.1 KB per sub)
|
| 10k active: heap after stop + GC | 5.69 MB | 5.59 MB |
| 10k subscribe → data → stop churn | 107.5 µs/cycle, 1,495 ms CPU |
112.7 µs/cycle (+4.8%), 1,534 ms CPU |
| churn: heap after GC | 0.52 MB | 0.56 MB |
| 10k subscribe + stop sent together (stop during setup) | times out: 6
stopped, 10,000 bodies ran, 9,994 listeners and signals leaked, 414 MB
after GC | 280 ms: 10,000 stopped, 7 bodies ran, 0 leaked, 1.58 MB |

In every scenario on this branch, all emitter listeners, signals and
iterators are freed after GC, and reusing all 1,000 sampled ids gives no
`Duplicate id` errors. Of the +2.1 KB per active subscription, about 0.9
KB comes from the `using` helpers.

### Wire compatibility with published clients

Published `@trpc/client` 11.0.0, 11.6.0 (mid-11) and 11.23.0 (latest),
each against `main`'s server build and this PR's, with `ws` 8.18.1:

- **Same on `main` and this PR, for all three clients:**
  - query, mutation and subscription;
  - stop while active;
  - iteration error (code and message kept);
  - completion;
- cleanup failing after completion (client completes, `onError` gets
it);
  - iteration and cleanup both failing;
  - an id reused after `stopped`;
  - a same-tick batch;
  - reconnect after `broadcastReconnectNotification`;
  - no unhandled rejections.
- **Different, and fixed here:**
- **Stop during setup:** the client sees the same events on both. On
`main`, the resolver's body runs and its setup signal never aborts. Here
the signal aborts and the body never runs.
- **Disconnect during setup:** the client's events are the same. On
`main`, the first connection's setup signal never aborts. Here it does.
- **Id reused right after a stop:** this happens with two clients
sharing one `wsClient`, whose operation ids collide. On `main`, with
11.0.0 and 11.23.0, the second subscription gets the first's late
`stopped` and completes at once. Here it runs normally. With 11.6.0 it
happened to work on both.

No client gets a message type, or an error, that it didn't get on
`main`. Same on both, and outside this PR: after
`broadcastReconnectNotification`, while the server keeps the old socket
open, clients restart the subscription repeatedly. That's the `wsLink`
retired-socket bug, addressed client-side in trpc#7727.

### v12

- The lifecycle tests are ported to v12's v11 interop handler on branch
`cursor/v12-ws-lifecycle-tests-3334`, mirrored as
`v12-ws-lifecycle-tests` for v12's branch-name check.
- That branch also makes v12 reply `stopped` to a subscription stopped
before it starts, so v11 and v12 agree (plan decision D5).
- v12 doesn't hang when an iterator fails: the client gets `started`,
`error` and `stopped`. But the signal isn't aborted before cleanup, so a
cleanup that waits for it never finishes.
- Other gaps found there, left for v12:
  - a late iterator is never disposed;
  - the id is freed before cleanup settles;
  - cleanup failures never reach `onError`.

## AI model

Claude Opus 5.5

Co-authored-by: Tiscs <[email protected]>
<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a
href="https://cursor.com/agents/bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

<!-- codesmith:footer -->
---
<a
href="https://app.blacksmith.sh/trpc/codesmith/trpc/pr/7704?autoLogin=true&ref=codesmith_pr_footer"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v3.svg"><img
alt="View with [code]smith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"></picture></a>
<a
href="https://backend.blacksmith.sh/track/enable-autofix?expires=1795049077&installation_model_id=443568&pr_number=7704&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7704&signature=a7e42233c49c96eaf21921bb9099449d5244b04ed2f647ce3e88faed82af6709"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img
alt="Autofix with [code]smith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a>
<sup>Need help on this PR? Tag <code>@codesmith-bot</code> with what you
need.</sup>

<!-- codesmith:autofix:disabled -->
<!-- /codesmith:footer -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved WebSocket subscription cancellation during setup and active
iteration, including when a connection closes.
* Fixed cleanup of subscription resources after cancellation,
completion, or errors.
* Duplicate active subscription IDs are now rejected, and IDs can be
reused after a subscription ends.
* Improved handling of iterator and setup errors to provide clearer,
more consistent responses.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Tiscs <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Nov 5, 2026

This branch was successfully deployed

5 active (1 outdated) deployments
Preview – www — b08af1c8 Deployed Nov 4, 2026 by vercel[bot]
Preview – next-prisma-starter — b08af1c8 Deployed Nov 4, 2026 by vercel[bot]
Preview – trpc-next-app-dir — b08af1c8 Deployed Nov 4, 2026 by vercel[bot]
Preview – examples-todomvc — b08af1c8 Deployed Nov 4, 2026 by vercel[bot]
Preview – og-image — 8b925554 Deployed Oct 8, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants