Skip to content

Conversation

KATT
Copy link
Contributor

@KATT KATT commented Jun 24, 2025

Serialize query keys the same way .data is serialized

Should fix trpc/trpc#6802

Summary by CodeRabbit

  • New Features
    • Query keys are now serialized during dehydrate/hydrate, enabling reliable round-tripping of complex keys (e.g., Date) across server and client.
  • Bug Fixes
    • More robust hydration: correctly reconstructs or updates queries with serialized keys and conditionally reuses initial promises without disrupting fetch status.
  • Tests
    • Expanded hydration test coverage, including non-primitive query keys and various dehydration/rehydration scenarios.
  • Chores
    • Added superjson as a dev dependency to support test serialization.

Copy link

nx-cloud bot commented Jun 24, 2025

View your CI Pipeline Execution ↗ for commit 33df077

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 2m 28s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 20s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-20 18:42:58 UTC

Copy link

pkg-pr-new bot commented Jun 24, 2025

More templates

@tanstack/angular-query-devtools-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9308

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9308

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9308

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9308

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9308

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@9308

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@9308

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9308

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9308

@tanstack/react-query

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

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@9308

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9308

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9308

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@9308

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9308

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9308

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@9308

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9308

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9308

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@9308

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9308

commit: 33df077

@KATT KATT marked this pull request as ready for review June 24, 2025 12:34
@KATT KATT marked this pull request as draft June 24, 2025 14:47
@KATT KATT marked this pull request as ready for review June 25, 2025 19:17
Comment on lines -1223 to -1228
expect(serializeDataMock).toHaveBeenCalledTimes(1)
expect(serializeDataMock).toHaveBeenCalledWith(0)

expect(deserializeDataMock).toHaveBeenCalledTimes(1)
expect(deserializeDataMock).toHaveBeenCalledWith(0)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed these as the test isn't about whether if serialization is about and the amount of times the mock gets called doubled so it gets a bit weird and unintuitive anyway

Copy link

codecov bot commented Jun 28, 2025

Codecov Report

❌ Patch coverage is 92.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 45.14%. Comparing base (a1b1279) to head (33df077).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #9308      +/-   ##
==========================================
- Coverage   45.15%   45.14%   -0.01%     
==========================================
  Files         208      208              
  Lines        8323     8322       -1     
  Branches     1886     1876      -10     
==========================================
- Hits         3758     3757       -1     
  Misses       4118     4118              
  Partials      447      447              
Components Coverage Δ
@tanstack/angular-query-devtools-experimental ∅ <ø> (∅)
@tanstack/angular-query-experimental 87.00% <ø> (ø)
@tanstack/eslint-plugin-query 83.24% <ø> (ø)
@tanstack/query-async-storage-persister 43.85% <ø> (ø)
@tanstack/query-broadcast-client-experimental 24.39% <ø> (ø)
@tanstack/query-codemods 0.00% <ø> (ø)
@tanstack/query-core 97.40% <92.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 77.77% <ø> (ø)
@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.

@@ -1,9 +1,11 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import assert from 'node:assert'
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this come from vitest?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's please hold off merging this until I'm back from vacation. Not sure if this is the right fix

Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

Dehydrate now serializes queryKey and data; hydrate deserializes queryKey/data, updates or rebuilds queries, and may re-use an initial promise to retry fetches. Tests switch to superjson for round-tripping non-primitive keys and add a test for Date-containing query keys. package.json adds superjson devDependency.

Changes

Cohort / File(s) Summary
Hydration Core Logic
packages/query-core/src/hydration.ts
Dehydrate queryKey via serializeData; hydrate deserializes queryKey and data, updates existing queries only when appropriate, creates new queries with deserialized keys/meta, and conditionally re-uses initial promise to trigger retries.
Hydration Tests
packages/query-core/src/__tests__/hydration.test.tsx
Replace ad-hoc Date/string conversions with superjson.serialize/deserialize; import superjson and set defaultOptions for dehydrate/hydrate; add test for complex (non-primitive) query keys and remove explicit serialization mocks.
Package Metadata
packages/query-core/package.json
Add superjson as a devDependency and adjust trailing comma in devDependencies.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Server
  participant Serializer as serializeData (superjson)
  participant Transport
  participant Client
  participant Hydrator as hydrate()
  participant Cache as QueryCache

  Server->>Serializer: dehydrate({ queryKey, data, ... })
  Serializer-->>Server: { serializedKey, serializedData, ... }
  Server->>Transport: send dehydrated payload
  Transport-->>Client: dehydrated payload

  Client->>Hydrator: hydrate(payload, { deserializeData })
  note right of Hydrator #DDEBF7: deserialize queryKey & data
  Hydrator->>Hydrator: deserializeQueryKey(), deserializeData()
  alt query exists in Cache
    Hydrator->>Cache: update state if dehydrated/newer (preserve fetchStatus)
  else
    Hydrator->>Cache: create query with deserialized key/meta and set state
  end
  opt initial promise present & eligible
    Hydrator->>Cache: attach initialPromise.then(deserializeData) -> retry fetch
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Assessment against linked issues

Objective Addressed Explanation
Serialize inputs (e.g., Date/ObjectId) in createHydrationHelpers to prevent errors (#6802)

Poem

I nibbled on keys, both crunchy and sweet,
Turned Dates into bytes for a tidy treat.
With superjson sparkles, I hop through the wire,
Hydrate my cache, then quietly retire.
Hashes align—what a delight! 🥕✨

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.


📜 Recent 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 99d3730 and 33df077.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • packages/query-core/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/query-core/package.json
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 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 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

@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: 0

🧹 Nitpick comments (3)
packages/query-core/src/hydration.ts (2)

89-91: Serializing queryKey changes the dehydrated payload shape — document and/or adjust typing

By setting queryKey: serializeData(query.queryKey), the dehydrated payload can now contain a non-QueryKey shape (e.g., superjson’s { json, meta }). However, DehydratedQuery.queryKey is typed as QueryKey (an array), which can mislead consumers who inspect dehydrated.queries on the server. At minimum, document that queryKey is serialized; optionally, widen the type to reflect reality.

Proposed doc update (outside the changed hunk):

// In interface DehydratedQuery
/**
 * Note: `queryKey` is serialized using the same transformer as `.state.data`
 * during dehydration and must be deserialized on hydration. Its runtime shape
 * may not be `QueryKey` until deserialized.
 */
interface DehydratedQuery {
  queryHash: string
  // consider: queryKey: unknown
  queryKey: QueryKey
  ...
}

If you want stricter correctness, consider changing the type to unknown and adapting internal usages. This would be a minor typing break for anyone accessing dehydrated.queries[i].queryKey directly, so weigh it against compatibility.


201-205: Defensive deserialization of queryKey to avoid hydration crashes

If a consumer mismatches serializers between dehydrate and hydrate, deserializeData(nextQuery.queryKey) can throw. A small guard prevents hard failures during hydration and falls back to the raw value.

Apply this diff:

-    const data = rawData === undefined ? rawData : deserializeData(rawData)
-    const queryKey = deserializeData(nextQuery.queryKey)
+    const data = rawData === undefined ? rawData : deserializeData(rawData)
+    let queryKey: QueryKey
+    try {
+      queryKey = deserializeData(nextQuery.queryKey) as QueryKey
+    } catch {
+      // Fallback for older payloads or mismatched serializers
+      queryKey = nextQuery.queryKey as unknown as QueryKey
+    }
packages/query-core/src/__tests__/hydration.test.tsx (1)

1-4: Minor: prefer using vitest’s expect over node:assert for consistency

The helper using Node’s assert is fine, but the suite predominantly uses expect. Consider inlining it with expect(entry).toBeTruthy() to keep a single assertion style.

-import assert from 'node:assert'
...
-    const getFirstEntry = (client: QueryClient) => {
-      const [entry] = client.getQueryCache().getAll()
-      assert(entry, 'cache should not be empty')
-      return entry
-    }
+    const getFirstEntry = (client: QueryClient) => {
+      const [entry] = client.getQueryCache().getAll()
+      expect(entry).toBeTruthy()
+      return entry!
+    }
📜 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 a1b1279 and 99d3730.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • packages/query-core/package.json (1 hunks)
  • packages/query-core/src/__tests__/hydration.test.tsx (10 hunks)
  • packages/query-core/src/hydration.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/query-core/src/__tests__/hydration.test.tsx (1)
packages/query-core/src/hydration.ts (2)
  • dehydrate (122-163)
  • hydrate (165-267)
packages/query-core/src/hydration.ts (2)
packages/query-core/src/query.ts (1)
  • promise (198-200)
packages/query-core/src/thenable.ts (1)
  • tryResolveSync (94-111)
🔇 Additional comments (4)
packages/query-core/package.json (1)

63-65: Add devDependency for superjson — looks good

Adding superjson under devDependencies is appropriate since it's only used in tests. No runtime impact.

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

249-265: Initial promise reuse is sound; confirm serializer symmetry for promise payloads

Reusing the server-side promise with initialPromise: Promise.resolve(promise).then(deserializeData) is aligned with the earlier serialization via query.promise?.then(serializeData). Please ensure docs/examples emphasize that consumers must pass symmetrical serializeData/deserializeData functions for both data and keys to avoid mismatch in restored data and query hash.

Would you like me to add a short docs snippet to the README explaining that both data and queryKey now use the same serializers and must be configured together?

packages/query-core/src/__tests__/hydration.test.tsx (2)

971-979: Consistent use of superjson in tests — good coverage

Switching to superjson for serialize/deserialize in tests accurately validates round-tripping of non-primitive data and keys. This meaningfully exercises the new behavior.

Also applies to: 988-994, 1007-1015, 1024-1030, 1043-1050, 1063-1067


1384-1429: Great end-to-end test for non-plain query keys

The test asserting key equality and hash parity across dehydrate/hydrate with a Date in the key is exactly what we needed. This should prevent regressions for the linked issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

bug: createHydrationHelpers doesn't serialize inputs
3 participants