Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
779dd77
fix(db): compare value classes with toJSON() by their serialized value
daveycodez Nov 22, 2026
78e7261
test(db): run the value class equality oracle in test:oracles
daveycodez Nov 22, 2026
0150c6a
fix(db): keep built-in rules for Map, Set and ArrayBuffer subclasses …
daveycodez Nov 22, 2026
e81a21d
fix(db): order value class ranges by serialized value
daveycodez Nov 23, 2026
e9849ad
fix(db): keep value class ranges and indexes consistent
daveycodez Nov 23, 2026
21fa4a3
fix(db): compare shared arrays in full and reconcile reference filters
daveycodez Nov 23, 2026
83487c7
fix(db): propagate reference replacements through queries
daveycodez Nov 23, 2026
17088e4
fix(db): scope Effect suppression and forward replacements to pooled …
daveycodez Nov 24, 2026
2c4661d
fix(db): carry deep-equal replacements through ordered queries
daveycodez Nov 24, 2026
77a2c6e
fix(db): hash replaced rows by reference for query operators
daveycodez Nov 24, 2026
78ce8a3
fix(db): keep distinct and hash-equal updates on live rows
daveycodez Nov 24, 2026
97ba764
test(db): oracle array order and distinct stability
daveycodez Nov 24, 2026
b24a616
docs: describe array order and distinct stability oracles
daveycodez Nov 24, 2026
e112e49
fix(db): address CodeRabbit replay and serialization findings
daveycodez Nov 24, 2026
dea0e34
fix(db): keep joined-load updates in Effects and release pooled views
daveycodez Nov 24, 2026
cad8034
fix(db): finish an Effect's replacement passes before publishing
daveycodez Nov 24, 2026
e6a6c03
test(db): generate the fixed reference-replacement oracle histories
daveycodez Nov 24, 2026
893f3a6
test(db): own the pooled view's state revision instead of a removed m…
daveycodez Nov 24, 2026
9ae974e
fix(db): carry deep-equal replacements through an Effect's truncate r…
daveycodez Nov 26, 2026
f76f059
test(db-ivm): send zero-weight inputs and cyclic payloads through dis…
daveycodez Nov 27, 2026
50e8781
fix(db-ivm): ignore zero-weight inputs and hash distinct support by key
daveycodez Nov 27, 2026
29f579a
test(db): check value class serializations and unchanged order in row…
daveycodez Nov 27, 2026
ef8423c
fix(db): count a changed serialization as a row change and keep poole…
daveycodez Nov 27, 2026
96cde17
test(db): follow a truncate replay through an Effect's functional filter
daveycodez Nov 27, 2026
1761ab7
test(db): require one array range order that agrees with sorting
daveycodez Nov 27, 2026
fadbc80
fix(db): order every array in range predicates as sorting does
daveycodez Nov 27, 2026
f58298b
docs: state the value class serialization contract and the new oracle…
daveycodez Nov 27, 2026
1ff8704
test(db-ivm): name distinct collision payloads by member in observations
daveycodez Nov 27, 2026
bb19965
test(db): keep array range tests in step with the sorted order
daveycodez Nov 27, 2026
ad9894f
test(db): avoid shadowed names in the value class row equality property
daveycodez Nov 27, 2026
8836d58
test(db): run the array order property three times as often
daveycodez Nov 27, 2026
7fb2cf4
test(db-ivm): judge a distinct throw on a legal delivery as a law vio…
daveycodez Nov 27, 2026
29d3eae
fix(db): describe why a range ranks object kinds inside arrays
daveycodez Nov 27, 2026
666ad49
fix(db-ivm): track distinct support for keys that cannot be hashed
daveycodez Nov 27, 2026
ae8294d
fix(db): address CodeRabbit replay, ordering and identity findings
daveycodez Nov 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/index-equal-row-replacement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/db': patch
'@tanstack/db-ivm': patch
---

Keep indexes and filtered subscriptions current when a sync write replaces a row with a deep-equal one. A reference-valued field such as a `Map` could stay indexed under its old instance, so a later update left a stale entry and ordered reads could repeat one row and omit another. A subscription or live query filtered on such a field by reference now loses or gains the row when its instance is replaced, including through joins, functional filters, ordered queries, filters over a projection and pooled queries. An ordered query also takes the position of the new instance, and a `distinct` query always shows an instance some row still holds. A reader that keeps the row is still told nothing, because its value is unchanged. A subscriber that buffers a truncate replay also drops a row whose reference left its filter during the replay, and an Effect's joins follow a row whose reference a truncate replay replaced with a deep-equal instance. An Effect still reports a real update that a joined source delivers while deep-equal replacements run, and a pooled query no longer keeps discarded views alive or evaluates their filters on deep-equal writes. A real update between values that hash alike, such as a class and a plain object with the same fields, now reaches ordered queries and joins too. An ordered pooled query no longer notifies readers when deep-equal replacements leave its order unchanged. `distinct` accepts keys and payloads outside the selected identity that cannot be hashed, such as cyclic ones, and never shows an input of weight zero. A truncate replay's deep-equal replacement also reaches a filter on the new instance after `distinct`.
5 changes: 5 additions & 0 deletions .changeset/value-class-equality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': minor
---

Compare instances of value classes, classes whose instances define `toJSON()` such as the `surrealdb` SDK's `RecordId`, by their serialized value instead of by reference. `eq`, `inArray`, join conditions, `groupBy`, indexes and ordering now match a distinct instance with an equal `toJSON()` result, so filtering or joining on record IDs works in any table. Query identity follows the same relation: equal captures are one query, so `useLiveQuery` needs no `queryKey` for them, and `getStableValueHash` (and therefore a `queryKey`) accepts such instances instead of throwing `UnhashableQueryIRError`. A value class instance never equals a plain value equal to its serialization. Dates, Temporal values, binary data, Maps, Sets and RegExps (including subclasses that define `toJSON()`) keep their own rules, and plain objects, arrays and classes without `toJSON()` still compare by reference. Range predicates (`gt`, `gte`, `lt`, `lte`) order a value class by the same serialized value as `orderBy`, rather than by `valueOf()`. Range predicates over arrays now compare them element by element in the order `orderBy` gives them, whether or not they hold a value class, so `[2]` is less than `[10]` and the order is transitive; where sorting would order two plain objects or two symbols by identity, the arrays compare as equal from that element on, and a symbol sorts after a nested array as it does in `orderBy`. Replacing a value class with an instance that serializes differently counts as a row change even when its enumerable fields are unchanged. A value class's `toJSON()` is read once, the first time it is compared or hashed, so instances must not be mutated afterwards.
81 changes: 81 additions & 0 deletions docs/contributing/oracle-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -2454,6 +2454,87 @@ The deep-equality and Collection change-event history owners check a Duration
field replacement and its subscriber mirror. These fixed histories do not
establish arbitrary multirow Duration updates or live-query publication.

The [value class equality oracle](https://github.com/TanStack/db/blob/main/packages/db/tests/query/serialized-value-equality-oracle.property.test.ts)
(`serialized-value.query-equality`, issue #2459) owns query equality for class
instances with `toJSON()`. An independent model compares record references by
their table and ID fields. Generated histories of up to four source rows, three
join rows and three synced updates, with no index, a BasicIndex or a
BTreeIndex, compare scans before and after indexing, an ordered read (equal
values in one run), a live-query `eq` filter, range filters against a record
probe, an inner join, query identity, demand keys and `getStableValueHash`,
including an unequal record and a nested query key. Every row and probe is a
fresh instance with its own `valueOf()`,
and a constructed history replaces an indexed group's first instance with an
equal one. Rows and join rows also hold Map, Set, ArrayBuffer and RegExp
subclasses whose `toJSON()` spells a record reference; they keep their built-in rule and
never match a record probe or join row, and a constructed history places one
among equal records. Plain records and arrays hold a throwing `toJSON`
accessor that must not be read. Array range filters compare captures with
shared and distinct object leaves, and a row that holds the capture array
itself. A constructed history replaces an indexed reference value with a
deep-equal one before updating its row. Each stored built-in carrier is also a
reference probe: a filtered subscription, a live query, a functional filter, a
filter over a plain, ordered or joined projection, a join with a Collection
holding the same instance, pooled views with attached and detached observers, and a fresh scan hold exactly
the rows that store it when each commit returns, and an Effect does once it has
run. An unfiltered subscriber and live query, ID filters and pooled ID views
that stay matched, and an Effect receive a change only when a row's value
changed, and a real update beside a replacement in one batch still reaches an
Effect, and a `distinct` query shows an instance some row still holds, with
at least one row and at most one per source row. A Date range bound and its
timestamp have different query identities over a record row. It does
not cover `inArray` (fixed tests in
`ir-stable-identity.test.ts`), on-demand or persisted sources, exact-output
identity, which keeps reference semantics, or throwing `toJSON()` methods.
Its second property (`serialized-value.array-order`) checks `gt`, `gte`, `lt`
and `lte` over generated arrays that mix value classes, record-shaped
`toJSON()` classes, plain objects, numbers, text (one numeric), nulls,
PlainDates, symbols, a typed array subclass and self-referencing arrays
against an independent order
model, including the native operators' throws, with the right operand's
objects given runtime identities first, and each value class instance
serialized at most once. Every array orders element by element. Over every
pair and triple of a history's array operands it checks that opposite pairs
have opposite signs and that the order is transitive, that range predicates
agree with `ascComparator` wherever an independent sort model says sorting
reads no reference, and that they tie where sorting first orders two objects
or two symbols by identity (PR #2460 review). Transitivity is not
checked through a number and a text that spells no number, which the
relational operators leave unordered. Only one generated text spells a number:
the relational operators and sorting compare a number with such a text as
numbers but two texts by code units, which is not transitive
(`5 < '10' < '2' < 5`) for bare values on main as well. Sorting is not compared through self-referencing arrays or
where it orders a Temporal value, an array or another object by reference.
Three more generated properties use small models.
`serialized-value.truncate-replay` gives up to three rows a probe reference, a
deep-equal copy or no row before a direct subscriber's truncate and after its
replay, and requires the replay to publish nothing before it completes and
then exactly the rows that stopped or started matching, to a filtered
subscription, to an Effect that joins on the probe and to an Effect whose
functional filter compares the reference with it, a `distinct` live query
over the references to show an instance some row still holds, and an Effect
that filters a `distinct` subquery on the probe to follow the replay.
`serialized-value.effect-joined-load` opens an on-demand
join load with a deep-equal or normal update; the provider moves one to three
rows by real updates or deep-equal replacements and may dispose the Effect,
and the model gives the one batch. `serialized-value.pooled-residual-swap`
applies batches of moves, real updates, deep-equal sort-field and tag
replacements, and tag serialization changes behind the same enumerable fields
to a pooled group with or without a residual reference filter, in key or
sort-field order. It compares attached and detached readers with the rows that
pass, in order, with their tag's serialization, and requires a batch of
deep-equal replacements that leaves the group's order and the shown rows as
they were to keep the attached snapshot and notify no subscriber. In a residual
view, a replacement that moves a row only past rows the view filters out is
outside that silence claim. The deep-equality owner's `utils.44` requires row
equality to tell apart value classes whose serialization differs behind equal
enumerable fields, bare, in a record or in an array. The
distinct representative oracle requires a shown payload to stay while the
inputs that hold it do, and `ivm.distinct-support-collisions` adds and removes
the four inputs of one verified digest family against a multiset model summed
by output key and payload, with zero-weight inputs before a world's changes
and self-referencing keys and payloads outside the selection.

The
[Temporal index order tests](https://github.com/TanStack/db/blob/main/packages/db/tests/temporal-index-order.test.ts)
(fixed tests; no oracle owner (tracked in #2264)) covers ZonedDateTime instant
Expand Down
24 changes: 24 additions & 0 deletions docs/guides/live-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,30 @@ Comparisons follow SQL/PostgreSQL conventions rather than raw JavaScript:
- **`null` / `undefined` use three-valued logic.** Any comparison involving `null` or `undefined` evaluates to `UNKNOWN`, so the row is not matched. For example `eq(user.score, null)` matches nothing — use a dedicated null check (e.g. `isUndefined`) to match missing values.
- **`NaN` follows PostgreSQL float semantics.** `NaN` is treated as equal to itself and greater than every other (non-null) value. So `eq(row.value, NaN)` matches `NaN` rows, `gt(row.value, x)` includes `NaN`, and ordering by such a field places `NaN` last. (Invalid `Date` values, whose timestamp is `NaN`, behave the same way.) This differs from JavaScript, where `NaN === NaN` is `false`, and matches how PostgreSQL orders and indexes floating-point values.

#### Value classes

A value class is a class whose instances define a `toJSON()` method, such as the `RecordId` of the `surrealdb` SDK or a decimal type. Queries compare its instances by their serialized value rather than by reference, so a distinct instance with the same `toJSON()` result matches:

```tsx
// userId and user.id are both RecordId instances, not the same object
const { data: user } = useLiveQuery({
query: (q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.id, userId))
.findOne(),
})
```

This applies to `eq`, `inArray`, join conditions, `groupBy`, indexes and ordering, and to query identity: two captures with equal `toJSON()` results are the same query, so the hook needs no `queryKey`, and a `queryKey` may contain value class instances.

- A value class instance never equals a plain value, even one equal to its serialization: `eq(user.id, 'user:abc')` does not match a `RecordId` that serializes to `'user:abc'`.
- Instances of two classes that serialize to the same value are equal.
- Ordering and range predicates (`gt`, `gte`, `lt`, `lte`) use a value class's serialized value, never `valueOf()`. A primitive sorts before a value class and any other object after it.
- Range predicates compare arrays element by element in the order sorting gives them, whether or not they hold a value class: `[2]` is less than `[10]`. Where sorting would order two plain objects or other reference-compared objects by identity, range predicates treat the arrays as equal from that element on.
- Built-in values keep their own rules: a `Date` compares by its timestamp, binary data by its bytes, and Temporal values by their own rules. Plain objects, arrays, and class instances without `toJSON()` compare by reference. A `Map`, `Set`, `RegExp` or `ArrayBuffer` keeps its built-in rule even in a subclass that defines `toJSON()`, so it is not a value class.
- Treat value class instances as immutable. TanStack DB reads an instance's `toJSON()` once, the first time it compares or hashes it, and keeps using that serialization for the instance's lifetime, even after it leaves every query and row. To change a value, such as a `URL`'s path, create a new instance (`new URL(url)`) instead of mutating one that TanStack DB has already seen.

## Select

Use `select` to specify which fields to include in your results and transform your data. Without `select`, you get the full schema.
Expand Down
2 changes: 1 addition & 1 deletion packages/db-ivm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ export * from './multiset.js'
export * from './operators/index.js'
export * from './types.js'
export { compareKeys, serializeValue } from './utils.js'
export { registerOpaqueHash } from './hashing/hash.js'
export { equalHashValues, registerOpaqueHash } from './hashing/hash.js'
113 changes: 88 additions & 25 deletions packages/db-ivm/src/operators/distinct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,70 @@ import type { KeyValue } from '../types.js'

type GetValue<T> = T extends KeyValue<unknown, infer V> ? V : never

// Keep the emitted row for its eventual retraction. Input representatives can
// differ even when the selected identity is equal.
type DistinctEntry<V> = [
identity: unknown,
row: KeyValue<number, V>,
multiplicity: number,
visible: boolean,
]
// Inputs supporting one selection, bucketed by their key's digest so that a
// payload outside the selection need not be hashable. Equal inputs share a
// count, so a fresh copy retracts its original, while a deep-equal row
// replacement compares apart.
type Support<T> = Map<Hash, Array<[input: T, multiplicity: number]>>

// Digests are unsigned, so keys outside the hashing domain, such as cyclic
// ones, share this bucket and are told apart by equality alone.
const UNHASHABLE_KEY = -1

function keyDigest(key: unknown): Hash {
try {
return hash(key)
} catch {
return UNHASHABLE_KEY
}
}

type DistinctEntry<T> = {
identity: unknown
key: number
// The input whose row was emitted, kept for its eventual retraction. Inputs
// can differ even when the selected identity is equal.
shown: T
multiplicity: number
visible: boolean
support: Support<T>
}

function addSupport<T extends KeyValue<unknown, unknown>>(
support: Support<T>,
input: T,
diff: number,
): void {
// An input of weight zero supports nothing.
if (diff === 0) return
const digest = keyDigest(input[0])
let inputs = support.get(digest)
if (!inputs) support.set(digest, (inputs = []))
const index = inputs.findIndex(([held]) => equalHashValues(held, input))
if (index < 0) {
inputs.push([input, diff])
return
}
const held = inputs[index]!
held[1] += diff
if (held[1] !== 0) return
inputs.splice(index, 1)
if (inputs.length === 0) support.delete(digest)
}

function isSupported<T extends KeyValue<unknown, unknown>>(
support: Support<T>,
input: T,
): boolean {
return (support.get(keyDigest(input[0])) ?? []).some(([held]) =>
equalHashValues(held, input),
)
}

// A visible selection has a positive total, so at least one input remains.
function firstSupported<T>(support: Support<T>): T {
return support.values().next().value![0]![0]
}

/**
* Operator that removes duplicates
Expand All @@ -28,7 +84,7 @@ export class DistinctOperator<
T extends KeyValue<unknown, unknown>,
> extends UnaryOperator<T, KeyValue<number, GetValue<T>>> {
#by: (value: T) => unknown
#values = new Map<Hash, Array<DistinctEntry<GetValue<T>>>>()
#values = new Map<Hash, Array<DistinctEntry<T>>>()
// Hash digests are unsigned. Negative keys give collisions a separate identity.
#nextCollisionKey = 0

Expand All @@ -52,23 +108,23 @@ export class DistinctOperator<
const hashedValue = hash(identity)
let bucket = this.#values.get(hashedValue)
if (!bucket) this.#values.set(hashedValue, (bucket = []))
let entry = bucket.find(([candidate]) =>
equalHashValues(candidate, identity),
let entry = bucket.find((candidate) =>
equalHashValues(candidate.identity, identity),
)
if (!entry) {
entry = [
entry = {
identity,
[
bucket.length ? --this.#nextCollisionKey : hashedValue,
value[1] as GetValue<T>,
],
0,
false,
]
key: bucket.length ? --this.#nextCollisionKey : hashedValue,
shown: value,
multiplicity: 0,
visible: false,
support: new Map(),
}
bucket.push(entry)
}
updatedBuckets.add(hashedValue)
entry[2] += diff
entry.multiplicity += diff
addSupport(entry.support, value, diff)
}
}

Expand All @@ -80,11 +136,18 @@ export class DistinctOperator<
const bucket = this.#values.get(hashedValue)!
let retained = 0
for (const entry of bucket) {
const [, row, multiplicity, wasVisible] = entry
const visible = multiplicity > 0
if (visible !== wasVisible) result.push([row, visible ? 1 : -1])
entry[3] = visible
if (multiplicity !== 0) bucket[retained++] = entry
const { key, shown: previous, support, visible: wasVisible } = entry
const visible = entry.multiplicity > 0
// A selection that stays visible must not outlive the row it shows.
if (visible && !isSupported(support, previous))
entry.shown = firstSupported(support)
const replaced = entry.shown !== previous
if (wasVisible && (!visible || replaced))
result.push([[key, previous[1] as GetValue<T>], -1])
if (visible && (!wasVisible || replaced))
result.push([[key, entry.shown[1] as GetValue<T>], 1])
entry.visible = visible
if (entry.multiplicity !== 0) bucket[retained++] = entry
}
bucket.length = retained
if (retained === 0) this.#values.delete(hashedValue)
Expand Down
11 changes: 10 additions & 1 deletion packages/db-ivm/tests/distinct-calibration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,17 @@ it(`rejects a representative absent from source inputs`, () => {
checkDistinctRepresentatives(
[[[0, { member: 0, variant: 999 }], 1]],
source,
source,
`fabricated representative`,
),
).toThrow(/distinct representative contribution diverged/)
})

it(`rejects a representative no source row still holds`, () => {
expect(() =>
checkDistinctRepresentatives(
[[[0, { member: 0, variant: 0 }], 1]],
[{ member: 0, variant: 1 }],
`retired representative`,
),
).toThrow(/distinct representative contribution diverged/)
})
Loading