Skip to content

fix(query-core): don't reject imperative fetch with CancelledError when a superseding fetch is started#11061

Open
xianjianlf2 wants to merge 2 commits into
TanStack:mainfrom
xianjianlf2:fix/fetchquery-cancelled-on-invalidate-8060
Open

fix(query-core): don't reject imperative fetch with CancelledError when a superseding fetch is started#11061
xianjianlf2 wants to merge 2 commits into
TanStack:mainfrom
xianjianlf2:fix/fetchquery-cancelled-on-invalidate-8060

Conversation

@xianjianlf2

@xianjianlf2 xianjianlf2 commented Jul 13, 2026

Copy link
Copy Markdown

Problem

When a fetch is silently cancelled because a new fetch supersedes it (e.g.
invalidateQueries refetching an active observer with cancelRefetch: true),
callers that joined the in-flight fetch via the early-return in Query.fetch
received the raw retryer promise, which rejects with a silent CancelledError.

The async fetch body already piggybacks onto the superseding fetch on silent
cancellation, but the early-return path bypassed it, so an imperative
fetchQuery could reject with a CancelledError even though the query
continued fetching.

Fix

Route both the early-return and the catch-block piggyback through a shared
helper that follows the chain of superseding fetches until one settles, while
still rethrowing when the silent cancellation isn't from a superseding fetch
(e.g. query destroyed).

Testing

Added a regression test in packages/query-core/src/__tests__/queryClient.test.tsx
covering the scenario where an imperative fetch is superseded by an
invalidateQueries-triggered refetch, asserting the imperative call resolves
with the fresh data instead of rejecting with a CancelledError.

Closes #8060

Summary by CodeRabbit

  • Bug Fixes

    • Fixed query fetching when an in-progress request is invalidated and refetched, ensuring the latest refetch result is used.
    • Updated handling of silent cancellations so imperative fetches no longer fail incorrectly and instead resolve with the superseding result.
    • Preserved existing cancellation behavior when a query is explicitly destroyed.
  • Tests

    • Added a regression test covering imperative fetchQuery resolution during invalidation while an observer is refetching.

…en a superseding fetch is started

When a fetch is silently cancelled because a new fetch supersedes it (e.g.
`invalidateQueries` refetching an active observer with `cancelRefetch: true`),
callers that joined the in-flight fetch via the early-return in `Query.fetch`
received the raw retryer promise, which rejects with a silent `CancelledError`.
The async `fetch` body already piggybacks onto the superseding fetch on silent
cancellation, but the early-return path bypassed it.

Route both the early-return and the catch-block piggyback through a shared
helper that follows the chain of superseding fetches until one settles, while
still rethrowing when the silent cancellation isn't from a superseding fetch
(e.g. query destroyed).

Closes TanStack#8060
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ddcc2701-80a7-4e79-a7d0-290e0029c043

📥 Commits

Reviewing files that changed from the base of the PR and between b51699f and 2c8a3ec.

📒 Files selected for processing (1)
  • packages/query-core/src/__tests__/queryClient.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/query-core/src/tests/queryClient.test.tsx

📝 Walkthrough

Walkthrough

Query now follows superseding fetch promises after silent cancellation. A regression test verifies that an imperative fetchQuery resolves successfully when invalidation triggers an active observer refetch.

Changes

Silent cancellation continuation

Layer / File(s) Summary
Superseding fetch promise handling
packages/query-core/src/query.ts, packages/query-core/src/__tests__/queryClient.test.tsx
Query follows replacement retryer promises for silent cancellations and in-flight fetch callers. A test covers invalidation during an imperative fetch with an active observer refetch.

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

Sequence Diagram(s)

sequenceDiagram
  participant QueryClient
  participant Query
  participant QueryObserver
  QueryClient->>Query: start imperative fetch
  QueryObserver->>Query: refetch after invalidation
  Query-->>Query: silently cancel superseded retryer
  Query-->>QueryClient: follow latest retryer promise
  Query-->>QueryClient: resolve with superseding result
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, fix, and testing, but it does not follow the repo template or include the required checklist and release impact sections. Rewrite the PR description using the template headings, and add the checklist plus release impact section with the required details.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the core change: preventing imperative fetches from rejecting with CancelledError after a superseding fetch starts.
Linked Issues check ✅ Passed The code and regression test address #8060 by making fetchQuery resolve with the superseding fetch result instead of a silent CancelledError.
Out of Scope Changes check ✅ Passed The changes are narrowly focused on query cancellation behavior and a matching regression test, with no obvious unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

🧹 Nitpick comments (1)
packages/query-core/src/__tests__/queryClient.test.tsx (1)

1060-1094: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen the assertion to verify fresh data from the superseding fetch.

expect.any(Number) would pass even if fetchPromise resolved with stale data from the priming fetch (count = 1) instead of fresh data from the superseding fetch (count = 2). Asserting the specific value verifies the correct fetch result is propagated.

♻️ Proposed fix
-    await expect(fetchPromise).resolves.toEqual(expect.any(Number))
+    await expect(fetchPromise).resolves.toBe(2)
🤖 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/query-core/src/__tests__/queryClient.test.tsx` around lines 1060 -
1094, Strengthen the final assertion in the invalidation/refetch test so
fetchPromise resolves specifically to 2, confirming it receives the superseding
fetch’s fresh result rather than the priming result of 1. Keep the existing test
flow and cleanup unchanged.
🤖 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.

Nitpick comments:
In `@packages/query-core/src/__tests__/queryClient.test.tsx`:
- Around line 1060-1094: Strengthen the final assertion in the
invalidation/refetch test so fetchPromise resolves specifically to 2, confirming
it receives the superseding fetch’s fresh result rather than the priming result
of 1. Keep the existing test flow and cleanup unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 58990ea9-f848-48e9-8acb-57928aedf22e

📥 Commits

Reviewing files that changed from the base of the PR and between 79d2384 and b51699f.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/queryClient.test.tsx
  • packages/query-core/src/query.ts

@xianjianlf2

Copy link
Copy Markdown
Author

Addressed the assertion-strengthening review in 2c8a3ec. I used toBe(3) rather than toBe(2) after verifying the sequence locally: 1 is the priming fetch, 2 is the observer's background refetch, and the invalidate-triggered superseding fetch resolves to 3.\n\nLocal check:\n- PATH=/Users/even/.nvm/versions/node/v24.18.0/bin:/Users/even/.nvm/versions/node/v20.20.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/pmk/env/global/bin:/Library/Apple/usr/bin:/Users/even/.codex/tmp/arg0/codex-arg0VOKUrl:/Users/even/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override:/Users/even/.bun/bin:/Users/even/.local/bin:/Users/even/.nvm/versions/node/v20.20.2/bin:/Users/even/.cargo/bin:/Users/even/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/fallback:/Applications/ChatGPT.app/Contents/Resources pnpm --dir packages/query-core test:lib src/__tests__/queryClient.test.tsx

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.

invalidateQueries inconsistently cancels fetchQuery

1 participant