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) between server and client.
  • Bug Fixes
    • More robust hydration: queries are correctly reconstructed or updated with serialized keys and initial promise-based results are reused conditionally without altering fetch status.
  • Tests
    • Expanded hydration tests covering non-primitive keys and serialization scenarios.
  • Chores
    • Added a dev dependency to support test serialization.

Copy link

nx-cloud bot commented Jun 24, 2025

View your CI Pipeline Execution ↗ for commit a114b10

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

☁️ Nx Cloud last updated this comment at 2025-09-26 12:11:30 UTC

Copy link

pkg-pr-new bot commented Jun 24, 2025

More templates

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

@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 -1229
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 46.37%. Comparing base (db60bdd) to head (a114b10).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #9308      +/-   ##
==========================================
- Coverage   46.38%   46.37%   -0.01%     
==========================================
  Files         214      214              
  Lines        8488     8487       -1     
  Branches     1927     1919       -8     
==========================================
- Hits         3937     3936       -1     
  Misses       4108     4108              
  Partials      443      443              
Components Coverage Δ
@tanstack/angular-query-experimental 93.85% <ø> (ø)
@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.48% <92.00%> (-0.01%) ⬇️
@tanstack/query-devtools 3.48% <ø> (ø)
@tanstack/query-persist-client-core 79.60% <ø> (ø)
@tanstack/query-sync-storage-persister 84.61% <ø> (ø)
@tanstack/query-test-utils 77.77% <ø> (ø)
@tanstack/react-query 96.00% <ø> (ø)
@tanstack/react-query-devtools 10.00% <ø> (ø)
@tanstack/react-query-next-experimental ∅ <ø> (∅)
@tanstack/react-query-persist-client 100.00% <ø> (ø)
@tanstack/solid-query 78.06% <ø> (ø)
@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
Contributor Author

Choose a reason for hiding this comment

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

hello 🙃

Copy link
Contributor

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 now serializes queryKey via serializeData; hydrate deserializes queryKey and data, updates existing queries only when appropriate (preserving fetchStatus), creates new queries with deserialized keys/meta, and conditionally re-uses an initial promise to trigger retries.
Hydration Tests
packages/query-core/src/__tests__/hydration.test.tsx
Replace ad-hoc serialization hooks with superjson.serialize/superjson.deserialize; import superjson and set defaultOptions for dehydrate/hydrate; add a test validating Date-containing (non-primitive) query keys; remove explicit mocks for serialization/deserialization.
Package Metadata
packages/query-core/package.json
Add superjson as a devDependency and adjust devDependencies formatting.

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: serialize({ 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

Suggested reviewers

  • arnoud-dv

Assessment against linked issues

Objective Addressed Explanation
Serialize inputs (e.g., Date/ObjectId) in createHydrationHelpers to prevent errors (#6802) Hydration/dehydration now serialize/deserialize queryKey and data using provided serializers (superjson used in tests).

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! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description does not follow the repository’s required template since it lacks the designated “## 🎯 Changes”, “## ✅ Checklist”, and “## 🚀 Release Impact” sections and omits the checklist items and release impact details. Please update the description to use the provided template by adding the “## 🎯 Changes” section with a summary of modifications, including the required checklist under “## ✅ Checklist” and specifying release impact under “## 🚀 Release Impact”.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title “fix: serialize queryKey” succinctly captures the core change of adding serialization to query keys using superjson and follows conventional commit style, making it clear and focused on the main fix.
Linked Issues Check ✅ Passed The changes implement serialization of non-primitive query keys via superjson in both dehydration and hydration, update the core hydration workflow accordingly, and include tests for complex key types, directly addressing the requirements of issue #6802.
Out of Scope Changes Check ✅ Passed All modifications, including the addition of the superjson dev dependency, hydration logic updates, and test adjustments, are directly related to serializing query keys and do not introduce any unrelated or out-of-scope changes.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Copy link
Contributor

@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.

Copy link

changeset-bot bot commented Sep 26, 2025

⚠️ No Changeset found

Latest commit: a114b10

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

@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 (1)
packages/query-core/src/__tests__/hydration.test.tsx (1)

1385-1429: Make the new key-serialization test less brittle

The toMatchObject assertion on Query instances can be fragile due to instance internals. You already assert queryKey and queryHash equality; that’s sufficient.

Apply:

     expect(clientEntry.queryKey).toEqual(queryKey)
     expect(clientEntry.queryKey).toEqual(serverEntry.queryKey)
     expect(clientEntry.queryHash).toEqual(serverEntry.queryHash)

-    expect(clientEntry).toMatchObject(serverEntry)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33df077 and a114b10.

📒 Files selected for processing (2)
  • packages/query-core/package.json (1 hunks)
  • packages/query-core/src/__tests__/hydration.test.tsx (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/query-core/package.json
🧰 Additional context used
🧬 Code graph analysis (1)
packages/query-core/src/__tests__/hydration.test.tsx (2)
packages/query-core/src/queryClient.ts (1)
  • QueryClient (61-648)
packages/query-core/src/hydration.ts (2)
  • dehydrate (122-163)
  • hydrate (165-267)
⏰ 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: Preview
  • GitHub Check: Test
🔇 Additional comments (5)
packages/query-core/src/__tests__/hydration.test.tsx (5)

1-1: Optional: Prefer Vitest’s assert over node:assert for consistency

Importing assert from vitest keeps all test utilities from the same source and avoids Node-specific ESM specifiers in tests.

Apply:

-import assert from 'node:assert'
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, test, vi, assert } from 'vitest'

Also applies to: 4-4, 7-8


45-45: No action needed (formatting-only change)

Whitespace-only change.


972-996: LGTM: superjson-based (de)serialization wired correctly

Using serializeData/deserializeData with superjson ensures non-plain types (e.g., Date) round-trip for both data and queryKey.

Based on learnings

Also applies to: 1008-1032, 1044-1069


1208-1208: LGTM

The client-side QueryClient instantiation here is fine and reads clearer.


1384-1384: No action needed (formatting-only change)

Whitespace-only change.

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
4 participants