Skip to content

fix(client): abort JSONL stream on httpBatchStreamLink unsubscribe - #7390

Merged
KATT merged 10 commits into
trpc:mainfrom
vinamra1102:fix/httpBatchStreamLink-abort-on-unsubscribe
Jul 26, 2026
Merged

KATT merged 10 commits into
trpc:mainfrom
vinamra1102:fix/httpBatchStreamLink-abort-on-unsubscribe

Conversation

@vinamra1102

@vinamra1102 vinamra1102 commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #7389

What changed

httpBatchStreamLink creates an AbortController and passes it to jsonlStreamConsumer on every request, but the observable's cleanup function was a noop abortController.abort() was never called on unsubscribe.

This meant the underlying JSONL response stream continued consuming data from the server even after the subscriber disconnected (component unmount, navigation, query cancellation).

Fix

Call abortController.abort() in the cleanup function so the stream is cancelled when the observable is unsubscribed.

Tests

Added a test that subscribes to a batch stream observable, unsubscribes before the response completes, and asserts the fetch was aborted.

Summary by CodeRabbit

  • Bug Fixes

    • Batch-stream network requests now reliably abort when subscriptions are canceled, and completion/error handling no longer triggers subsequent teardown aborts.
  • Tests

    • Added a test verifying network requests are aborted upon subscription cancellation.
  • Chores

    • Updated test package dependency versions for client and server test packages.

Review Change Stack

@vinamra1102
vinamra1102 requested a review from a team as a code owner May 25, 2026 10:59
@vercel

vercel Bot commented May 25, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
next-prisma-starter Ready Ready Preview Jul 26, 2026 11:17am
og-image Ready Ready Preview, Comment Jul 26, 2026 11:17am

Request Review

@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

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
📝 Walkthrough

Walkthrough

Creates a per-subscription AbortController in httpBatchStreamLink, races its signal with the operation signal when calling loader.load, aborts that controller on observable teardown (and marks subscription done on errors), and adds a test asserting fetch's AbortSignal is aborted after unsubscribe. Tests package deps are bumped.

Changes

httpBatchStreamLink Unsubscribe Abort Handling

Layer / File(s) Summary
Per-subscription AbortController and signal racing
packages/client/src/links/httpBatchStreamLink.ts
Creates an AbortController per observable subscription, passes signal: raceAbortSignals(op.signal, ac.signal) into loader.load, sets isDone = true on promise rejection, and calls ac.abort() in the observable teardown when not finished.
Test verification of unsubscribe abort behavior
packages/tests/server/links.test.ts
Adds a test that spies on globalThis.fetch, captures the passed AbortSignal, returns a never-ending ReadableStream, waits for the first fetch call, unsubscribes the chain subscription, and asserts the captured signal becomes aborted and its reason?.name equals 'AbortError'.
Test package dependency bump
packages/tests/package.json
Updates @trpc/client and @trpc/server versions from 11.16.0 to 11.17.0 in the tests package.

Sequence Diagram(s)

sequenceDiagram
  participant Subscriber
  participant httpBatchStreamLink
  participant Loader
  participant fetch
  Subscriber->>httpBatchStreamLink: subscribe()
  httpBatchStreamLink->>Loader: loader.load(op, { signal: raceAbortSignals(op.signal, ac.signal) })
  Loader->>fetch: globalThis.fetch(..., { signal })
  Subscriber->>httpBatchStreamLink: unsubscribe()
  httpBatchStreamLink->>httpBatchStreamLink: ac.abort()
  Loader->>fetch: fetch signal aborted
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • trpc/trpc#6462: Related fixes touching httpBatchStreamLink stream termination and error handling.

Suggested labels

♻️ autoupdate

Suggested reviewers

  • KATT
  • Nick-Lucas

Poem

A rabbit taps the stream with care,
Small controllers born for every subscribe,
Unsubscribe nibbles—abort! the signal flares,
No stray bytes linger, the pipeline sighs. 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: aborting the JSONL stream on unsubscribe in httpBatchStreamLink.
Description check ✅ Passed The description adequately explains the bug, the fix, and the test added. The template sections are covered (closing issue, changes summary, testing checklist completed).
Linked Issues check ✅ Passed The PR addresses all core objectives from #7389: creating per-subscription AbortController, passing combined signal to loader.load, calling abort() in observable cleanup, and adding abort verification test.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the AbortController issue: implementation in httpBatchStreamLink, test coverage, and necessary version bumps in package.json.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1001-1044: The test currently sets a global fetch mock and calls
vi.restoreAllMocks() only on the success path which can leak the mock; replace
the global mock with a factory-scoped mock (use a helper like getMockFetch())
and ensure teardown always runs by registering restoration in a
finally/afterEach-style cleanup so globalThis.fetch is restored regardless of
test outcome; update the test that constructs the mock used by
httpBatchStreamLink/mockRuntime (references: globalThis.fetch mock,
fetchCalled/fetchSignal, httpBatchStreamLink, createChain, chain.subscribe,
sub.unsubscribe) to obtain the mock from getMockFetch() and restore it in
guaranteed cleanup rather than calling vi.restoreAllMocks() only at the end.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ab85d44f-4f0f-4409-82db-6ebc6db2ee35

📥 Commits

Reviewing files that changed from the base of the PR and between 23c723c and 24bb263.

📒 Files selected for processing (2)
  • packages/client/src/links/httpBatchStreamLink.ts
  • packages/tests/server/links.test.ts

Comment thread packages/tests/server/links.test.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
packages/tests/server/links.test.ts (1)

1001-1043: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make fetch mock cleanup guaranteed and factory-scoped.

The current cleanup at Line 1043 only runs on the success path; if the test fails earlier, globalThis.fetch can remain mocked and bleed into later tests. Use a per-test mock factory and restore in finally.

Suggested patch
 test('httpBatchStreamLink - unsubscribe aborts fetch', async () => {
   let fetchSignal: AbortSignal | undefined;
-  const fetchCalled = new Promise<void>((resolve) => {
-    vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
-      fetchSignal = init?.signal ?? undefined;
-      resolve();
-      return new Response(
-        new ReadableStream({
-          start() {
-            // never enqueue or close - keeps the stream open
-          },
-        }),
-        { status: 200 },
-      );
-    });
-  });
+  let resolveFetchCalled: (() => void) | undefined;
+  const fetchCalled = new Promise<void>((resolve) => {
+    resolveFetchCalled = resolve;
+  });
+  const getMockFetch = () =>
+    vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
+      fetchSignal = init?.signal ?? undefined;
+      resolveFetchCalled?.();
+      return new Response(
+        new ReadableStream({
+          start() {
+            // never enqueue or close - keeps the stream open
+          },
+        }),
+        { status: 200 },
+      );
+    });
+  const mockFetch = getMockFetch();
 
-  const links = [
-    httpBatchStreamLink({
-      url: 'http://localhost:9999',
-    })(mockRuntime),
-  ];
+  try {
+    const links = [
+      httpBatchStreamLink({
+        url: 'http://localhost:9999',
+      })(mockRuntime),
+    ];
 
-  const chain = createChain({
-    links,
-    op: {
-      id: 1,
-      type: 'query',
-      path: 'hello',
-      input: null,
-      context: {},
-      signal: null,
-    },
-  });
+    const chain = createChain({
+      links,
+      op: {
+        id: 1,
+        type: 'query',
+        path: 'hello',
+        input: null,
+        context: {},
+        signal: null,
+      },
+    });
 
-  const sub = chain.subscribe({});
+    const sub = chain.subscribe({});
 
-  await fetchCalled;
+    await fetchCalled;
 
-  expect(fetchSignal!.aborted).toBe(false);
+    expect(fetchSignal!.aborted).toBe(false);
 
-  sub.unsubscribe();
+    sub.unsubscribe();
 
-  expect(fetchSignal!.aborted).toBe(true);
-
-  vi.restoreAllMocks();
+    expect(fetchSignal!.aborted).toBe(true);
+  } finally {
+    mockFetch.mockRestore();
+  }
 });
As per coding guidelines, "Create fresh mock instances per test using a factory (e.g., `getMockFetch()`)" and "Do not use global mocks that persist across tests".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tests/server/links.test.ts` around lines 1001 - 1043, The test
currently spies on globalThis.fetch directly and only restores mocks on the
success path; replace the direct spy with a per-test mock factory (e.g., call
getMockFetch() to create the mocked fetch and capture fetchSignal) and ensure
the mock is restored in a finally block (or use try/finally with
vi.restoreAllMocks() or mock.restore()) so globalThis.fetch cannot leak to other
tests; update the section that sets fetchSignal (formerly inside
vi.spyOn(globalThis, 'fetch').mockImplementation(...)) to use the factory's
implementation and call the factory-provided restore in finally after
sub.unsubscribe().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1001-1043: The test currently spies on globalThis.fetch directly
and only restores mocks on the success path; replace the direct spy with a
per-test mock factory (e.g., call getMockFetch() to create the mocked fetch and
capture fetchSignal) and ensure the mock is restored in a finally block (or use
try/finally with vi.restoreAllMocks() or mock.restore()) so globalThis.fetch
cannot leak to other tests; update the section that sets fetchSignal (formerly
inside vi.spyOn(globalThis, 'fetch').mockImplementation(...)) to use the
factory's implementation and call the factory-provided restore in finally after
sub.unsubscribe().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c58355e7-61ea-4170-ada9-e0b37e7c4dd5

📥 Commits

Reviewing files that changed from the base of the PR and between 24bb263 and 78acc26.

📒 Files selected for processing (3)
  • packages/client/src/links/httpBatchStreamLink.ts
  • packages/tests/package.json
  • packages/tests/server/links.test.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/tests/package.json

@pkg-pr-new

pkg-pr-new Bot commented May 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

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

@trpc/next

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

@trpc/openapi

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

@trpc/react-query

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

@trpc/server

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

@trpc/tanstack-react-query

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

@trpc/upgrade

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

commit: 8d482e4

The observable's cleanup function was a noop, so unsubscribing from a
batch stream link observable left the underlying fetch and JSONL stream
consuming data indefinitely. Now each observable creates an AbortController
whose signal is raced with the operation's existing signal; unsubscribe
calls abort(), propagating through allAbortSignals to cancel the fetch
once all subscribers in a batch have disconnected.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
packages/tests/server/links.test.ts (1)

1000-1043: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make fetch mock cleanup failure-safe and factory-scoped.

vi.restoreAllMocks() only runs on the success path here; if the test fails earlier, the globalThis.fetch mock can leak across tests.

Proposed fix
 test('httpBatchStreamLink - unsubscribe aborts fetch', async () => {
   let fetchSignal: AbortSignal | undefined;
-  const fetchCalled = new Promise<void>((resolve) => {
-    vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
+  let resolveFetchCalled: (() => void) | undefined;
+  const fetchCalled = new Promise<void>((resolve) => {
+    resolveFetchCalled = resolve;
+  });
+  const getMockFetch = () =>
+    vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
       fetchSignal = init?.signal ?? undefined;
-      resolve();
+      resolveFetchCalled?.();
       return new Response(
         new ReadableStream({
           start() {
             // never enqueue or close - keeps the stream open
           },
         }),
         { status: 200 },
       );
     });
-  });
+  const mockFetch = getMockFetch();
 
-  const links = [
-    httpBatchStreamLink({
-      url: 'http://localhost:9999',
-    })(mockRuntime),
-  ];
+  try {
+    const links = [
+      httpBatchStreamLink({
+        url: 'http://localhost:9999',
+      })(mockRuntime),
+    ];
 
-  const chain = createChain({
-    links,
-    op: {
-      id: 1,
-      type: 'query',
-      path: 'hello',
-      input: null,
-      context: {},
-      signal: null,
-    },
-  });
+    const chain = createChain({
+      links,
+      op: {
+        id: 1,
+        type: 'query',
+        path: 'hello',
+        input: null,
+        context: {},
+        signal: null,
+      },
+    });
 
-  const sub = chain.subscribe({});
+    const sub = chain.subscribe({});
 
-  await fetchCalled;
+    await fetchCalled;
 
-  expect(fetchSignal!.aborted).toBe(false);
+    expect(fetchSignal!.aborted).toBe(false);
 
-  sub.unsubscribe();
+    sub.unsubscribe();
 
-  expect(fetchSignal!.aborted).toBe(true);
-
-  vi.restoreAllMocks();
+    expect(fetchSignal!.aborted).toBe(true);
+  } finally {
+    mockFetch.mockRestore();
+  }
 });
As per coding guidelines, "Create fresh mock instances per test using a factory (e.g., `getMockFetch()`)" and "Do not use global mocks that persist across tests".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tests/server/links.test.ts` around lines 1000 - 1043, Replace the
global, test-wide fetch spy with a factory-scoped mock and guarantee cleanup in
a finally block: create a getMockFetch() helper that installs a mock
implementation on globalThis.fetch (capturing fetchSignal and resolving
fetchCalled as in the diff) and returns a restore function; in the test, call
const restore = getMockFetch(...) before creating links (instead of
vi.spyOn/globalThis.fetch) and then use try { ... the existing assertions and
sub.unsubscribe() } finally { restore() } (remove the vi.restoreAllMocks call).
This ensures the mock is fresh per test and always restored even if the test
fails; reference: getMockFetch, fetchCalled, fetchSignal, httpBatchStreamLink,
createChain, sub.unsubscribe.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@packages/tests/server/links.test.ts`:
- Around line 1000-1043: Replace the global, test-wide fetch spy with a
factory-scoped mock and guarantee cleanup in a finally block: create a
getMockFetch() helper that installs a mock implementation on globalThis.fetch
(capturing fetchSignal and resolving fetchCalled as in the diff) and returns a
restore function; in the test, call const restore = getMockFetch(...) before
creating links (instead of vi.spyOn/globalThis.fetch) and then use try { ... the
existing assertions and sub.unsubscribe() } finally { restore() } (remove the
vi.restoreAllMocks call). This ensures the mock is fresh per test and always
restored even if the test fails; reference: getMockFetch, fetchCalled,
fetchSignal, httpBatchStreamLink, createChain, sub.unsubscribe.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6d57a84b-d674-4c91-b990-583456c17b02

📥 Commits

Reviewing files that changed from the base of the PR and between 78acc26 and 5106b1b.

📒 Files selected for processing (3)
  • packages/client/src/links/httpBatchStreamLink.ts
  • packages/tests/package.json
  • packages/tests/server/links.test.ts

@vinamra1102

Copy link
Copy Markdown
Contributor Author

The Bun E2E failure is in examples/bun#test-dev and appears to be an
infrastructure issue (process exited with code 1, no failed assertions).
All other E2E suites pass including the streaming and batching tests
directly related to this change.

daltino

This comment was marked as low quality.

@vinamra1102

Copy link
Copy Markdown
Contributor Author

@daltino Thanks for the thorough review!

1. Cleanup return block with the isDone guard:

return () => {
  if (!isDone) {
    ac.abort();
  }
};

This ensures abort() only fires on explicit unsubscribe — not when the observable completes or errors naturally, which would kill the JSONL stream while iterable responses are still being consumed.

2. isDone is set to true at the top of both .then() and .catch(), before any observer.complete() or observer.error() call:

promise
  .then((res) => {
    isDone = true;
    // ... observer.next() + observer.complete()
  })
  .catch((err) => {
    isDone = true;
    observer.error(...);
  });

Since observer.complete()/observer.error() triggers teardown synchronously, isDone must be set before those calls.

3. Confirmed. raceAbortSignals accepts ...signals: Maybe<AbortSignal>[] and uses optional chaining (signal?.aborted, signal?.addEventListener) to skip null/undefined entries. When op.signal is null, only ac.signal is wired up.

4. Will add an expect(fetchSignal?.reason).toBeInstanceOf(DOMException) assertion to the test.

5. resolve() executes synchronously inside the mock body before return new Response(...). By the time await fetchCalled settles, fetchSignal is already captured — no race between signal capture and the assertion.

6. Acknowledged — _res is pre-existing, untouched by this change.

7. packages/tests/package.json lists bare version strings, but .npmrc has link-workspace-packages=true and pnpm-workspace.yaml includes packages/*, so pnpm resolves these as workspace links at install time. The 11.16.0 → 11.17.0 bump was applied by manypkg fix during pnpm lint-fix to match the current workspace version.

@github-actions

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 Jul 27, 2026

This branch was successfully deployed

5 active deployments
Preview – www — 8d482e42 Deployed Jul 26, 2026 by vercel[bot]
Preview – examples-todomvc — 8d482e42 Deployed Jul 26, 2026 by vercel[bot]
Preview – next-prisma-starter — 8d482e42 Deployed Jul 26, 2026 by vercel[bot]
Preview – trpc-next-app-dir — 8d482e42 Deployed Jul 26, 2026 by vercel[bot]
Preview – og-image — 8d482e42 Deployed Jul 26, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: httpBatchStreamLink AbortController is created but never called on unsubscribe

3 participants