diff --git a/.changeset/value-class-equality.md b/.changeset/value-class-equality.md new file mode 100644 index 0000000000..8f7642d881 --- /dev/null +++ b/.changeset/value-class-equality.md @@ -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 and Sets (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()`. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index a8e7b6deeb..44a82942a5 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -2283,6 +2283,25 @@ 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 and ArrayBuffer 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. 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. + 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 diff --git a/docs/guides/live-queries.md b/docs/guides/live-queries.md index 391853cba6..c7db357dd0 100644 --- a/docs/guides/live-queries.md +++ b/docs/guides/live-queries.md @@ -884,6 +884,29 @@ 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. +- 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` 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 while they are in a query or a row. + ## Select Use `select` to specify which fields to include in your results and transform your data. Without `select`, you get the full schema. diff --git a/packages/db/package.json b/packages/db/package.json index b495b1603d..ea22fb4995 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -23,7 +23,7 @@ "test": "vitest --run", "test:dist": "vitest run --config vitest.dist.config.ts", "test:facade-retention": "node --expose-gc --import tsx tests/facade-retention.probe.ts", - "test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts", + "test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts tests/query/serialized-value-equality-oracle.property.test.ts", "bench:nested-includes": "vitest bench tests/query/includes-performance.bench.ts --run --coverage.enabled=false --reporter=verbose", "test:indexed-db:package": "pnpm --filter @tanstack/db... build && vitest run --config vitest.indexed-db.package.config.ts", "test:collection-gc:browser": "playwright test --config playwright.collection-gc.config.ts", diff --git a/packages/db/src/query/ir-stable-identity.ts b/packages/db/src/query/ir-stable-identity.ts index 94c2f05dca..df4b0c0671 100644 --- a/packages/db/src/query/ir-stable-identity.ts +++ b/packages/db/src/query/ir-stable-identity.ts @@ -1,6 +1,6 @@ import { isPlainObject } from '../utils/type-guards.js' import { UnhashableQueryIRError } from '../errors.js' -import { normalizeValue } from '../utils/comparison.js' +import { normalizeValue, serializedClassValue } from '../utils/comparison.js' import { isRefProxy, toExpression } from './builder/ref-proxy.js' import { getQueryIR } from './builder/query-ir.js' import { @@ -1036,6 +1036,13 @@ function canonicalizeRuntimeValue( return canonicalizeObject(value, path, seen) } + // A value class hashes by its serialized value. The tag keeps it apart from + // a plain string or record equal to that serialization. + const serialized = serializedClassValue(value) + if (serialized !== undefined) { + return [`toJSON`, serialized] + } + throw new UnhashableQueryIRError(path, `non-plain object value`) } diff --git a/packages/db/src/utils/comparison.ts b/packages/db/src/utils/comparison.ts index e8e2c01b03..85a7f31016 100644 --- a/packages/db/src/utils/comparison.ts +++ b/packages/db/src/utils/comparison.ts @@ -1,6 +1,7 @@ import { durationFields, isTemporal } from '../utils' import { getRuntimeReferenceIdentity } from '../query/runtime-reference-identity' import { codedMessage, devBuild } from '../error-message' +import { isPlainObject } from './type-guards' import type { DurationFields } from '../utils' import type { CompareOptions } from '../query/builder/types' @@ -92,8 +93,17 @@ export const ascComparator = (a: any, b: any, opts: CompareOptions): number => { const bIsObject = typeof b === `object` if (aIsObject || bIsObject) { - // Symbols and objects share the runtime's reference-identity sequence. if (aIsObject && bIsObject) { + // Value classes order by their serialized value, before other objects, + // so equal instances compare equal in sorts and tree indexes. + const aJSON = serializedClassValue(a) + const bJSON = serializedClassValue(b) + if (aJSON !== undefined || bJSON !== undefined) { + if (aJSON === undefined) return 1 + if (bJSON === undefined) return -1 + return aJSON < bJSON ? -1 : aJSON > bJSON ? 1 : 0 + } + // Symbols and objects share the runtime's reference-identity sequence. const aId = getRuntimeReferenceIdentity(a)[2] const bId = getRuntimeReferenceIdentity(b)[2] return aId - bId @@ -253,6 +263,41 @@ function normalizeBinary(value: Uint8Array): string { return key } +/** + * The serialized value of a value class: an instance of a class with a + * `toJSON()` method, such as a record ID or a decimal, that no other rule + * covers. Built-in values (Dates, Temporal values, binary data, Maps and + * Sets), including subclasses that define `toJSON()`, keep their own rules, + * and plain records and arrays are not value classes. Record keys + * in the serialized value are sorted, so key order does not change it. + */ +export function serializedClassValue(value: object): string | undefined { + // Excluded objects keep their own rules, so their `toJSON` is never read: it + // can be an accessor that throws. + if ( + isPlainObject(value) || + Array.isArray(value) || + value instanceof Date || + value instanceof Map || + value instanceof Set || + value instanceof ArrayBuffer || + ArrayBuffer.isView(value) || + isTemporal(value) || + typeof (value as { toJSON?: unknown }).toJSON !== `function` + ) { + return undefined + } + return JSON.stringify(value, (_key, field: unknown) => + isPlainObject(field) + ? Object.fromEntries( + Object.keys(field) + .sort() + .map((key) => [key, field[key]]), + ) + : field, + ) +} + /** * Normalize a value for comparison and Map key usage * Converts values that can't be directly compared or used as Map keys @@ -291,6 +336,13 @@ export function normalizeValue(value: any): any { return normalizeBinary(value) } + // A value class compares by its serialized value, in a namespace no plain + // string or other normalized value occupies. + const serialized = serializedClassValue(value) + if (serialized !== undefined) { + return normalizedKey(`toJSON`, serialized) + } + return value } @@ -332,13 +384,35 @@ export function compareTemporalValues(a: unknown, b: unknown): number { return compare(a, b) } +const VALUE_CLASS_ORDER: CompareOptions = { + direction: `asc`, + nulls: `first`, + stringSort: `lexical`, +} + +function holdsValueClass( + value: unknown, + seen: Set = new Set(), +): boolean { + if (typeof value !== `object` || value === null || seen.has(value)) { + return false + } + seen.add(value) + return Array.isArray(value) + ? value.some((item) => holdsValueClass(item, seen)) + : serializedClassValue(value) !== undefined +} + /** * Order two non-null values, returning -1, 0, or 1. * * Temporal types intentionally throw from `valueOf` to prevent silent * miscomparison via the native relational operators — delegate to - * `compareTemporalValues` for them. For everything else (numbers, strings, - * Dates via `valueOf`, etc.) the native operators do the right thing. + * `compareTemporalValues` for them. A value class, alone or inside an array, + * uses the sort order, which reads its serialized value: equal captures are + * one query, so a range must not depend on `valueOf`. For everything else + * (numbers, strings, Dates via `valueOf`, etc.) the native operators do the + * right thing. * * Callers must handle null/undefined themselves — this helper assumes both * arguments are non-null. @@ -347,6 +421,9 @@ export function compareValues(a: unknown, b: unknown): number { if (isTemporal(a) && isTemporal(b)) { return compareTemporalValues(a, b) } + if (holdsValueClass(a) || holdsValueClass(b)) { + return Math.sign(ascComparator(a, b, VALUE_CLASS_ORDER)) + } return (a as any) < (b as any) ? -1 : (a as any) > (b as any) ? 1 : 0 } diff --git a/packages/db/tests/oracle-config.ts b/packages/db/tests/oracle-config.ts index 438336dfa9..e2bb46feaa 100644 --- a/packages/db/tests/oracle-config.ts +++ b/packages/db/tests/oracle-config.ts @@ -658,6 +658,7 @@ const staticOracleProperties = [ `ir-identity.output-denotation`, `ir-identity.union-output-aliases`, `ir-identity.reference-queries`, + `serialized-value.query-equality`, `query-identity.compiled-output`, `query-identity.equality-partition`, `where-predicate.publication`, diff --git a/packages/db/tests/oracle-replay-manifest.ts b/packages/db/tests/oracle-replay-manifest.ts index b4fa0ef32a..e89ee7d428 100644 --- a/packages/db/tests/oracle-replay-manifest.ts +++ b/packages/db/tests/oracle-replay-manifest.ts @@ -662,6 +662,11 @@ const ownerGroups: ReadonlyArray< `query-identity`, `compiled-output equality-partition`, ], + [ + `db/tests/query/serialized-value-equality-oracle.property.test.ts`, + `serialized-value`, + `query-equality`, + ], [ `trailbase-db-collection/tests/lifecycle-oracle.property.test.ts`, `trailbase`, @@ -1553,6 +1558,7 @@ const replayTestNames = new Map([ `ir-identity.output-denotation`, `ir-identity.union-output-aliases`, `ir-identity.reference-queries`, + `serialized-value.query-equality`, `query.public-container-copy`, `query-identity.compiled-output`, `query-identity.equality-partition`, diff --git a/packages/db/tests/query/ir-stable-identity.test.ts b/packages/db/tests/query/ir-stable-identity.test.ts index 7806cb4d4d..732cc16255 100644 --- a/packages/db/tests/query/ir-stable-identity.test.ts +++ b/packages/db/tests/query/ir-stable-identity.test.ts @@ -5,7 +5,7 @@ // ir-stable-identity-support.ts. import { describe, expect, it, vi } from 'vitest' import { Temporal } from 'temporal-polyfill' -import { CollectionImpl } from '../../src/collection/index.js' +import { CollectionImpl, createCollection } from '../../src/collection/index.js' import { Query, getQueryIR } from '../../src/query/builder/index.js' import { add, @@ -32,7 +32,8 @@ import { sum, upper, } from '../../src/query/builder/functions.js' -import { include } from '../../src/query/index.js' +import { createLiveQueryCollection, include } from '../../src/query/index.js' +import { localOnlyCollectionOptions } from '../../src/local-only.js' import { UnhashableQueryIRError, getLoadSubsetDemandKey, @@ -50,6 +51,7 @@ import { getRuntimeReferenceIdentity, } from '../../src/query/runtime-reference-identity.js' import { createValueIdentity } from '../../src/query/equality-value-identity.js' +import { normalizeValue } from '../../src/utils/comparison.js' import { createAlphaRenamedImplicitJoinQuery, createProfileValueQuery, @@ -1092,3 +1094,184 @@ describe(`stable QueryIR identity smoke test`, () => { ).not.toThrow() }) }) + +// A record ID shaped like the `surrealdb` SDK's `RecordId` (issue #2459). +class RecordId { + readonly table: string + readonly id: string + constructor(table: string, id: string) { + this.table = table + this.id = id + } + toString(): string { + return `${this.table}:${this.id}` + } + toJSON(): string { + return this.toString() + } +} + +describe(`value classes`, () => { + it(`hash by their serialized value`, () => { + const hash = getStableValueHash(new RecordId(`user`, `abc`)) + + expect(hash).toBe(`["toJSON","\\"user:abc\\""]`) + expect(getStableValueHash(new RecordId(`user`, `abc`))).toBe(hash) + expect(getStableValueHash(new RecordId(`user`, `xyz`))).not.toBe(hash) + expect(getStableValueHash(`user:abc`)).not.toBe(hash) + expect(getStableValueHash({ table: `user`, id: `abc` })).not.toBe(hash) + expect( + getStableValueHash([`currentUser`, new RecordId(`user`, `abc`)]), + ).toBe(getStableValueHash([`currentUser`, new RecordId(`user`, `abc`)])) + }) + + it(`hash a serialized record independently of its key order`, () => { + class Point { + readonly order: `xy` | `yx` + constructor(order: `xy` | `yx`) { + this.order = order + } + toJSON() { + return this.order === `xy` ? { x: 1, y: 2 } : { y: 2, x: 1 } + } + } + + expect(getStableValueHash(new Point(`xy`))).toBe( + getStableValueHash(new Point(`yx`)), + ) + }) + + it(`keep the rules of built-in values and classes without toJSON`, () => { + class OpaqueValue { + value = `Tanner` + } + class NoValue { + toJSON() { + return undefined + } + } + + expect(getStableValueHash(new Date(0))).toBe( + `["Date","1970-01-01T00:00:00.000Z"]`, + ) + expect(getStableValueHash(new Uint8Array([1]))).toBe( + `["binary","Uint8Array",[1]]`, + ) + expect(() => getStableValueHash(new OpaqueValue())).toThrow( + UnhashableQueryIRError, + ) + expect(() => getStableValueHash(new NoValue())).toThrow( + UnhashableQueryIRError, + ) + expect(() => + getStableValueHash(Temporal.PlainDate.from(`2026-01-02`)), + ).toThrow(UnhashableQueryIRError) + }) + + it(`keep the built-in rules of Map, Set and ArrayBuffer subclasses with toJSON`, () => { + class IdMap extends Map { + toJSON() { + return `user:abc` + } + } + class IdSet extends Set { + toJSON() { + return `user:abc` + } + } + class IdBuffer extends ArrayBuffer { + toJSON() { + return `user:abc` + } + } + + for (const [instance, base] of [ + [new IdMap(), new Map()], + [new IdSet(), new Set()], + [new IdBuffer(1), new ArrayBuffer(1)], + ] as const) { + // Equality and hashing both follow the base type, not toJSON(). + expect(normalizeValue(instance)).toBe(instance) + expect(getStableValueHash(instance)).toBe(getStableValueHash(base)) + expect(normalizeValue(instance)).not.toBe( + normalizeValue(new RecordId(`user`, `abc`)), + ) + } + }) + + it(`give equal captures one query identity`, () => { + const query = (value: unknown) => + getQueryIR( + new Query() + .from({ user: usersCollection }) + .where(({ user }) => eq(user.id, value as never)), + ) + + expect(getQueryIdentity(query(new RecordId(`user`, `abc`)))).toBe( + getQueryIdentity(query(new RecordId(`user`, `abc`))), + ) + expect(getQueryIdentity(query(new RecordId(`user`, `abc`)))).not.toBe( + getQueryIdentity(query(new RecordId(`user`, `xyz`))), + ) + expect(getQueryIdentity(query(new RecordId(`user`, `abc`)))).not.toBe( + getQueryIdentity(query(`user:abc`)), + ) + }) + + it(`match an equal instance in inArray`, () => { + const id = new PropRef([`row`, `id`]) + const row = { row: { id: new RecordId(`user`, `abc`) } } + const constantList = new Func(`in`, [ + id, + new Value([new RecordId(`user`, `abc`)]), + ]) + const rowList = new Func(`in`, [ + new Value(new RecordId(`user`, `abc`)), + new PropRef([`row`, `ids`]), + ]) + + expect(compileExpression(constantList)(row)).toBe(true) + expect( + compileExpression(rowList)({ + row: { ids: [new RecordId(`user`, `abc`)] }, + }), + ).toBe(true) + expect( + compileExpression(new Func(`in`, [id, new Value([`user:abc`])]))( + row, + ), + ).toBe(false) + }) + + // The reproduction from issue #2459. + it(`reproduces issue 2459: eq matches a distinct equal instance`, async () => { + const users = createCollection( + localOnlyCollectionOptions({ + id: `issue-2459-users`, + getKey: (user: { id: RecordId; name: string }) => user.id.toString(), + initialData: [{ id: new RecordId(`user`, `abc`), name: `A` }], + }), + ) + const ir = (value: RecordId) => + getQueryIR( + new Query() + .from({ user: users }) + .where(({ user }) => eq(user.id, value)), + ) + + expect(() => getStableValueHash(new RecordId(`user`, `abc`))).not.toThrow() + expect(getQueryIdentity(ir(new RecordId(`user`, `abc`)))).toBe( + getQueryIdentity(ir(new RecordId(`user`, `abc`))), + ) + + const live = createLiveQueryCollection((q) => + q + .from({ user: users }) + .where(({ user }) => eq(user.id, new RecordId(`user`, `abc`))), + ) + await live.preload() + expect(live.toArray.map((user) => user.name)).toEqual([`A`]) + await live.cleanup() + await users.cleanup() + }) +}) diff --git a/packages/db/tests/query/serialized-value-equality-oracle.property.test.ts b/packages/db/tests/query/serialized-value-equality-oracle.property.test.ts new file mode 100644 index 0000000000..1caf58efdb --- /dev/null +++ b/packages/db/tests/query/serialized-value-equality-oracle.property.test.ts @@ -0,0 +1,821 @@ +/** + * # Do value classes with `toJSON()` compare by value in queries? + * + * Law and source: a class instance that defines `toJSON()` and is not one of + * the built-in value types (Date, Temporal, binary data) is a value. Query + * equality compares two such instances by their serialized value, so `eq`, + * exact index lookups, live-query `where` clauses and join conditions match a + * distinct instance that serializes to the same value. A plain value equal to + * that serialization stays unequal, and query identity and + * `getStableValueHash` follow the same relation. Authority: issue #2459 and + * the "Value classes" section of `docs/guides/live-queries.md`. + * + * A Map, Set or ArrayBuffer is a built-in value even when a subclass defines + * `toJSON()`: it keeps its built-in rule, comparing by reference, so it never + * equals a value class that serializes alike. Authority: the same section's + * built-in rule, which names these types. + * + * A range predicate uses the documented order of value classes: their + * serialized value, never `valueOf()`. A primitive sorts before a value class + * and any other object after it. Equal captures are one query, so a predicate + * must not depend on anything outside the serialization. Plain records, arrays + * and other excluded objects keep reference semantics without their `toJSON` + * property being read. + * + * Why an example can miss the failure: a probe that is the stored instance + * matches under reference equality too, an index can agree with a scan until + * the instance that represents a group of equal values leaves it, and a join + * can match through one side's index while the other side compares + * references. + * + * Model: `modelEq` compares record references by their table and ID fields. + * It never calls `toJSON()` and imports no query normalization. A text value + * spelled like a record reference is a different kind, and null is UNKNOWN. + * A built-in carrier (a Map, Set or ArrayBuffer subclass whose `toJSON()` + * spells a record reference) compares by reference, and every materialized + * value is a fresh instance, so it equals nothing. + * + * History grammar: up to four source rows and three join rows hold a record + * reference, its text look-alike, a built-in carrier look-alike, or null, over + * two tables and two IDs. The + * source has no index, a BasicIndex, or a BTreeIndex. Up to three synced + * updates follow; a weighted one replaces a row's reference with a distinct + * equal instance, so an index must keep a group when its first instance + * leaves. Every row, update and probe builds a fresh instance, so no match + * can come from reference identity. + * + * Production driver: `currentStateAsChanges({ where })` before and after the + * index is created (an index spy confirms the indexed route), a live-query + * Collection filtered by `eq` against the probe, and an inner join of the + * source with the join rows on their references, read after the initial load + * and after every update. Query identity, demand keys and + * `getStableValueHash` are read for two distinct equal probes. + * + * Refinement check: every read returns exactly the model's keys or pairs, and + * the identities of equal probes are equal, while a record probe's identity + * differs from its text look-alike's and from an unequal record's, including + * inside a nested query key. Each record instance has its own `valueOf()`, so + * a range read that used it disagrees with the model. A built-in carrier spelled like the + * probe never matches it, in a scan, an index, a filter or a join, and sorts + * as its own run. + * + * Known omissions: `inArray`, on-demand and + * persisted sources, exact-output (`select`) identity, which keeps reference + * semantics, and classes whose `toJSON()` throws or returns a non-JSON value. + */ +import { fc } from '@fast-check/vitest' +import { describe, expect, vi } from 'vitest' +import { createCollection } from '../../src/collection/index.js' +import { BasicIndex } from '../../src/indexes/basic-index.js' +import { BTreeIndex } from '../../src/indexes/btree-index.js' +import { Query, getQueryIR } from '../../src/query/builder/index.js' +import { + createLiveQueryCollection, + eq, + gt, + gte, + lt, + lte, +} from '../../src/query/index.js' +import { + getLoadSubsetDemandKey, + getQueryIdentity, + getStableValueHash, +} from '../../src/query/ir-stable-identity.js' +import { Func, PropRef, Value } from '../../src/query/ir.js' +import { DEFAULT_COMPARE_OPTIONS } from '../../src/utils.js' +import { oracleProperty } from '../oracle-config.js' +import { + forwardAssertionJudgment, + recordAssertionJudgment, + recordedAssertionJudgment, +} from '../oracle-assertion-adapter.js' +import { mockSyncCollectionOptions, withOracleCleanup } from '../utils.js' + +const property = `serialized-value.query-equality` + +const reachStates = [ + // A row matched a probe that is a distinct, equal instance. + `distinct-instance-matched`, + // An update replaced a matching reference with a distinct equal instance + // while an index held it. + `indexed-equal-replacement`, + // A join matched references held by two Collections. + `join-matched`, + // An ordered read held two distinct, equal record references. + `ordered-equal-run`, + // A source row held a built-in carrier spelled like a record probe. + `builtin-lookalike-held`, + // A range read compared a distinct record equal to the probe. + `range-equal-record`, + // Identity compared a record probe with an unequal record. + `unequal-record-probe`, + // A plain record or array held a toJSON accessor that must not be read. + `excluded-accessor-held`, +] as const +type ReachState = (typeof reachStates)[number] + +type Table = `user` | `org` +type RefSpec = + | { kind: `record`; table: Table; id: `a` | `b` } + | { kind: `text`; table: Table; id: `a` | `b` } + | { kind: `builtin`; carrier: Carrier; table: Table; id: `a` | `b` } + | { kind: `null` } +type Carrier = `Map` | `Set` | `ArrayBuffer` | `PlainRecord` | `Array` +type UnequalBy = `table` | `id` | `both` +type IndexMode = `none` | `basic` | `btree` +type History = { + rows: Array + joinRows: Array + index: IndexMode + // `sameValue` replaces the row's current value with a distinct, equal + // instance; otherwise the row takes `value`. `row` wraps to the rows. + updates: Array<{ row: number; value: RefSpec; sameValue: boolean }> + probe: Extract + unequalBy: UnequalBy +} + +let nextRank = 0 + +/** A record reference shaped like the `surrealdb` SDK's `RecordId`. */ +class RecordRef { + readonly table: string + readonly id: string + // Differs per instance, so an order that reads valueOf() splits equal values. + readonly rank = nextRank++ + constructor(table: string, id: string) { + this.table = table + this.id = id + } + toString(): string { + return `${this.table}:${this.id}` + } + toJSON(): string { + return this.toString() + } + valueOf(): number { + return this.rank + } + equals(other: unknown): boolean { + return ( + other instanceof RecordRef && + other.table === this.table && + other.id === this.id + ) + } +} + +// Built-in carriers: subclasses of Map, Set and ArrayBuffer whose toJSON() +// spells a record reference, as RecordRef's does. +class RecordMap extends Map { + readonly ref: string + constructor(ref: string) { + super() + this.ref = ref + } + toJSON(): string { + return this.ref + } +} +class RecordSet extends Set { + readonly ref: string + constructor(ref: string) { + super() + this.ref = ref + } + toJSON(): string { + return this.ref + } +} +class RecordBuffer extends ArrayBuffer { + readonly ref: string + constructor(ref: string) { + super(0) + this.ref = ref + } + toJSON(): string { + return this.ref + } +} + +// Excluded objects keep reference semantics, so their toJSON is never read. +function withThrowingToJSON(target: T): T { + return Object.defineProperty(target, `toJSON`, { + get() { + throw new Error(`an excluded object's toJSON was read`) + }, + }) +} + +type Row = { id: string; ref: object | string | null } + +// --------------------------------------------------------------------------- +// Model +// --------------------------------------------------------------------------- + +// `eq` keeps a pair only when TRUE: null is UNKNOWN, a record reference +// equals a record reference with the same table and ID, a text value equals +// the same text, and the two kinds never equal each other. A built-in carrier +// compares by reference and every value here is a fresh instance, so it +// equals nothing. +function modelEq(left: RefSpec, right: RefSpec): boolean { + if (left.kind === `null` || right.kind === `null`) return false + if (left.kind === `builtin` || right.kind === `builtin`) return false + return ( + left.kind === right.kind && + left.table === right.table && + left.id === right.id + ) +} + +type RangeOp = `gt` | `gte` | `lt` | `lte` + +// A record probe's order: text before it, other objects after it, and records +// by their table and ID text. Null is UNKNOWN, so it never matches. +function modelRangeKeys( + rows: ReadonlyMap, + probe: Extract, + op: RangeOp, +) { + const spelled = `${probe.table}:${probe.id}` + const order = (spec: RefSpec): number => { + if (spec.kind === `text`) return -1 + if (spec.kind === `builtin`) return 1 + if (spec.kind === `null`) return 0 + const value = `${spec.table}:${spec.id}` + return value < spelled ? -1 : value > spelled ? 1 : 0 + } + const keep = (result: number) => + op === `gt` + ? result > 0 + : op === `gte` + ? result >= 0 + : op === `lt` + ? result < 0 + : result <= 0 + return [...rows] + .filter(([, spec]) => spec.kind !== `null` && keep(order(spec))) + .map(([key]) => key) + .sort() +} + +function unequalRecord( + probe: Extract, + by: UnequalBy, +): Extract { + const table = probe.table === `user` ? `org` : `user` + const id = probe.id === `a` ? `b` : `a` + return { + kind: `record`, + table: by === `id` ? probe.table : table, + id: by === `table` ? probe.id : id, + } +} + +function modelKeys(rows: ReadonlyMap, probe: RefSpec) { + return [...rows] + .filter(([, value]) => modelEq(value, probe)) + .map(([key]) => key) + .sort() +} + +// Sorting keeps equal values together: each sort class occupies one run. A +// built-in carrier equals only itself, so it is its own class. +function sortClass(spec: RefSpec, key: string): string { + if (spec.kind === `null`) return `null` + if (spec.kind === `builtin`) return `builtin:${key}` + return `${spec.kind}:${spec.table}:${spec.id}` +} + +function expectContiguousRuns( + keys: ReadonlyArray, + rows: ReadonlyMap, + label: string, +): void { + expect([...keys].sort(), `${label}: keys`).toEqual([...rows.keys()].sort()) + const closed = new Set() + let current: string | undefined + for (const key of keys) { + const next = sortClass(rows.get(key)!, key) + if (next === current) continue + expect(closed.has(next), `${label}: ${next} split by ${current}`).toBe( + false, + ) + if (current !== undefined) closed.add(current) + current = next + } +} + +function modelPairs( + rows: ReadonlyMap, + joinRows: ReadonlyMap, +) { + const pairs: Array = [] + for (const [left, value] of rows) + for (const [right, joinValue] of joinRows) + if (modelEq(value, joinValue)) pairs.push(`${left}|${right}`) + return pairs.sort() +} + +// --------------------------------------------------------------------------- +// History grammar +// --------------------------------------------------------------------------- + +const tableArbitrary = fc.constantFrom(`user`, `org`) +const idArbitrary = fc.constantFrom<`a` | `b`>(`a`, `b`) +const probeArbitrary = fc.oneof( + { + weight: 3, + arbitrary: fc.record({ + kind: fc.constant(`record` as const), + table: tableArbitrary, + id: idArbitrary, + }), + }, + fc.record({ + kind: fc.constant(`text` as const), + table: tableArbitrary, + id: idArbitrary, + }), +) +const carrierArbitrary = fc.constantFrom( + `Map`, + `Set`, + `ArrayBuffer`, + `PlainRecord`, + `Array`, +) +const builtinArbitrary = fc.record({ + kind: fc.constant(`builtin` as const), + carrier: carrierArbitrary, + table: tableArbitrary, + id: idArbitrary, +}) +const refArbitrary: fc.Arbitrary = fc.oneof( + { weight: 6, arbitrary: probeArbitrary }, + { weight: 2, arbitrary: builtinArbitrary }, + fc.record({ kind: fc.constant(`null` as const) }), +) +const historyArbitrary: fc.Arbitrary = fc.record({ + rows: fc.array(refArbitrary, { minLength: 1, maxLength: 4 }), + joinRows: fc.array(refArbitrary, { maxLength: 3 }), + index: fc.constantFrom(`none`, `basic`, `btree`), + updates: fc.array( + fc.record({ + row: fc.nat({ max: 3 }), + value: refArbitrary, + sameValue: fc.boolean(), + }), + { maxLength: 3 }, + ), + probe: probeArbitrary, + unequalBy: fc.constantFrom(`table`, `id`, `both`), +}) + +// --------------------------------------------------------------------------- +// Production driver +// --------------------------------------------------------------------------- + +function materializeCarrier(carrier: Carrier, ref: string): object { + switch (carrier) { + case `Map`: + return new RecordMap(ref) + case `Set`: + return new RecordSet(ref) + case `ArrayBuffer`: + return new RecordBuffer(ref) + case `PlainRecord`: + return withThrowingToJSON({ ref }) + case `Array`: + return withThrowingToJSON([ref]) + } +} + +// Every call builds a fresh instance, so equal references are never the same +// object. +function materialize(spec: RefSpec): object | string | null { + switch (spec.kind) { + case `record`: + return new RecordRef(spec.table, spec.id) + case `text`: + return `${spec.table}:${spec.id}` + case `builtin`: + return materializeCarrier(spec.carrier, `${spec.table}:${spec.id}`) + case `null`: + return null + } +} + +function rowKey(index: number) { + return `r${index}` +} + +function joinKey(index: number) { + return `j${index}` +} + +let collectionId = 0 + +async function runHistory( + history: History, + reach: (state: ReachState) => void, +): Promise { + // Later resources read earlier ones, so they are cleaned up first. + const cleanups: Array<() => unknown> = [] + const cleanup = (step: () => unknown) => cleanups.unshift(step) + await withOracleCleanup(async () => { + const run = collectionId++ + const indexType = + history.index === `basic` + ? BasicIndex + : history.index === `btree` + ? BTreeIndex + : undefined + const model = new Map( + history.rows.map((spec, index) => [rowKey(index), spec] as const), + ) + const joinModel = new Map( + history.joinRows.map((spec, index) => [joinKey(index), spec] as const), + ) + const source = createCollection( + mockSyncCollectionOptions({ + id: `serialized-value-source-${run}`, + getKey: (row) => row.id, + initialData: history.rows.map((spec, index) => ({ + id: rowKey(index), + ref: materialize(spec), + })), + autoIndex: `off`, + ...(indexType === undefined ? {} : { defaultIndexType: indexType }), + }), + ) + cleanup(() => source.cleanup()) + const joined = createCollection( + mockSyncCollectionOptions({ + id: `serialized-value-join-${run}`, + getKey: (row) => row.id, + initialData: history.joinRows.map((spec, index) => ({ + id: joinKey(index), + ref: materialize(spec), + })), + autoIndex: `off`, + }), + ) + cleanup(() => joined.cleanup()) + await source.stateWhenReady() + await joined.stateWhenReady() + + const where = new Func(`eq`, [ + new PropRef([`ref`]), + new Value(materialize(history.probe)), + ]) + const scanKeys = () => + source + .currentStateAsChanges({ where })! + .map((change) => String(change.key)) + .sort() + + expect(scanKeys(), `initial scan`).toEqual(modelKeys(model, history.probe)) + + const index = + indexType === undefined ? undefined : source.createIndex((row) => row.ref) + const lookup = index === undefined ? undefined : vi.spyOn(index, `lookup`) + + const filtered = createLiveQueryCollection({ + id: `serialized-value-filter-${run}`, + query: (q) => + q + .from({ item: source }) + .where(({ item }) => eq(item.ref, materialize(history.probe))), + }) + cleanup(() => filtered.cleanup()) + const pairs = createLiveQueryCollection({ + id: `serialized-value-pairs-${run}`, + query: (q) => + q + .from({ item: source }) + .join( + { other: joined }, + ({ item, other }) => eq(item.ref, other.ref), + `inner`, + ) + .select(({ item, other }) => ({ + item: item.id, + other: other.id, + })), + }) + cleanup(() => pairs.cleanup()) + await filtered.preload() + await pairs.preload() + + const recordProbe = + history.probe.kind === `record` ? history.probe : undefined + const rangeOps = { gt, gte, lt, lte } + const ranges = recordProbe + ? (Object.keys(rangeOps) as Array).map((op) => { + const live = createLiveQueryCollection({ + id: `serialized-value-${op}-${run}`, + query: (q) => + q + .from({ item: source }) + .where(({ item }) => + rangeOps[op]( + item.ref as never, + materialize(recordProbe) as never, + ), + ), + }) + cleanup(() => live.cleanup()) + return { op, live } + }) + : [] + for (const range of ranges) await range.live.preload() + + const orderedKeys = () => + source + .currentStateAsChanges({ + orderBy: [ + { + expression: new PropRef([`ref`]), + compareOptions: DEFAULT_COMPARE_OPTIONS, + }, + ], + })! + .map((change) => String(change.key)) + + const check = (checkpoint: string) => { + const expectedKeys = modelKeys(model, history.probe) + const expectedPairs = modelPairs(model, joinModel) + expect(scanKeys(), `${checkpoint}: scan`).toEqual(expectedKeys) + expectContiguousRuns(orderedKeys(), model, `${checkpoint}: ordered`) + const recordClasses = [...model.values()] + .filter((spec) => spec.kind === `record`) + .map((spec) => sortClass(spec, ``)) + if (new Set(recordClasses).size < recordClasses.length) + reach(`ordered-equal-run`) + const probe = history.probe + if ( + probe.kind === `record` && + [...model.values()].some( + (spec) => + spec.kind === `builtin` && + spec.table === probe.table && + spec.id === probe.id, + ) + ) + reach(`builtin-lookalike-held`) + if (lookup !== undefined) { + lookup.mockClear() + expect(scanKeys(), `${checkpoint}: indexed scan`).toEqual(expectedKeys) + expect(lookup, `${checkpoint}: index route`).toHaveBeenCalled() + } + expect( + filtered.toArray.map((row) => row.id).sort(), + `${checkpoint}: live-query where`, + ).toEqual(expectedKeys) + expect( + pairs.toArray.map((row) => `${row.item}|${row.other}`).sort(), + `${checkpoint}: join`, + ).toEqual(expectedPairs) + if (history.probe.kind === `record` && expectedKeys.length > 0) + reach(`distinct-instance-matched`) + if (recordProbe !== undefined) { + for (const { op, live } of ranges) { + expect( + live.toArray.map((row) => row.id).sort(), + `${checkpoint}: ${op}`, + ).toEqual(modelRangeKeys(model, recordProbe, op)) + } + if (expectedKeys.length > 0) reach(`range-equal-record`) + } + if ( + [...model.values()].some( + (spec) => + spec.kind === `builtin` && + (spec.carrier === `PlainRecord` || spec.carrier === `Array`), + ) + ) + reach(`excluded-accessor-held`) + if ( + expectedPairs.some((pair) => { + const [left] = pair.split(`|`) + return model.get(left!)!.kind === `record` + }) + ) + reach(`join-matched`) + } + + check(`initial load`) + + for (const [step, update] of history.updates.entries()) { + const key = rowKey(update.row % history.rows.length) + const previous = model.get(key)! + const value = update.sameValue ? previous : update.value + if ( + index !== undefined && + update.sameValue && + modelEq(previous, history.probe) + ) + reach(`indexed-equal-replacement`) + model.set(key, value) + source.utils.begin() + source.utils.write({ + type: `update`, + value: { id: key, ref: materialize(value) }, + }) + source.utils.commit() + check(`update ${step}`) + } + + // Identity: two distinct, equal probes are one query and one demand, + // and hash alike; a record probe differs from its text look-alike. + const queryFor = (value: unknown) => + getQueryIR( + new Query() + .from({ item: source }) + .where(({ item }) => eq(item.ref, value as never)), + ) + const demandFor = (value: unknown) => + getLoadSubsetDemandKey({ + where: new Func(`eq`, [ + new PropRef([`ref`]), + new Value(value), + ]), + }) + const first = materialize(history.probe) + const second = materialize(history.probe) + expect( + getQueryIdentity(queryFor(first)), + `equal probes: query identity`, + ).toBe(getQueryIdentity(queryFor(second))) + expect(demandFor(first), `equal probes: demand key`).toBe(demandFor(second)) + expect(getStableValueHash(first), `equal probes: value hash`).toBe( + getStableValueHash(second), + ) + if (history.probe.kind === `record`) { + const text = materialize({ ...history.probe, kind: `text` }) + expect( + getQueryIdentity(queryFor(first)), + `record and text: query identity`, + ).not.toBe(getQueryIdentity(queryFor(text))) + expect(getStableValueHash(first), `record and text: value hash`).not.toBe( + getStableValueHash(text), + ) + } + if (recordProbe !== undefined) { + reach(`unequal-record-probe`) + const unequal = materialize(unequalRecord(recordProbe, history.unequalBy)) + const nestedKey = (value: unknown) => + getStableValueHash([`items`, { owners: [value] }], `queryKey`) + expect( + getQueryIdentity(queryFor(first)), + `unequal records: query identity`, + ).not.toBe(getQueryIdentity(queryFor(unequal))) + expect(demandFor(first), `unequal records: demand key`).not.toBe( + demandFor(unequal), + ) + expect(getStableValueHash(first), `unequal records: value hash`).not.toBe( + getStableValueHash(unequal), + ) + expect(nestedKey(first), `equal records: nested query key`).toBe( + nestedKey(second), + ) + expect(nestedKey(first), `unequal records: nested query key`).not.toBe( + nestedKey(unequal), + ) + } + }, cleanups) +} + +describe(`value classes compare by their serialized value`, () => { + oracleProperty({ + id: property, + law: { + statement: `Query equality, exact index lookup, live-query filters and joins match distinct class instances whose toJSON() values are equal, never a plain value equal to that serialization; query identity and getStableValueHash follow the same relation and separate unequal values. Range predicates order a value class by that serialization, never valueOf(). A Map, Set or ArrayBuffer subclass with toJSON() keeps its built-in rule and never equals a value class, and a plain record or array keeps reference semantics without its toJSON property being read.`, + authority: `Issue #2459 and the "Value classes" section of docs/guides/live-queries.md.`, + limits: `One toJSON() class over two tables and two IDs, its text look-alike, empty Map, Set and ArrayBuffer subclass look-alikes, plain records and arrays with a throwing toJSON accessor (never probes), and null; up to four source rows, three join rows and three synced updates; range reads use record probes; no inArray, on-demand or persisted sources, or exact-output identity.`, + }, + owns: [ + 'src/utils/comparison.ts#normalizeValue', + 'src/utils/comparison.ts#serializedClassValue', + 'src/utils/comparison.ts#compareValues', + 'src/query/ir-stable-identity.ts#getStableValueHash', + 'src/indexes/basic-index.ts#BasicIndex.lookup', + 'src/indexes/btree-index.ts#BTreeIndex.lookup', + ], + histories: { + arbitrary: historyArbitrary, + runs: 60, + fixedSeeds: [2459], + states: reachStates, + constructed: [ + { + name: `an indexed group keeps an equal reference after its first instance is replaced`, + enters: [ + `distinct-instance-matched`, + `indexed-equal-replacement`, + `join-matched`, + `ordered-equal-run`, + `range-equal-record`, + `unequal-record-probe`, + ], + build: (generated): History => { + const probe = { + kind: `record` as const, + table: generated.probe.table, + id: generated.probe.id, + } + return { + ...generated, + rows: [probe, probe, ...generated.rows.slice(2)], + joinRows: [probe, ...generated.joinRows.slice(1)], + index: generated.index === `basic` ? `basic` : `btree`, + updates: [ + { row: 0, value: probe, sameValue: true }, + ...generated.updates.slice(0, 2), + ], + probe, + } + }, + }, + { + name: `a built-in carrier spelled like the record probe sits among equal records`, + enters: [ + `builtin-lookalike-held`, + `distinct-instance-matched`, + `join-matched`, + `ordered-equal-run`, + ], + build: (generated): History => { + const probe = { + kind: `record` as const, + table: generated.probe.table, + id: generated.probe.id, + } + const carriers: ReadonlyArray = [ + `Map`, + `Set`, + `ArrayBuffer`, + ] + const lookalike = { + kind: `builtin` as const, + carrier: carriers[generated.rows.length % carriers.length]!, + table: probe.table, + id: probe.id, + } + return { + ...generated, + rows: [probe, lookalike, probe, ...generated.rows.slice(3)], + joinRows: [lookalike, probe, ...generated.joinRows.slice(2)], + probe, + } + }, + }, + { + name: `excluded objects with a toJSON accessor sit among equal records`, + enters: [ + `excluded-accessor-held`, + `distinct-instance-matched`, + `range-equal-record`, + `unequal-record-probe`, + ], + build: (generated): History => { + const probe = { + kind: `record` as const, + table: generated.probe.table, + id: generated.probe.id, + } + const excluded = (carrier: Carrier) => ({ + kind: `builtin` as const, + carrier, + table: probe.table, + id: probe.id, + }) + return { + ...generated, + rows: [ + probe, + excluded(`PlainRecord`), + excluded(`Array`), + ...generated.rows.slice(3), + ], + joinRows: [ + excluded(`PlainRecord`), + probe, + ...generated.joinRows.slice(2), + ], + probe, + } + }, + }, + ], + }, + resolve: (history) => ({ history }), + model: recordedAssertionJudgment, + driver: (plan: { history: History }, observe) => + recordAssertionJudgment(property, plan, observe, () => + runHistory(plan.history, (state) => observe(`reach`, state)), + ), + check: forwardAssertionJudgment, + }) +}) diff --git a/packages/db/tests/query/value-class-comparison.test.ts b/packages/db/tests/query/value-class-comparison.test.ts new file mode 100644 index 0000000000..9cf723cdc9 --- /dev/null +++ b/packages/db/tests/query/value-class-comparison.test.ts @@ -0,0 +1,110 @@ +// Fixed examples for how value classes order and which objects are excluded. +// The law and its generated histories are owned by +// serialized-value-equality-oracle.property.test.ts. +import { describe, expect, it } from 'vitest' +import { createCollection } from '../../src/collection/index.js' +import { BasicIndex } from '../../src/indexes/basic-index.js' +import { BTreeIndex } from '../../src/indexes/btree-index.js' +import { Func, PropRef, Value } from '../../src/query/ir.js' +import { + compareValues, + normalizeValue, + serializedClassValue, +} from '../../src/utils/comparison.js' +import { mockSyncCollectionOptions } from '../utils.js' + +class Bound { + constructor( + readonly json: string, + readonly rank: number, + ) {} + toJSON() { + return this.json + } + valueOf() { + return this.rank + } +} + +const throwing = (target: T): T => + Object.defineProperty(target, `toJSON`, { + get() { + throw new Error(`toJSON was read`) + }, + }) + +describe(`compareValues with value classes`, () => { + it(`orders by the serialized value, not valueOf`, () => { + expect(compareValues(new Bound(`b`, 1), new Bound(`a`, 9))).toBe(1) + expect(compareValues(new Bound(`a`, 9), new Bound(`b`, 1))).toBe(-1) + expect(compareValues(new Bound(`a`, 1), new Bound(`a`, 9))).toBe(0) + }) + + it(`puts primitives before a value class and other objects after it`, () => { + expect(compareValues(new Bound(`a`, -1), 100)).toBe(1) + expect(compareValues(100, new Bound(`a`, 999))).toBe(-1) + expect(compareValues(new Bound(`a`, 999), new Map())).toBe(-1) + expect(compareValues(new Map(), new Bound(`a`, 999))).toBe(1) + }) + + it(`compares arrays that hold value classes by those values`, () => { + expect(compareValues([new Bound(`b`, 1)], [new Bound(`a`, 9)])).toBe(1) + expect(compareValues([new Bound(`a`, 1)], [new Bound(`a`, 9)])).toBe(0) + }) + + it(`leaves values without a value class to the native operators`, () => { + expect(compareValues(2, 10)).toBe(-1) + expect(compareValues(`b`, `a`)).toBe(1) + expect(compareValues(new Date(2), new Date(1))).toBe(1) + expect(compareValues([2], [10])).toBe(1) + }) +}) + +describe(`excluded objects with a throwing toJSON accessor`, () => { + const excluded = (): Array<[string, object]> => [ + [`plain record`, throwing({ a: 1 })], + [`null-prototype record`, throwing(Object.create(null))], + [`array`, throwing([1])], + [`Date`, throwing(new Date(1))], + [`Map`, throwing(new Map())], + [`Set`, throwing(new Set())], + [`ArrayBuffer`, throwing(new ArrayBuffer(1))], + [`typed array`, throwing(new Uint8Array(1))], + ] + + it.each(excluded())(`does not read it on a %s`, (_name, value) => { + expect(serializedClassValue(value)).toBeUndefined() + expect(() => normalizeValue(value)).not.toThrow() + }) + + it.each([ + [`no index`, undefined], + [`BasicIndex`, BasicIndex], + [`BTreeIndex`, BTreeIndex], + ] as const)(`keeps reference equality with %s`, async (_name, indexType) => { + type Row = { id: string; ref: object } + const ref = throwing({ a: 1 }) + const collection = createCollection( + mockSyncCollectionOptions({ + id: `excluded-accessor-${_name}`, + getKey: (row) => row.id, + initialData: [ + { id: `same`, ref }, + { id: `other`, ref: throwing({ a: 1 }) }, + ], + autoIndex: `off`, + ...(indexType === undefined ? {} : { defaultIndexType: indexType }), + }), + ) + await collection.stateWhenReady() + if (indexType !== undefined) collection.createIndex((row) => row.ref) + const where = new Func(`eq`, [ + new PropRef([`ref`]), + new Value(ref), + ]) + expect( + collection.currentStateAsChanges({ where })!.map((change) => change.key), + ).toEqual([`same`]) + await collection.cleanup() + }) +}) diff --git a/packages/react-db/tests/useLiveQuery.test.tsx b/packages/react-db/tests/useLiveQuery.test.tsx index 9066de784c..fcbfd10069 100644 --- a/packages/react-db/tests/useLiveQuery.test.tsx +++ b/packages/react-db/tests/useLiveQuery.test.tsx @@ -3324,6 +3324,129 @@ describe(`Query Collections`, () => { warnSpy.mockRestore() }) + it(`matches and keeps identity for equal value-class captures without queryKey`, async () => { + // A record ID shaped like the `surrealdb` SDK's `RecordId` (#2459). + class RecordId { + readonly table: string + readonly id: string + constructor(table: string, id: string) { + this.table = table + this.id = id + } + toString() { + return `${this.table}:${this.id}` + } + toJSON() { + return this.toString() + } + } + type User = { id: RecordId; name: string } + const users = createCollection( + localOnlyCollectionOptions({ + id: `derived-identity-value-class`, + getKey: (user: User) => user.id.toString(), + initialData: [ + { id: new RecordId(`user`, `abc`), name: `A` }, + { id: new RecordId(`user`, `xyz`), name: `B` }, + ], + }), + ) + + // Each render builds a new, equal instance, as code that reads a + // route parameter does. + const { result, rerender } = renderHook( + ({ id }) => + useLiveQuery({ + query: (q) => + q + .from({ user: users }) + .where(({ user }) => eq(user.id, new RecordId(`user`, id))) + .findOne(), + }), + { initialProps: { id: `abc` } }, + ) + + await waitFor(() => { + expect(result.current.data?.name).toBe(`A`) + }) + const firstCollection = result.current.collection + rerender({ id: `abc` }) + expect(result.current.collection).toBe(firstCollection) + rerender({ id: `xyz` }) + await waitFor(() => { + expect(result.current.data?.name).toBe(`B`) + }) + + // A queryKey may hold a value class too. + const keyed = renderHook(() => + useLiveQuery({ + queryKey: [`user`, new RecordId(`user`, `abc`)], + query: (q) => + q + .from({ user: users }) + .where(({ user }) => eq(user.id, new RecordId(`user`, `abc`))), + }), + ) + await waitFor(() => { + expect(keyed.result.current.data.map((user) => user.name)).toEqual([ + `A`, + ]) + }) + }) + + it(`orders value-class bounds by serialization through rerenders`, async () => { + class Bound { + constructor( + readonly json: string, + readonly rank: number, + ) {} + toJSON() { + return this.json + } + valueOf() { + return this.rank + } + } + type Row = { id: string; bound: Bound } + const rows = createCollection( + localOnlyCollectionOptions({ + id: `derived-identity-value-class-range`, + getKey: (row: Row) => row.id, + initialData: [{ id: `row`, bound: new Bound(`b`, 1) }], + }), + ) + const { result, rerender } = renderHook( + ({ json, rank }) => + useLiveQuery({ + query: (q) => + q + .from({ row: rows }) + .where(({ row }) => gt(row.bound, new Bound(json, rank))), + }), + { initialProps: { json: `a`, rank: 5 } }, + ) + + await waitFor(() => { + expect(result.current.data.map((row) => row.id)).toEqual([`row`]) + }) + const firstCollection = result.current.collection + + // valueOf() changed but the serialization did not: the same query. + rerender({ json: `a`, rank: 0 }) + expect(result.current.collection).toBe(firstCollection) + expect(result.current.data.map((row) => row.id)).toEqual([`row`]) + + // A changed bound is a new query with its own result. + rerender({ json: `c`, rank: 0 }) + await waitFor(() => { + expect(result.current.data).toEqual([]) + }) + rerender({ json: `a`, rank: 9 }) + await waitFor(() => { + expect(result.current.data.map((row) => row.id)).toEqual([`row`]) + }) + }) + it(`uses explicit queryKey for functional query variants`, async () => { const collection = createCollection( mockSyncCollectionOptions({