Skip to content

Query identity/hashing: support class instances with a stable serialization (e.g. toJSON), such as SurrealDB RecordId #2459

Open

Description

@daveycodez
  • I've validated the bug against the latest version of DB packages

Versions

  • @tanstack/db 1.0.0-rc.1.5
  • @tanstack/react-db 1.0.0-rc.1.5
  • Node 24.20.0 (repro), React app in the browser (real-world case)

Describe the bug

Query identity and value hashing only understand plain values plus a fixed set of built-ins. In canonicalizeRuntimeValue (query/ir-stable-identity.js) Date, Map, Set, ArrayBuffer/typed arrays, bigint, undefined, NaN/±Infinity/-0 and plain objects are handled; any other class instance throws:

UnhashableQueryIRError: Query IR is not stably hashable at value: non-plain object value

Inside query IR, equality / exact-output operands that are class instances don't throw; they get a per-reference runtimeReference identity, and eq also compares them by reference (normalizeValue special-cases Date, Temporal and Uint8Array, but nothing else). So two equal value objects give different query identities and don't match each other.

This hits ID types that are classes. @surrealdb/tanstack-db (SurrealDB's adapter) stores every row id as the surrealdb SDK's RecordId class (_table, _id, equals(), toString() → "user:abc", toJSON()). The obvious query is:

const { data: user } = useLiveQuery({
  query: (q) =>
    q.from({ user: users }).where(({ user }) => eq(user.id, userId)).findOne(),
})
// userId: RecordId<"user">

In our app this hook reported status: 'ready' / isReady: true with no row, while the source collection held the matching row and an equivalent createLiveQueryCollection returned it. Adding an explicit queryKey (["currentUser", String(userId)]) fixed it. We haven't pinned down the exact internal path (the collection is syncMode: 'on-demand'), but from the app's side the failure was silent: nothing was thrown or logged. Also, queryKey itself goes through getStableValueHash, so queryKey: ["currentUser", userId] throws; the ID has to be turned into a string by hand.

To Reproduce

Minimal, no SurrealDB needed:

import {
  createCollection, localOnlyCollectionOptions, createLiveQueryCollection,
  eq, getStableValueHash, getQueryIdentity, Query,
} from '@tanstack/db'

class RecordId {
  constructor(table, id) { this.table = table; this.id = id }
  toString() { return `${this.table}:${this.id}` }
  toJSON() { return this.toString() }
}

// 1. Value hashing (used for queryKey / derived hook identity)
getStableValueHash({ d: new Date(0) }) // ok: ["Date","1970-01-01T00:00:00.000Z"]
getStableValueHash(new RecordId('user', 'abc'))
// UnhashableQueryIRError: Query IR is not stably hashable at value: non-plain object value

// 2. Query identity: equal values, different identity
const users = createCollection(localOnlyCollectionOptions({
  id: 'users',
  getKey: (u) => u.id.toString(),
  initialData: [{ id: new RecordId('user', 'abc'), name: 'A' }],
}))
const ir = (v) => new Query().from({ user: users }).where(({ user }) => eq(user.id, v))._getQuery()
getQueryIdentity(ir(new RecordId('user', 'abc'))) === getQueryIdentity(ir(new RecordId('user', 'abc')))
// false: value is ["runtimeReference", "...", n]

// 3. eq on an equal but distinct instance matches nothing
const lq = createLiveQueryCollection((q) =>
  q.from({ user: users }).where(({ user }) => eq(user.id, new RecordId('user', 'abc'))))
await lq.preload()
lq.toArray.length // 0 (1 when the exact stored instance is passed)

Expected behavior / proposal

  1. Value-based identity for serializable class instances. When a value isn't one of the built-ins but provides a stable serialization, use it instead of throwing or falling back to reference identity. For example, use toJSON() when present, or a symbol hook ([Symbol.for('tanstack.db.hash')]()), or a configurable hasher/normalizer. Then RecordId, Decimal types, etc. work in useLiveQuery({ query }) and in queryKey without a manual key. The same hook could feed normalizeValue so eq compares by value too.
  2. (Moved to Dev warning when a live query captures a value with only reference identity (silent empty results or render loops) #2462, so this issue covers requirement 1 only.) Fail loudly instead of silently. If a captured value can't be given a stable identity (or is only identified by reference), throw or log a dev-mode warning that names the value path and points at queryKey, instead of a query that reports ready with no rows. Today the only workaround is an explicit queryKey, which the react-db docs describe as being for opaque functional variants.

Additional context

Real-world setup: @surrealdb/tanstack-db 1.0.0-alpha.1, surrealdb 2.x, surrealCollectionOptions({ table: { name: 'user' }, syncMode: 'on-demand', ... }).

Activity

  1. daveycodez commented on Nov 22, 2026

    @daveycodez
    ContributorAuthor

    Some more context on why this matters beyond the current-user example above.

    The real need is filtering on foreign keys in any table. The example in the issue is eq(user.id, userId), but the case that makes workarounds unworkable is scoped data where row-level permissions let you read many people's rows, e.g. profiles of everyone in your orgs:

    useLiveQuery({
      query: (q) => q.from({ profile: profiles }).where(({ profile }) => eq(profile.orgId, orgId)),
    })
    // profile.orgId and orgId are both RecordId<"org">

    That has to work in any table, for any record-id field, without a hand-written queryKey or a createLiveQueryCollection per value.

    So value equality in eq is the core requirement, not an extra. Making these values hashable fixes identity, but eq (and inArray, join equality, index lookups) would still compare by reference, so two equal RecordIds still wouldn't match.

    Why reference equality is fragile here. @surrealdb/tanstack-db interns RecordIds: it keeps one shared instance per canonical id string and normalizes every record-id field in every row to it. Reference equality therefore only works when the app's value happens to be that interned instance, and the adapter doesn't export a way to obtain it. A RecordId that comes from the SDK's auth call, a route param, or another query generally won't be the same object, so the filter silently matches nothing.

    Another stable hook. Besides toJSON() (→ "table:id"), the SDK's RecordId also implements equals(other), which could be used for comparison if a serialization-based approach isn't preferred.

  2. aron-intframe commented on Nov 22, 2026

    @aron-intframe

    The "ready, no row, while the source collection holds the row" part reproduces without React and without useLiveQuery. It comes from @surrealdb/tanstack-db, not from the hook. On every loadSubset, the adapter takes the RecordId instance out of the request's predicate and rewrites the stored row's id to that instance. So when two live queries ask for the same record with two equal but distinct RecordId objects, the query that loaded last owns the row, and the earlier query's reference eq stops matching. It stays ready with no row.

    Repro with the real packages (@surrealdb/tanstack-db@1.0.0-alpha.1, @tanstack/db@1.0.0-rc.1.5, surrealdb@2.2.2) and a stub db instead of a server:

    const db = {
      query: async () => [[{ id: new RecordId('user', 'abc'), name: 'A' }]],
      isFeatureSupported: () => false,
      live: async () => ({ subscribe() {}, kill: async () => {} }),
      select: async () => [],
    }
    const users = createCollection(surrealCollectionOptions({
      db, table: { name: 'user' }, queryClient: new QueryClient(), queryKey: ['user'], syncMode: 'on-demand',
    }))
    const byId = (v) => createLiveQueryCollection((q) =>
      q.from({ user: users }).where(({ user }) => eq(user.id, v)).findOne())
    
    const idA = new RecordId('user', 'abc') // e.g. from the SDK's auth/info call
    const idB = new RecordId('user', 'abc') // e.g. built from a route param
    const a = byId(idA); a.subscribeChanges(() => {}); await a.preload()
    const b = byId(idB); b.subscribeChanges(() => {}); await b.preload()
    $ node repro/adapter.mjs
    --- two equal RecordId instances
    after query A loads: A=1 row, source rows=1, stored row.id is idA
    after query B loads: A=0 row (status=ready), B=1 row, source rows=1, stored row.id is idB
    --- same ids through an app-level intern
    after query A loads: A=1 row, source rows=1, stored row.id is idA (=== idB)
    after query B loads: A=1 row (status=ready), B=1 row, source rows=1, stored row.id is idA (=== idB)
    

    Where it happens, in the adapter's dist/index.mjs (1.0.0-alpha.1):

    • loadSubset calls primeRecordIdIdentityFromSubset(subset) and then applyPreferredRecordIdIdentityToCollection(ctx, preferredFromSubset).
    • normalizeSubsetValuesInPlace calls preferRecordIdLikeIdentity, which does recordIdIdentityPool.set(canonical, value) for the predicate's RecordId. The last instance seen wins. It also assigns obj.value = preferred back into the request's expression tree, which the LoadSubsetOptions docs in @tanstack/db say adapters must not do.
    • applyPreferredRecordIdIdentityToCollection walks collection.entries() and rewrites (delete, then insert) every stored row whose id now maps to a different instance.

    So the "interned" instance isn't stable either. It is whichever RecordId the latest predicate carried, so exporting it wouldn't help. The rebind can make only one instance match at a time, so the adapter can't solve this alone. Value-based eq in @tanstack/db (your proposal 1) is what removes it.

    Workaround that works today: send every RecordId your app puts into a query through one app-level intern keyed by toString(). That includes ids from the auth call, route params, and ids read from other rows (profile.orgId). Every predicate then carries the same instance, the adapter rebinds rows to it, and reference eq keeps matching (second block above). This also covers the foreign-key case from your comment, with no per-value queryKey:

    const ids = new Map<string, RecordId>()
    export const rid = <T extends RecordId>(id: T): T => {
      const k = id.toString()
      let v = ids.get(k)
      if (!v) ids.set(k, (v = id))
      return v as T
    }
    // where(({ profile }) => eq(profile.orgId, rid(orgId)))

    I can't tell from here why adding queryKey helped in your app. The failure doesn't need the hook, so my guess is that it changed which query issued the latest load.

    One more data point for proposal 2 ("fail loudly"). If the RecordId is constructed during render (for example new RecordId('user', params.id) in the component body) and there is no queryKey, each render gets a new runtimeReference identity, so useLiveQuery builds a new live query every render and never settles. This used a local on-demand collection, React 19.3.1 and jsdom:

    $ NODE_ENV=development node repro/loop.mjs nokey
    queryKey=false: 5000 renders after 1151ms, still rendering; last: status=loading isReady=false data=undefined
    $ NODE_ENV=development node repro/loop.mjs key
    queryKey=true renders in 1s: 3
    

    The only signal is the dev warning about deriving identity on a hot render path. It recommends queryKey but doesn't say which captured value keeps changing.

  3. daveycodez commented on Nov 22, 2026

    @daveycodez
    ContributorAuthor

    Thanks @aron-intframe, that's a very useful repro, and it matches what we saw: the adapter rebinds stored rows to whichever RecordId instance the latest predicate carried, so only one instance matches at a time. With value equality from #2460, every equal RecordId matches regardless of which instance the adapter holds, so the rebinding no longer matters for eq. Separately, the adapter writing into the loadSubset request is fixed in surrealdb/tanstack-db#16 (it doesn't fix the two-instance case by itself, since eq still compares by reference without #2460).

    To keep this issue closable by #2460, I'm narrowing it to requirement 1 (value identity and equality for classes with a stable serialization, i.e. toJSON()). Requirement 2 (fail loudly / a dev warning naming the captured value when it only has reference identity), including your render-loop data point, is now tracked in #2462.

    Related, on the persistence side: rows restored from SQLite persistence decode as plain objects rather than class instances, so they don't compare equal to a RecordId even with #2460. That's #2461.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions