Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/perf-include-rows-skip-hashing.md
Original file line number Diff line number Diff line change
@@ -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 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.
9 changes: 9 additions & 0 deletions packages/db/src/query/live/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,15 @@ type BucketValue<Value> = readonly [bucketKey: BucketKey, value: Value]
type CellValue<Value> = 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, 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:

```text
Expand Down
16 changes: 9 additions & 7 deletions packages/db/src/query/live/bucket-facade-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class BucketFacadeAdapter {
snapshot,
publications,
[...changes.values()].map(
(change) => change.value.publicKey as string | number,
({ value: [publicKey] }) => publicKey as string | number,
),
)
for (const change of changes.values()) {
Expand Down Expand Up @@ -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.publicKey)
const [publicKey] = row
const key = serializeValue(publicKey)
const change = rows.get(key) ?? {
deletes: 0,
inserts: 0,
Expand Down Expand Up @@ -481,7 +482,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
Expand All @@ -490,18 +492,18 @@ 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()
}

/** 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 })
const [publicKey, value] = change.value
this.resolve(value)
entry.collection.getKeyFromItem({ $key: publicKey })
}

private resolveValue(value: unknown): unknown {
Expand Down
53 changes: 30 additions & 23 deletions packages/db/src/query/live/materialized-pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,16 @@ type CanonicalResult = {
tuple: ResultTuple
}

export type BucketRow = {
publicKey: unknown
value: Record<PropertyKey, any>
order: string | undefined
}
// A bucket row leads with its public key. The D2 index tells apart values
// 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<PropertyKey, any>,
order: string | undefined,
]

export type BucketFacadeCompilation = {
edgeId: string
Expand Down Expand Up @@ -330,17 +335,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],
]
}
Expand All @@ -349,7 +355,7 @@ function attachInlineInclude(
? emptyMaterializedValue(include.materialization)
: bucketValue.value
return [
parent!.parentKey,
parentKey,
[
setNestedValue(value, include.resultPath, materialized),
order,
Expand Down Expand Up @@ -382,7 +388,7 @@ function createBucketRows(
rawTuple as ResultTuple
return [
routeKey(correlationKey, parentContext, valueIdentity),
{ publicKey: publicKey ?? internalKey, value, order },
[publicKey ?? internalKey, value, order],
] as [string, BucketRow]
}),
)
Expand Down Expand Up @@ -476,22 +482,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
}

Expand All @@ -501,8 +508,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]
Expand Down
22 changes: 2 additions & 20 deletions packages/db/tests/facade-retention.probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand All @@ -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()
Expand Down
Loading
Loading