Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix(core): make sure queries revert synchronously #9601

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
TkDodo merged 1 commit into main from feature/sync-revert
Aug 30, 2025
Merged

Conversation

Copy link
Collaborator

@TkDodo TkDodo commented Aug 30, 2025
edited by coderabbitai bot
Loading

the switch from the callback approach to async/await with catch was necessary to be able to transform errors into revert-state data for imperative query calls; however, this was a change in behavior because catch in async/await doesn't happen immediately - it runs in the next microtask. That opened up an opportunity for a slight race condition if we re-start a fetch in-between. And who does that? Of course, React Strict Mode.

This PR moves the actual state reverting back to a callback (so it happens synchronously), while still keeping the try/catch refactoring merely to transform the promise and the usual error handling

fixes #9579

Summary by CodeRabbit

  • Refactor
    • Updated cancellation behavior: cancellations now invoke an onCancel callback with error details; revert (when requested) happens during onCancel, and canceled fetches no longer auto-reapply revert in the error path. Existing data is retained when available; otherwise, the cancellation surfaces.
    • Renamed the configuration option from abort to onCancel for retry/cancellation handling (breaking change for integrators).
  • Tests
    • Added coverage for unsubscribe/resubscribe during an in-flight fetch to validate the new cancellation semantics.

the switch from the callback approach to async/await with catch was necessary to be able to transform errors into revert-state data for imperative query calls; however, this was a change in behavior because catch in async/await doesn't happen immediately - it runs in the next microtask. That opened up an opportunity for a slight race condition if we re-start a fetch in-between. And who does that? Of course, React Strict Mode.
This PR moves the actual state reverting back to a callback (so it happens synchronously), while still keeping the try/catch refactoring merely to transform the promise and the usual error handling
Copy link

coderabbitai bot commented Aug 30, 2025
edited
Loading

Walkthrough

Introduces a new cancellation flow by replacing Retryer abort with onCancel, adjusts revert-on-cancel handling in query logic, and adds a test validating cancellation when resubscribing during an in-flight fetch. No other production files are modified.

Changes

Cohort / File(s) Summary
Retryer API and cancellation flow
packages/query-core/src/retryer.ts
Replaces abort?: () => void with onCancel?: (error: TError) => void. cancel() now creates a CancelledError, calls onCancel with it, and rejects with that typed error.
Query fetch and revert-on-cancel handling
packages/query-core/src/query.ts
Updates createRetryer usage to onCancel and moves revert-on-cancel behavior into the onCancel callback. Removes automatic revert from the catch path; now returns existing data or rethrows CancelledError as appropriate. Minor comment wording change.
Tests for cancellation semantics
packages/query-core/src/__tests__/query.test.tsx
Adds a test verifying that canceling an in-flight fetch upon unsubscribe triggers a new fetch on resubscribe, with the first promise rejecting as CancelledError and final state reflecting the second fetch’s success.

Sequence Diagram(s)

sequenceDiagram
 participant Obs1 as Observer #1
 participant Query as Query
 participant Retryer as Retryer
 participant AC as AbortController
 participant QFn as queryFn
 Obs1->>Query: subscribe()
 activate Query
 Query->>AC: new AbortController()
 Query->>Retryer: createRetryer({ onCancel })
 Retryer->>QFn: invoke(queryFn, { signal: AC.signal })
 activate QFn
 Obs1-->>Query: unsubscribe() (during in-flight)
 Retryer->>Retryer: cancel()
 Retryer-->>Query: onCancel(CancelledError)
 Note right of Query: If error.revert === true<br/>revert transient state
 Query->>AC: abort()
 deactivate QFn
 Retryer-->>Obs1: reject(CancelledError)
 participant Obs2 as Observer #2
 Obs2->>Query: subscribe()
 Query->>AC: new AbortController()
 Query->>Retryer: createRetryer({ onCancel })
 Retryer->>QFn: invoke(queryFn, { signal: AC.signal })
 QFn-->>Retryer: resolve(data1)
 Retryer-->>Query: success(data1)
 Query-->>Obs2: notify(status: success, fetchStatus: idle, data1)
 deactivate Query
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

package: query-core

Poem

A whisk of wind, a fetch in flight—
I thump to cancel, mid-delight.
Hop-hop, retry, new path I choose,
Abort the old, no time to lose.
Two carrots fetched, the second sweet—
Success at last, with tidy feet. 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/sync-revert

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

nx-cloud bot commented Aug 30, 2025
edited
Loading

View your CI Pipeline Execution ↗ for commit 23d4346

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 53s View ↗

☁️ Nx Cloud last updated this comment at 2025年08月30日 12:14:20 UTC

Copy link

pkg-pr-new bot commented Aug 30, 2025

More templates
@tanstack/angular-query-devtools-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9601
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9601
@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9601
@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9601
@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9601
@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@9601
@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@9601
@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9601
@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9601
@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@9601
@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@9601
@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9601
@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9601
@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@9601
@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9601
@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9601
@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@9601
@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9601
@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9601
@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@9601
@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9601

commit: 23d4346

Copy link

Sizes for commit 23d4346:

Branch Bundle Size
Main
This PR

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/query-core/src/retryer.ts (1)

13-13: Type-safety and ordering: make onCancel explicitly handle CancelledError and run before reject.

  • onCancel always receives a CancelledError; tightening the type clarifies intent and avoids downstream casts.
  • Running onCancel before reject ensures synchronous side-effects (like revert) occur prior to any queued catch handlers, making the fix more robust across environments.

Apply this diff:

@@ interface RetryerConfig<TData = unknown, TError = DefaultError> {
- onCancel?: (error: TError) => void
+ onCancel?: (error: CancelledError & TError) => void
@@
- const cancel = (cancelOptions?: CancelOptions): void => {
- if (!isResolved()) {
- const error = new CancelledError(cancelOptions) as TError
- reject(error)
-
- config.onCancel?.(error)
- }
- }
+ const cancel = (cancelOptions?: CancelOptions): void => {
+ if (!isResolved()) {
+ const error = new CancelledError(cancelOptions) as CancelledError & TError
+ // Run synchronous cancel side-effects (e.g., revert) before any queued catch handlers.
+ config.onCancel?.(error)
+ reject(error)
+ }
+ }

Also applies to: 87-93

packages/query-core/src/query.ts (1)

510-518: Defensive revert: guard against undefined revertState and narrow error type.

Today #revertState is set before creating the retryer, but a small guard makes this future-proof and avoids spreading undefined by accident.

Apply this diff:

- onCancel: (error) => {
- if (error instanceof CancelledError && error.revert) {
- this.setState({
- ...this.#revertState,
- fetchStatus: 'idle' as const,
- })
- }
- abortController.abort()
- },
+ onCancel: (error) => {
+ if (error instanceof CancelledError) {
+ if (error.revert && this.#revertState) {
+ this.setState({ ...this.#revertState, fetchStatus: 'idle' as const })
+ }
+ abortController.abort()
+ }
+ },
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 428c19f and 23d4346.

📒 Files selected for processing (3)
  • packages/query-core/src/__tests__/query.test.tsx (1 hunks)
  • packages/query-core/src/query.ts (2 hunks)
  • packages/query-core/src/retryer.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/query-core/src/__tests__/query.test.tsx (3)
packages/query-core/src/utils.ts (2)
  • sleep (355-359)
  • hashQueryKeyByOptions (203-209)
packages/query-core/src/query.ts (1)
  • Query (159-678)
packages/query-core/src/retryer.ts (1)
  • CancelledError (58-66)
packages/query-core/src/query.ts (1)
packages/query-core/src/retryer.ts (1)
  • CancelledError (58-66)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Test
  • GitHub Check: Preview
🔇 Additional comments (2)
packages/query-core/src/retryer.ts (1)

10-21: LGTM: onCancel hook restores synchronous revert without touching retry semantics.

Replacing abort with onCancel cleanly separates transport aborting from cancellation-side effects, aligning with the PR goal of synchronous revert. No behavioral regressions spotted in retry loop or pause/continue paths.

packages/query-core/src/query.ts (1)

561-563: Comment clarity is good; matches the new behavior.

The "piggyback onto that promise" note reads well and aligns with the silent cancel path. No change needed.

Comment on lines +1196 to +1244
test('should not override fetching state when revert happens after new observer subscribes', async () => {
const key = queryKey()
let count = 0

const queryFn = vi.fn(async ({ signal: _signal }) => {
// Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path
await sleep(50)
return 'data' + count++
})

const query = new Query({
client: queryClient,
queryKey: key,
queryHash: hashQueryKeyByOptions(key),
options: { queryFn },
})

const observer1 = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
})

query.addObserver(observer1)
const promise1 = query.fetch()

await vi.advanceTimersByTimeAsync(10)

query.removeObserver(observer1)

const observer2 = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
})

query.addObserver(observer2)

query.fetch()

await expect(promise1).rejects.toBeInstanceOf(CancelledError)
await vi.waitFor(() => expect(query.state.fetchStatus).toBe('idle'))

expect(queryFn).toHaveBeenCalledTimes(2)

expect(query.state).toMatchObject({
fetchStatus: 'idle',
status: 'success',
data: 'data1',
})
})
Copy link

@coderabbitai coderabbitai bot Aug 30, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix flakiness and expectation mismatch in new revert-sync test.

  • With fake timers active, waitFor won’t progress the 50ms sleep; advance timers instead to let the second fetch resolve.
  • Assert that after a microtask tick the state remains "fetching" (proves revert no longer overrides a new fetch).
  • The counter logic returns "data0" for the first completed call; make it pre-increment so the second fetch yields "data1" as asserted.

Apply this diff:

@@
- test('should not override fetching state when revert happens after new observer subscribes', async () => {
+ test('should not override fetching state when revert happens after new observer subscribes', async () => {
@@
- let count = 0
+ let count = 0
@@
- const queryFn = vi.fn(async ({ signal: _signal }) => {
- // Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path
- await sleep(50)
- return 'data' + count++
- })
+ const queryFn = vi.fn(async ({ signal: _signal }) => {
+ // Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path
+ await sleep(50)
+ return 'data' + ++count
+ })
@@
- query.fetch()
+ query.fetch()
+ // Let any queued catch handlers run; fetching state must remain
+ await Promise.resolve()
+ expect(query.state.fetchStatus).toBe('fetching')
@@
- await expect(promise1).rejects.toBeInstanceOf(CancelledError)
- await vi.waitFor(() => expect(query.state.fetchStatus).toBe('idle'))
+ await expect(promise1).rejects.toBeInstanceOf(CancelledError)
+ await vi.advanceTimersByTimeAsync(50)
+ expect(query.state.fetchStatus).toBe('idle')
@@
- expect(query.state).toMatchObject({
+ expect(query.state).toMatchObject({
 fetchStatus: 'idle',
 status: 'success',
- data: 'data1',
+ data: 'data1',
 })

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/query-core/src/__tests__/query.test.tsx around lines 1196 to 1244,
the test is flaky because fake timers prevent the 50ms sleep from advancing, the
test doesn’t assert the intermediate fetching state after the revert/new fetch
overlap, and the counter returns the wrong data; replace the vi.waitFor that
expects the 50ms sleep to complete with vi.advanceTimersByTimeAsync(50) so the
second fetch can resolve, add a microtask tick (e.g., await Promise.resolve() or
equivalent) and assert query.state.fetchStatus === 'fetching' immediately after
to prove revert didn’t override the new fetch, and change the counter increment
to pre-increment so the second resolved call yields "data1" to match the final
expectation.

Copy link
Contributor

Hi @TkDodo , I was thinking about the synchronous revert approach and wondered if it might face a similar challenge to what you mentioned in my PR?
Your comment: #9580 (comment)

When onCancel executes synchronously during removeObserver, wouldn't the revert happen immediately before any new observer can be added? Here's a test case that might help illustrate this scenario

test('should prevent revert when disabled observer is added after removal', async () => {
 const key = queryKey()
 const queryFn = vi.fn(async ({ signal: _signal }) => {
 await sleep(50)
 return 'data'
 })
 const query = new Query({
 client: queryClient,
 queryKey: key,
 queryHash: hashQueryKeyByOptions(key),
 options: { queryFn },
 })
 const observer1 = new QueryObserver(queryClient, {
 queryKey: key,
 queryFn,
 })
 query.addObserver(observer1)
 const promise1 = query.fetch()
 await vi.advanceTimersByTimeAsync(10)
 query.removeObserver(observer1)
 const observer2 = new QueryObserver(queryClient, {
 queryKey: key,
 queryFn,
 enabled: false,
 })
 query.addObserver(observer2)
 await expect(promise1).rejects.toBeInstanceOf(CancelledError)
 expect(query.state.fetchStatus).toBe('fetching')
 expect(query.state.data).toBeUndefined()
})

It seems like the synchronous execution might revert the state before the disabled observer gets added, which could lose the fetch state even though no new fetch was initiated.

Perhaps checking this.observers.length > 0 instead of this.isActive() might address both concerns? Since a disabled observer still indicates the component is using the query (just not actively fetching), wouldn't it make sense to preserve the state in that case? I'm curious what you think about this approach - it might handle both the original StrictMode issue and the disabled observer scenario.

Copy link
Collaborator Author

TkDodo commented Aug 30, 2025

When onCancel executes synchronously during removeObserver, wouldn't the revert happen immediately before any new observer can be added?

yes, it would, but that is what we want. The flow is this:

  • observer gets added, we fetch
  • observer gets removed, we cancel and revert the query back into fetchStatus: 'idle'
  • new observer gets mounted

now, the new observer can start from a "clean state" and will get us into fetchStatus: 'fetching' if the observer triggers a fetch, or it will keep us in idle state if its disabled.

before, we had this flow:

  • observer gets added, we fetch
  • observer gets removed, revert gets "scheduled" but isn’t done.
  • new observer gets mounted, initiates fetch
  • revert happens and sets us back to fetchStatus: 'idle', which is not what we want.

the test case you showed is wrong because query.addObserver alone doesn’t trigger anything. To initiate a fetch, we need observer.subscribe() or query.fetch. So you can’t expect the query to be in fetchStatus: 'fetching' by just calling query.addObserver.

joseph0926 reacted with thumbs up emoji joseph0926 reacted with heart emoji

Copy link

codecov bot commented Aug 30, 2025
edited
Loading

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.26%. Comparing base (428c19f) to head (23d4346).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@ Coverage Diff @@
## main #9601 +/- ##
===========================================
+ Coverage 45.15% 59.26% +14.11% 
===========================================
 Files 208 137 -71 
 Lines 8323 5565 -2758 
 Branches 1886 1494 -392 
===========================================
- Hits 3758 3298 -460 
+ Misses 4118 1963 -2155 
+ Partials 447 304 -143 
Components Coverage Δ
@tanstack/angular-query-devtools-experimental ∅ <ø> (∅)
@tanstack/angular-query-experimental 87.00% <ø> (ø)
@tanstack/eslint-plugin-query ∅ <ø> (∅)
@tanstack/query-async-storage-persister 43.85% <ø> (ø)
@tanstack/query-broadcast-client-experimental 24.39% <ø> (ø)
@tanstack/query-codemods ∅ <ø> (∅)
@tanstack/query-core 97.41% <100.00%> (+<0.01%) ⬆️
@tanstack/query-devtools 3.48% <ø> (ø)
@tanstack/query-persist-client-core 79.47% <ø> (ø)
@tanstack/query-sync-storage-persister 84.61% <ø> (ø)
@tanstack/query-test-utils ∅ <ø> (∅)
@tanstack/react-query 95.95% <ø> (ø)
@tanstack/react-query-devtools 10.00% <ø> (ø)
@tanstack/react-query-next-experimental ∅ <ø> (∅)
@tanstack/react-query-persist-client 100.00% <ø> (ø)
@tanstack/solid-query 78.13% <ø> (ø)
@tanstack/solid-query-devtools ∅ <ø> (∅)
@tanstack/solid-query-persist-client 100.00% <ø> (ø)
@tanstack/svelte-query 87.58% <ø> (ø)
@tanstack/svelte-query-devtools ∅ <ø> (∅)
@tanstack/svelte-query-persist-client 100.00% <ø> (ø)
@tanstack/vue-query 71.10% <ø> (ø)
@tanstack/vue-query-devtools ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@TkDodo TkDodo merged commit 379670d into main Aug 30, 2025
9 of 10 checks passed
@TkDodo TkDodo deleted the feature/sync-revert branch August 30, 2025 12:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Reviewers

@coderabbitai coderabbitai[bot] coderabbitai[bot] left review comments

Assignees
No one assigned
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

v5.85.2 introduced a breaking change while using StrictMode

AltStyle によって変換されたページ (->オリジナル) /