Repository navigation
Description
- I've validated the bug against the latest version of DB packages
Versions
@tanstack/db1.0.0-rc.1.5@tanstack/react-db1.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
- 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. ThenRecordId, Decimal types, etc. work inuseLiveQuery({ query })and inqueryKeywithout a manual key. The same hook could feednormalizeValuesoeqcompares by value too. - (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 explicitqueryKey, 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
daveycodez commentedon Nov 22, 2026
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:That has to work in any table, for any record-id field, without a hand-written
queryKeyor acreateLiveQueryCollectionper value.So value equality in
eqis the core requirement, not an extra. Making these values hashable fixes identity, buteq(andinArray, join equality, index lookups) would still compare by reference, so two equalRecordIds still wouldn't match.Why reference equality is fragile here.
@surrealdb/tanstack-dbinternsRecordIds: 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. ARecordIdthat 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'sRecordIdalso implementsequals(other), which could be used for comparison if a serialization-based approach isn't preferred.aron-intframe commentedon Nov 22, 2026
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 everyloadSubset, the adapter takes theRecordIdinstance out of the request's predicate and rewrites the stored row'sidto that instance. So when two live queries ask for the same record with two equal but distinctRecordIdobjects, the query that loaded last owns the row, and the earlier query's referenceeqstops matching. It staysreadywith 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 stubdbinstead of a server:Where it happens, in the adapter's
dist/index.mjs(1.0.0-alpha.1):loadSubsetcallsprimeRecordIdIdentityFromSubset(subset)and thenapplyPreferredRecordIdIdentityToCollection(ctx, preferredFromSubset).normalizeSubsetValuesInPlacecallspreferRecordIdLikeIdentity, which doesrecordIdIdentityPool.set(canonical, value)for the predicate'sRecordId. The last instance seen wins. It also assignsobj.value = preferredback into the request's expression tree, which theLoadSubsetOptionsdocs in@tanstack/dbsay adapters must not do.applyPreferredRecordIdIdentityToCollectionwalkscollection.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
RecordIdthe 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-basedeqin@tanstack/db(your proposal 1) is what removes it.Workaround that works today: send every
RecordIdyour app puts into a query through one app-level intern keyed bytoString(). 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 referenceeqkeeps matching (second block above). This also covers the foreign-key case from your comment, with no per-valuequeryKey:I can't tell from here why adding
queryKeyhelped 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
RecordIdis constructed during render (for examplenew RecordId('user', params.id)in the component body) and there is noqueryKey, each render gets a newruntimeReferenceidentity, souseLiveQuerybuilds a new live query every render and never settles. This used a local on-demand collection, React 19.3.1 and jsdom:The only signal is the dev warning about deriving identity on a hot render path. It recommends
queryKeybut doesn't say which captured value keeps changing.daveycodez commentedon Nov 22, 2026
Thanks @aron-intframe, that's a very useful repro, and it matches what we saw: the adapter rebinds stored rows to whichever
RecordIdinstance the latest predicate carried, so only one instance matches at a time. With value equality from #2460, every equalRecordIdmatches regardless of which instance the adapter holds, so the rebinding no longer matters foreq. Separately, the adapter writing into theloadSubsetrequest is fixed in surrealdb/tanstack-db#16 (it doesn't fix the two-instance case by itself, sinceeqstill 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
RecordIdeven with #2460. That's #2461.