From eb7349d93f5335b49eb6539c05dcb9735f83b2b2 Mon Sep 17 00:00:00 2001 From: Isaac Date: Mon, 12 Oct 2026 07:56:12 -0600 Subject: [PATCH 1/3] perf(db): key include rows held in D2 state so the index skips hashing The include graph held routed parents, canonical results and bucket rows as objects. The D2 index partitions values by a leading string or number and hashes a whole value only when two share that prefix, so every one of these objects was hashed in full: 48,008 hashes for one issue-to-creator hydrate. They are now tuples that lead with their key. Consolidation is unchanged, because values that share a key are still compared by hash. BucketRow now matches the tuple shape ARCHITECTURE.md describes. Co-authored-by: Isaac --- .changeset/perf-include-rows-skip-hashing.md | 5 + docs/errors.md | 2 +- .../src/query/live/bucket-facade-adapter.ts | 14 +- .../src/query/live/materialized-pipeline.ts | 69 ++++---- packages/db/tests/facade-retention.probe.ts | 22 +-- .../tests/fixtures/error-site-messages.json | 2 +- .../tests/query/bucket-facade-adapter.test.ts | 154 +++--------------- ...et-facade-rollback-oracle.property.test.ts | 16 +- 8 files changed, 85 insertions(+), 199 deletions(-) create mode 100644 .changeset/perf-include-rows-skip-hashing.md diff --git a/.changeset/perf-include-rows-skip-hashing.md b/.changeset/perf-include-rows-skip-hashing.md new file mode 100644 index 0000000000..6eb3eda227 --- /dev/null +++ b/.changeset/perf-include-rows-skip-hashing.md @@ -0,0 +1,5 @@ +--- +'@tanstack/db': patch +--- + +Live queries with includes hydrate faster. The rows that the include graph keeps in its join and reduce state now lead with their key, so the dataflow index tells them apart by key and hashes a whole row only when two rows share a key. On a 10,000-issue benchmark, an issue-to-creator include hydrates about 30% faster and a two-level include about 33% faster. diff --git a/docs/errors.md b/docs/errors.md index ae48d674fd..3d6df32bcb 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -1673,7 +1673,7 @@ Canonical query row has no positive contributor Development builds show this message, with `${...}` replaced by values: ```text -Query contributors for public key ${serializeValue(left.publicKey)} are not congruent +Query contributors for public key ${serializeValue(publicKey)} are not congruent ``` diff --git a/packages/db/src/query/live/bucket-facade-adapter.ts b/packages/db/src/query/live/bucket-facade-adapter.ts index ec6fc31af5..75e2864ccc 100644 --- a/packages/db/src/query/live/bucket-facade-adapter.ts +++ b/packages/db/src/query/live/bucket-facade-adapter.ts @@ -142,7 +142,7 @@ export class BucketFacadeAdapter { snapshot, publications, [...changes.values()].map( - (change) => change.value.publicKey as string | number, + (change) => change.value[0] as string | number, ), ) for (const change of changes.values()) { @@ -241,7 +241,7 @@ export class BucketFacadeAdapter { const buckets = getOrCreate(this.pending, edgeId, () => new Map()) const rows = getOrCreate(buckets, bucketKey, () => new Map()) - const key = serializeValue(row.publicKey) + const key = serializeValue(row[0]) const change = rows.get(key) ?? { deletes: 0, inserts: 0, @@ -481,7 +481,8 @@ export class BucketFacadeAdapter { change: PendingRow, hasOrderBy: boolean, ): void { - const key = change.value.publicKey as string | number + const [publicKey, value, nextOrder] = change.value + const key = publicKey as string | number if (change.deletes > change.inserts) { sync.write({ type: `delete`, key }) return @@ -490,9 +491,8 @@ export class BucketFacadeAdapter { const present = accepted !== undefined // A key that nets to no change while absent gets no write. if (change.inserts === change.deletes && !present) return - const nextOrder = change.value.order const orderChanged = present && entry.order.get(accepted) !== nextOrder - const row = { ...this.resolve(change.value.value), $key: key } + const row = { ...this.resolve(value), $key: key } if (nextOrder !== undefined) entry.order.set(row, nextOrder) sync.write({ type: present ? `update` : `insert`, value: row }) if (hasOrderBy && orderChanged) sync.collection._markLayoutChange() @@ -500,8 +500,8 @@ export class BucketFacadeAdapter { /** Resolve and validate every public key before opening a sync transaction. */ private prepareChange(entry: FacadeEntry, change: PendingRow): void { - this.resolve(change.value.value) - entry.collection.getKeyFromItem({ $key: change.value.publicKey }) + this.resolve(change.value[1]) + entry.collection.getKeyFromItem({ $key: change.value[0] }) } private resolveValue(value: unknown): unknown { diff --git a/packages/db/src/query/live/materialized-pipeline.ts b/packages/db/src/query/live/materialized-pipeline.ts index 5c27a5bac2..6ecdd60cb7 100644 --- a/packages/db/src/query/live/materialized-pipeline.ts +++ b/packages/db/src/query/live/materialized-pipeline.ts @@ -37,16 +37,16 @@ type IncludeRoute = { parentContext: Record | null } -type CanonicalResult = { - publicKey: unknown - tuple: ResultTuple -} +// Rows held in D2 state lead with their public key: the index partitions +// values by a leading string or number, so distinct keys never need a +// structural hash. +type CanonicalResult = readonly [publicKey: unknown, tuple: ResultTuple] -export type BucketRow = { - publicKey: unknown - value: Record - order: string | undefined -} +export type BucketRow = readonly [ + publicKey: unknown, + value: Record, + order: string | undefined, +] export type BucketFacadeCompilation = { edgeId: string @@ -229,7 +229,7 @@ function canonicalizeByPublicKey( routeKey(tuple[2], tuple[3], valueIdentity), publicKey, ]) - return [relationKey, { publicKey, tuple }] as [string, CanonicalResult] + return [relationKey, [publicKey, tuple]] as [string, CanonicalResult] }), reduce((values: Array<[CanonicalResult, number]>) => { const totalMultiplicity = values.reduce( @@ -261,7 +261,7 @@ function canonicalizeByPublicKey( return [[visible, 1]] }), - map(([relationKey, { publicKey, tuple }]) => [ + map(([relationKey, [publicKey, tuple]]) => [ scope === `root` ? publicKey : relationKey, tuple, ]), @@ -272,10 +272,11 @@ function assertCongruentContributors( left: CanonicalResult, right: CanonicalResult, ): void { + const [publicKey, leftTuple] = left const [leftValue, leftOrder, leftCorrelation, leftContext, leftRouting] = - left.tuple + leftTuple const [rightValue, rightOrder, rightCorrelation, rightContext, rightRouting] = - right.tuple + right[1] if ( leftOrder !== rightOrder || @@ -286,8 +287,8 @@ function assertCongruentContributors( ) { throw new Error( devBuild() && process.env.NODE_ENV !== `production` - ? `Query contributors for public key ${serializeValue(left.publicKey)} are not congruent` - : codedMessage(156, { publicKey: left.publicKey }), + ? `Query contributors for public key ${serializeValue(publicKey)} are not congruent` + : codedMessage(156, { publicKey }), ) } } @@ -330,17 +331,18 @@ function attachInlineInclude( routing.parentContext, valueIdentity, ), - { parentKey, tuple }, - ] as [string, { parentKey: unknown; tuple: ResultTuple }] + [parentKey, tuple], + ] as [string, readonly [parentKey: unknown, tuple: ResultTuple]] }), join(bucketValues, `left`), map(([_bucketKey, [parent, bucketValue]]) => { + const [parentKey, tuple] = parent! const [value, order, correlationKey, parentContext, routing, publicKey] = - parent!.tuple + tuple const edgeRouting = routing?.[include.fieldName] if (edgeRouting?.active !== true) { return [ - parent!.parentKey, + parentKey, [value, order, correlationKey, parentContext, routing, publicKey], ] } @@ -349,7 +351,7 @@ function attachInlineInclude( ? emptyMaterializedValue(include.materialization) : bucketValue.value return [ - parent!.parentKey, + parentKey, [ setNestedValue(value, include.resultPath, materialized), order, @@ -382,7 +384,7 @@ function createBucketRows( rawTuple as ResultTuple return [ routeKey(correlationKey, parentContext, valueIdentity), - { publicKey: publicKey ?? internalKey, value, order }, + [publicKey ?? internalKey, value, order], ] as [string, BucketRow] }), ) @@ -476,22 +478,23 @@ function routeKey( } function compareBucketRows(left: BucketRow, right: BucketRow): number { - if (left.order !== right.order) { - if (left.order === undefined) return 1 - if (right.order === undefined) return -1 - return left.order < right.order ? -1 : 1 + const [leftPublicKey, , leftOrder] = left + const [rightPublicKey, , rightOrder] = right + if (leftOrder !== rightOrder) { + if (leftOrder === undefined) return 1 + if (rightOrder === undefined) return -1 + return leftOrder < rightOrder ? -1 : 1 } if ( - (typeof left.publicKey === `string` || - typeof left.publicKey === `number`) && - (typeof right.publicKey === `string` || typeof right.publicKey === `number`) + (typeof leftPublicKey === `string` || typeof leftPublicKey === `number`) && + (typeof rightPublicKey === `string` || typeof rightPublicKey === `number`) ) { - return compareKeys(left.publicKey, right.publicKey) + return compareKeys(leftPublicKey, rightPublicKey) } - const leftKey = serializeValue(left.publicKey) - const rightKey = serializeValue(right.publicKey) + const leftKey = serializeValue(leftPublicKey) + const rightKey = serializeValue(rightPublicKey) return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0 } @@ -501,8 +504,8 @@ function materializeRows( ): unknown { const scalarField = include.scalarField const values = scalarField - ? rows.map(({ value }) => value[scalarField]) - : rows.map(({ value }) => value) + ? rows.map(([, value]) => value[scalarField]) + : rows.map(([, value]) => value) if (include.materialization === `array`) return values if (include.materialization === `singleton`) return values[0] diff --git a/packages/db/tests/facade-retention.probe.ts b/packages/db/tests/facade-retention.probe.ts index fa45d249b0..05d4daba78 100644 --- a/packages/db/tests/facade-retention.probe.ts +++ b/packages/db/tests/facade-retention.probe.ts @@ -31,21 +31,7 @@ function capture( const value = { id: 1, payload: new ArrayBuffer(1024 * 1024) } const bucketKey = `group` activeBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) - rows.sendData( - new MultiSet([ - [ - [ - bucketKey, - { - publicKey: 1, - value, - order: undefined, - }, - ], - 1, - ], - ]), - ) + rows.sendData(new MultiSet([[[bucketKey, [1, value, undefined]], 1]])) graph.run() const ref: BucketFacadeRef = { [BUCKET_FACADE_REF]: { edgeId: `children`, bucketKey }, @@ -58,11 +44,7 @@ function capture( assert.equal(view.get(1)?.id, 1) const retained = holder === `view` ? view : view.get.bind(view) if (pendingUpdate) { - rows.sendData( - new MultiSet([ - [[bucketKey, { publicKey: 2, value: { id: 2 }, order: undefined }], 1], - ]), - ) + rows.sendData(new MultiSet([[[bucketKey, [2, { id: 2 }, undefined]], 1]])) graph.run() } if (released) adapter.cleanup() diff --git a/packages/db/tests/fixtures/error-site-messages.json b/packages/db/tests/fixtures/error-site-messages.json index c990f1a3e2..dc77ebef04 100644 --- a/packages/db/tests/fixtures/error-site-messages.json +++ b/packages/db/tests/fixtures/error-site-messages.json @@ -451,7 +451,7 @@ }, "156": { "file": "query/live/materialized-pipeline.ts", - "template": "Query contributors for public key ${serializeValue(left.publicKey)} are not congruent", + "template": "Query contributors for public key ${serializeValue(publicKey)} are not congruent", "literals": ["Query contributors for public key ", " are not congruent"] }, "157": { diff --git a/packages/db/tests/query/bucket-facade-adapter.test.ts b/packages/db/tests/query/bucket-facade-adapter.test.ts index 0c72556cd4..5c1564869e 100644 --- a/packages/db/tests/query/bucket-facade-adapter.test.ts +++ b/packages/db/tests/query/bucket-facade-adapter.test.ts @@ -74,16 +74,8 @@ describe(`BucketFacadeAdapter`, () => { const ref: BucketFacadeRef = { [BUCKET_FACADE_REF]: { edgeId: `children`, bucketKey: `group` }, } - const oldRow: BucketRow = { - publicKey: 1, - value: { id: 1, name: `old` }, - order: undefined, - } - const newRow: BucketRow = { - publicKey: 1, - value: { id: 1, name: `new` }, - order: undefined, - } + const oldRow: BucketRow = [1, { id: 1, name: `old` }, undefined] + const newRow: BucketRow = [1, { id: 1, name: `new` }, undefined] const send = (row: BucketRow, weight: number) => rows.sendData(new MultiSet([[[`group`, row], weight]])) try { @@ -143,13 +135,11 @@ describe(`BucketFacadeAdapter`, () => { values.map((value) => [ [ bucketKey, - { - publicKey: value.id, + [ + value.id, value, - order: ordered - ? String(size - value.id).padStart(3, `0`) - : undefined, - }, + ordered ? String(size - value.id).padStart(3, `0`) : undefined, + ], ], 1, ]), @@ -193,15 +183,7 @@ describe(`BucketFacadeAdapter`, () => { expect.soft(visited, `source rows visited`).toBeLessThanOrEqual(size) const inserted = { id: size } rows.sendData( - new MultiSet([ - [ - [ - bucketKey, - { publicKey: inserted.id, value: inserted, order: `999` }, - ], - 1, - ], - ]), + new MultiSet([[[bucketKey, [inserted.id, inserted, `999`]], 1]]), ) graph.run() adapter.flush().publish() @@ -231,8 +213,8 @@ describe(`BucketFacadeAdapter`, () => { activeBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) rows.sendData( new MultiSet([ - [[bucketKey, { publicKey: moving.id, value: moving, order: `0` }], 1], - [[bucketKey, { publicKey: fixed.id, value: fixed, order: `1` }], 1], + [[bucketKey, [moving.id, moving, `0`]], 1], + [[bucketKey, [fixed.id, fixed, `1`]], 1], ]), ) graph.run() @@ -249,8 +231,8 @@ describe(`BucketFacadeAdapter`, () => { rows.sendData( new MultiSet([ - [[bucketKey, { publicKey: moving.id, value: moving, order: `0` }], -1], - [[bucketKey, { publicKey: moving.id, value: moving, order: `2` }], 1], + [[bucketKey, [moving.id, moving, `0`]], -1], + [[bucketKey, [moving.id, moving, `2`]], 1], ]), ) graph.run() @@ -277,11 +259,8 @@ describe(`BucketFacadeAdapter`, () => { activeBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) rows.sendData( new MultiSet([ - [ - [bucketKey, { publicKey: original.id, value: original, order: `0` }], - 1, - ], - [[bucketKey, { publicKey: fixed.id, value: fixed, order: `1` }], 1], + [[bucketKey, [original.id, original, `0`]], 1], + [[bucketKey, [fixed.id, fixed, `1`]], 1], ]), ) graph.run() @@ -336,22 +315,9 @@ describe(`BucketFacadeAdapter`, () => { const added = { id: 2, value: `added` } rows.sendData( new MultiSet([ - [ - [bucketKey, { publicKey: original.id, value: original, order: `0` }], - -1, - ], - [ - [ - bucketKey, - { - publicKey: replacement.id, - value: replacement, - order: `2`, - }, - ], - 1, - ], - [[bucketKey, { publicKey: added.id, value: added, order: `3` }], 1], + [[bucketKey, [original.id, original, `0`]], -1], + [[bucketKey, [replacement.id, replacement, `2`]], 1], + [[bucketKey, [added.id, added, `3`]], 1], ]), ) graph.run() @@ -409,28 +375,8 @@ describe(`BucketFacadeAdapter`, () => { rows.sendData( new MultiSet([ - [ - [ - bucketKey, - { - publicKey: replacement.id, - value: replacement, - order: `2`, - }, - ], - -1, - ], - [ - [ - bucketKey, - { - publicKey: replacement.id, - value: replacement, - order: `0`, - }, - ], - 1, - ], + [[bucketKey, [replacement.id, replacement, `2`]], -1], + [[bucketKey, [replacement.id, replacement, `0`]], 1], ]), ) graph.run() @@ -507,23 +453,10 @@ describe(`BucketFacadeAdapter`, () => { firstActiveBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) secondActiveBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) firstRows.sendData( - new MultiSet([ - [ - [bucketKey, { publicKey: first.id, value: first, order: undefined }], - 1, - ], - ]), + new MultiSet([[[bucketKey, [first.id, first, undefined]], 1]]), ) secondRows.sendData( - new MultiSet([ - [ - [ - bucketKey, - { publicKey: second.id, value: second, order: undefined }, - ], - 1, - ], - ]), + new MultiSet([[[bucketKey, [second.id, second, undefined]], 1]]), ) graph.run() @@ -585,15 +518,7 @@ describe(`BucketFacadeAdapter`, () => { const original = { id: 1, value: `original` } activeBuckets.sendData(new MultiSet([[[bucketKey, true], 1]])) rows.sendData( - new MultiSet([ - [ - [ - bucketKey, - { publicKey: original.id, value: original, order: undefined }, - ], - 1, - ], - ]), + new MultiSet([[[bucketKey, [original.id, original, undefined]], 1]]), ) graph.run() adapter.flush().publish() @@ -640,24 +565,8 @@ describe(`BucketFacadeAdapter`, () => { index.throwBeforeBuild = true rows.sendData( new MultiSet([ - [ - [ - bucketKey, - { publicKey: original.id, value: original, order: undefined }, - ], - -1, - ], - [ - [ - bucketKey, - { - publicKey: replacement.id, - value: replacement, - order: undefined, - }, - ], - 1, - ], + [[bucketKey, [original.id, original, undefined]], -1], + [[bucketKey, [replacement.id, replacement, undefined]], 1], ]), ) graph.run() @@ -671,21 +580,8 @@ describe(`BucketFacadeAdapter`, () => { const final = { id: 1, value: `final` } rows.sendData( new MultiSet([ - [ - [ - bucketKey, - { - publicKey: replacement.id, - value: replacement, - order: undefined, - }, - ], - -1, - ], - [ - [bucketKey, { publicKey: final.id, value: final, order: undefined }], - 1, - ], + [[bucketKey, [replacement.id, replacement, undefined]], -1], + [[bucketKey, [final.id, final, undefined]], 1], ]), ) graph.run() diff --git a/packages/db/tests/query/bucket-facade-rollback-oracle.property.test.ts b/packages/db/tests/query/bucket-facade-rollback-oracle.property.test.ts index a5cd412bc6..8b9b0a00a3 100644 --- a/packages/db/tests/query/bucket-facade-rollback-oracle.property.test.ts +++ b/packages/db/tests/query/bucket-facade-rollback-oracle.property.test.ts @@ -453,11 +453,11 @@ class Driver { if (previous) { this.rows.sendData(new MultiSet([[[op.bucket, previous], -1]])) } - const row: BucketRow = { - publicKey: op.id, - value: { id: op.id, v: op.v }, - order: orderOf(op.rank, op.id), - } + const row: BucketRow = [ + op.id, + { id: op.id, v: op.v }, + orderOf(op.rank, op.id), + ] this.rows.sendData(new MultiSet([[[op.bucket, row], 1]])) sent!.set(op.id, row) } @@ -1451,11 +1451,11 @@ describe(`bucket facade rollback`, () => { const ref = (bucketKey: string) => ({ [BUCKET_FACADE_REF]: { edgeId: `children`, bucketKey }, }) - const row = (publicKey: number, value: object): BucketRow => ({ + const row = (publicKey: number, value: object): BucketRow => [ publicKey, value, - order: undefined, - }) + undefined, + ] const child10 = row(10, { id: 10, v: 1 }) const parent1 = row(1, { id: 1, kids: ref(`c1`) }) From c0ac4b2f69719319684b4c796066f6e40427e872 Mon Sep 17 00:00:00 2001 From: Isaac Date: Mon, 12 Oct 2026 10:19:51 -0600 Subject: [PATCH 2/3] refactor(db): keep the canonical result an object and record the layout rule The canonical reduce is keyed by the public key, so its values always share their leading key and the tuple shape saved no hashing there; it is an object again, with its original error message. Bucket rows and routed parents keep the key-first shape. ARCHITECTURE.md records the rule as a cost rule, the comparator reads tuple fields by index, and the facade adapter destructures bucket rows instead of reading them by position. Co-authored-by: Isaac --- docs/errors.md | 2 +- packages/db/src/query/live/ARCHITECTURE.md | 8 +++++ .../src/query/live/bucket-facade-adapter.ts | 10 +++--- .../src/query/live/materialized-pipeline.ts | 32 +++++++++++-------- .../tests/fixtures/error-site-messages.json | 2 +- 5 files changed, 35 insertions(+), 19 deletions(-) diff --git a/docs/errors.md b/docs/errors.md index 3d6df32bcb..ae48d674fd 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -1673,7 +1673,7 @@ Canonical query row has no positive contributor Development builds show this message, with `${...}` replaced by values: ```text -Query contributors for public key ${serializeValue(publicKey)} are not congruent +Query contributors for public key ${serializeValue(left.publicKey)} are not congruent ``` diff --git a/packages/db/src/query/live/ARCHITECTURE.md b/packages/db/src/query/live/ARCHITECTURE.md index 7561e33172..81342368cc 100644 --- a/packages/db/src/query/live/ARCHITECTURE.md +++ b/packages/db/src/query/live/ARCHITECTURE.md @@ -529,6 +529,14 @@ type BucketValue = readonly [bucketKey: BucketKey, value: Value] type CellValue = readonly [cellId: MaterializationCellId, value: Value] ``` +Physical layout: a value that D2 keeps in join or reduce state under a key +it shares with other values leads with its own string or number key, as the +child of a `BucketRow` and the routed parent of an inline include do. The D2 +index tells apart values with different leading keys without hashing them, +so only values that share a key are hashed. A value of another shape is +still correct, but the index hashes it whole. This is a cost rule, not part +of the relation semantics. + A route move is an ordinary weighted batch: ```text diff --git a/packages/db/src/query/live/bucket-facade-adapter.ts b/packages/db/src/query/live/bucket-facade-adapter.ts index 75e2864ccc..02a60b071f 100644 --- a/packages/db/src/query/live/bucket-facade-adapter.ts +++ b/packages/db/src/query/live/bucket-facade-adapter.ts @@ -142,7 +142,7 @@ export class BucketFacadeAdapter { snapshot, publications, [...changes.values()].map( - (change) => change.value[0] as string | number, + ({ value: [publicKey] }) => publicKey as string | number, ), ) for (const change of changes.values()) { @@ -241,7 +241,8 @@ export class BucketFacadeAdapter { const buckets = getOrCreate(this.pending, edgeId, () => new Map()) const rows = getOrCreate(buckets, bucketKey, () => new Map()) - const key = serializeValue(row[0]) + const [publicKey] = row + const key = serializeValue(publicKey) const change = rows.get(key) ?? { deletes: 0, inserts: 0, @@ -500,8 +501,9 @@ export class BucketFacadeAdapter { /** Resolve and validate every public key before opening a sync transaction. */ private prepareChange(entry: FacadeEntry, change: PendingRow): void { - this.resolve(change.value[1]) - entry.collection.getKeyFromItem({ $key: change.value[0] }) + const [publicKey, value] = change.value + this.resolve(value) + entry.collection.getKeyFromItem({ $key: publicKey }) } private resolveValue(value: unknown): unknown { diff --git a/packages/db/src/query/live/materialized-pipeline.ts b/packages/db/src/query/live/materialized-pipeline.ts index 6ecdd60cb7..dc44f4318e 100644 --- a/packages/db/src/query/live/materialized-pipeline.ts +++ b/packages/db/src/query/live/materialized-pipeline.ts @@ -37,11 +37,15 @@ type IncludeRoute = { parentContext: Record | null } -// Rows held in D2 state lead with their public key: the index partitions -// values by a leading string or number, so distinct keys never need a -// structural hash. -type CanonicalResult = readonly [publicKey: unknown, tuple: ResultTuple] +type CanonicalResult = { + publicKey: unknown + tuple: ResultTuple +} +// A bucket row leads with its public key. The D2 index tells apart values +// with a different leading string or number without hashing them, so rows +// of one bucket are hashed only when they share a key. A key of any other +// type falls back to hashing the whole row, as every row did before. export type BucketRow = readonly [ publicKey: unknown, value: Record, @@ -229,7 +233,7 @@ function canonicalizeByPublicKey( routeKey(tuple[2], tuple[3], valueIdentity), publicKey, ]) - return [relationKey, [publicKey, tuple]] as [string, CanonicalResult] + return [relationKey, { publicKey, tuple }] as [string, CanonicalResult] }), reduce((values: Array<[CanonicalResult, number]>) => { const totalMultiplicity = values.reduce( @@ -261,7 +265,7 @@ function canonicalizeByPublicKey( return [[visible, 1]] }), - map(([relationKey, [publicKey, tuple]]) => [ + map(([relationKey, { publicKey, tuple }]) => [ scope === `root` ? publicKey : relationKey, tuple, ]), @@ -272,11 +276,10 @@ function assertCongruentContributors( left: CanonicalResult, right: CanonicalResult, ): void { - const [publicKey, leftTuple] = left const [leftValue, leftOrder, leftCorrelation, leftContext, leftRouting] = - leftTuple + left.tuple const [rightValue, rightOrder, rightCorrelation, rightContext, rightRouting] = - right[1] + right.tuple if ( leftOrder !== rightOrder || @@ -287,8 +290,8 @@ function assertCongruentContributors( ) { throw new Error( devBuild() && process.env.NODE_ENV !== `production` - ? `Query contributors for public key ${serializeValue(publicKey)} are not congruent` - : codedMessage(156, { publicKey }), + ? `Query contributors for public key ${serializeValue(left.publicKey)} are not congruent` + : codedMessage(156, { publicKey: left.publicKey }), ) } } @@ -478,8 +481,11 @@ function routeKey( } function compareBucketRows(left: BucketRow, right: BucketRow): number { - const [leftPublicKey, , leftOrder] = left - const [rightPublicKey, , rightOrder] = right + // Indexed reads: this comparator runs for every pair a bucket sort compares. + const leftPublicKey = left[0] + const rightPublicKey = right[0] + const leftOrder = left[2] + const rightOrder = right[2] if (leftOrder !== rightOrder) { if (leftOrder === undefined) return 1 if (rightOrder === undefined) return -1 diff --git a/packages/db/tests/fixtures/error-site-messages.json b/packages/db/tests/fixtures/error-site-messages.json index dc77ebef04..c990f1a3e2 100644 --- a/packages/db/tests/fixtures/error-site-messages.json +++ b/packages/db/tests/fixtures/error-site-messages.json @@ -451,7 +451,7 @@ }, "156": { "file": "query/live/materialized-pipeline.ts", - "template": "Query contributors for public key ${serializeValue(publicKey)} are not congruent", + "template": "Query contributors for public key ${serializeValue(left.publicKey)} are not congruent", "literals": ["Query contributors for public key ", " are not congruent"] }, "157": { From 3e632084d30eab3096260212a71d576cd98b8e4a Mon Sep 17 00:00:00 2001 From: Isaac Date: Mon, 12 Oct 2026 11:50:56 -0600 Subject: [PATCH 3/3] docs(db): state the bucket-row cost rule precisely Retractions also hash against their own row, bigint keys are prefixes too, and the ARCHITECTURE rule now names the [publicKey, row, order] child tuple instead of BucketRow, which means the pair there. The comparator destructures again: indexed reads measured the same. Co-authored-by: Isaac --- .changeset/perf-include-rows-skip-hashing.md | 2 +- packages/db/src/query/live/ARCHITECTURE.md | 13 +++++++------ .../db/src/query/live/materialized-pipeline.ts | 14 ++++++-------- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/.changeset/perf-include-rows-skip-hashing.md b/.changeset/perf-include-rows-skip-hashing.md index 6eb3eda227..d5214ac6c4 100644 --- a/.changeset/perf-include-rows-skip-hashing.md +++ b/.changeset/perf-include-rows-skip-hashing.md @@ -2,4 +2,4 @@ '@tanstack/db': patch --- -Live queries with includes hydrate faster. The rows that the include graph keeps in its join and reduce state now lead with their key, so the dataflow index tells them apart by key and hashes a whole row only when two rows share a key. On a 10,000-issue benchmark, an issue-to-creator include hydrates about 30% faster and a two-level include about 33% faster. +Live queries with includes hydrate faster. The rows that the include graph keeps in its join and reduce state now lead with their key, so the dataflow index tells them apart by key and hashes a whole row only to match it against a row with the same key, such as its own retraction. On a 10,000-issue benchmark, an issue-to-creator include hydrates about 30% faster and a two-level include about 33% faster. diff --git a/packages/db/src/query/live/ARCHITECTURE.md b/packages/db/src/query/live/ARCHITECTURE.md index 81342368cc..fa79ecdec9 100644 --- a/packages/db/src/query/live/ARCHITECTURE.md +++ b/packages/db/src/query/live/ARCHITECTURE.md @@ -530,12 +530,13 @@ type CellValue = readonly [cellId: MaterializationCellId, value: Value] ``` Physical layout: a value that D2 keeps in join or reduce state under a key -it shares with other values leads with its own string or number key, as the -child of a `BucketRow` and the routed parent of an inline include do. The D2 -index tells apart values with different leading keys without hashing them, -so only values that share a key are hashed. A value of another shape is -still correct, but the index hashes it whole. This is a cost rule, not part -of the relation semantics. +it shares with other values leads with its own string, number or bigint +key, as the `[publicKey, row, order]` child of a bucket row and the routed +parent of an inline include do. The D2 index tells apart values with +different leading keys without hashing them, so a value is hashed only +against a value with the same leading key, such as its own retraction. A +value of another shape is still correct, but the index hashes it whenever +it shares a key. This is a cost rule, not part of the relation semantics. A route move is an ordinary weighted batch: diff --git a/packages/db/src/query/live/materialized-pipeline.ts b/packages/db/src/query/live/materialized-pipeline.ts index dc44f4318e..455fa391eb 100644 --- a/packages/db/src/query/live/materialized-pipeline.ts +++ b/packages/db/src/query/live/materialized-pipeline.ts @@ -43,9 +43,10 @@ type CanonicalResult = { } // A bucket row leads with its public key. The D2 index tells apart values -// with a different leading string or number without hashing them, so rows -// of one bucket are hashed only when they share a key. A key of any other -// type falls back to hashing the whole row, as every row did before. +// with a different leading string, number or bigint without hashing them, so +// a row of one bucket is hashed only against a row with the same key, +// including its own retraction. A key of any other type has the whole row +// hashed whenever it joins a bucket. export type BucketRow = readonly [ publicKey: unknown, value: Record, @@ -481,11 +482,8 @@ function routeKey( } function compareBucketRows(left: BucketRow, right: BucketRow): number { - // Indexed reads: this comparator runs for every pair a bucket sort compares. - const leftPublicKey = left[0] - const rightPublicKey = right[0] - const leftOrder = left[2] - const rightOrder = right[2] + const [leftPublicKey, , leftOrder] = left + const [rightPublicKey, , rightOrder] = right if (leftOrder !== rightOrder) { if (leftOrder === undefined) return 1 if (rightOrder === undefined) return -1