Skip to content
Open
5 changes: 5 additions & 0 deletions .changeset/lazy-join-keeps-key-filter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': patch
---

Keep loading the lazy side of a join inside an include by its join keys when the query also filters one side with `where`. The filter now narrows each keyed `loadSubset` request (for example `active = true AND id IN (7, 8, 9)`) instead of replacing it, so an on-demand Collection no longer receives a request for every row that matches the filter, or for every row when the filter is on the other side.
24 changes: 24 additions & 0 deletions docs/contributing/oracle-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -1285,6 +1285,30 @@ fixed collapse and the detail page; a child that takes over `setWindow` fails
the rows law. Focused tests require a window inside a `from` or joined subquery
not to answer `setWindow`.

Its two joined work laws (unmatched links, and indexed join targets) also
generate a join filter: none, a `where` on the links alone, or a `where` on the
joined targets alone. The optimizer pushes each filter into a subquery over its
own source, and the include must still filter the links by parent and load the
targets by the kept links' join values, so the filter narrows each keyed read
(live/ARCHITECTURE.md, Initial demand and Work). Both campaigns declare the
three filter states with `createOracleReach` and run one fixed example per
state; each state is reached by at least one fixed history in every run. On
main the include parent-routed both filtered sources and scanned the target
Collection: the target filter delivered 3 and examined 4 target rows at
baseline where the keyed bound is 2 and 3, and one unmatched link with a link
filter delivered 4 target rows where the bound is 2. Mutants that route the
filtered target, or the filtered links, by parent fail the target and link
states respectively. A focused test in
`packages/db/tests/query/lazy-join-source-where.test.ts` replays the on-demand
report: each `loadSubset` the lazy side receives names the join keys. The
owner does not generate subqueries that read a parent value, filters on both
sides at once, or `fn.where()` filters, which remain parent-routed. Only a
focused test in the same file shows that a joined subquery whose `where` reads
the parent stays parent-routed: a mutant that drops that check returns empty
child arrays there, and the existing include suites (637 tests) pass it. A
generated parent-reading subquery dimension in the cross-formulation owner
would close that gap.

Recorded limit (#2151): while an index-backed parent top-K refills within one
graph run (a held row moved out, a tie group loaded at the window edge, a
forward window move), it can briefly hold a row outside the window it shows once
Expand Down
18 changes: 14 additions & 4 deletions packages/db/src/query/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ import {
isCaseWhenConditionTrue,
toBooleanPredicate,
} from './evaluators.js'
import { processJoins, processSource, registerLazyDemandPlan } from './joins.js'
import {
isSourceFilter,
processJoins,
processSource,
registerLazyDemandPlan,
} from './joins.js'
import { findAggregate } from './find-aggregate.js'
import { getLazyLoadTargets } from './lazy-targets.js'
import { processOrderBy } from './order-by.js'
Expand Down Expand Up @@ -1652,6 +1657,12 @@ function processFromClause(
}

const compileSource = (source: CollectionSourceRef | QueryRef) => {
// A pushed-down source filter reads no parent value: it is filtered by the
// parent like its Collection, so keyed lazy demand still applies.
const isParentRouted =
parentKeyStream !== undefined &&
source.type === `queryRef` &&
!isSourceFilter(source)
const result = processSource(
source,
allInputs,
Expand All @@ -1678,7 +1689,7 @@ function processFromClause(
sourceWhereClauses,
valueIdentity,
`from`,
parentKeyStream,
isParentRouted ? parentKeyStream : undefined,
)
return {
...result,
Expand All @@ -1687,8 +1698,7 @@ function processFromClause(
sourceAlias: source.alias,
include,
})) ?? [],
isParentRouted:
source.type === `queryRef` && parentKeyStream !== undefined,
isParentRouted,
}
}

Expand Down
21 changes: 20 additions & 1 deletion packages/db/src/query/compiler/joins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
collectPropRefs,
getFromSources,
getPropRefSourceAlias,
getWhereExpression,
requireCollectionSource,
} from '../ir.js'
import { compileExpression } from './evaluators.js'
Expand Down Expand Up @@ -250,7 +251,8 @@ export function processJoins(
)
const routeJoinedSource =
parentKeyStream !== undefined &&
(joinClause.from.type === `queryRef` ||
((joinClause.from.type === `queryRef` &&
!isSourceFilter(joinClause.from)) ||
((joinClause.type === `right` || joinClause.type === `full`) &&
!mainSourceIsParentFiltered) ||
joinedExpressionUsesParent)
Expand Down Expand Up @@ -475,6 +477,23 @@ export function processJoins(

type JoinRefRole = `joined` | `main` | `ancestor` | `unknown`

// The optimizer pushes a source's own `where` into a subquery over that
// source. The subquery reads no parent value, so an include need not route it
// by parent: it joins like the source and keeps keyed lazy demand, and the
// filter narrows each keyed load.
export function isSourceFilter({ query }: QueryRef): boolean {
const { from, where = [], ...rest } = query
return (
(from.type === `collectionRef` || from.type === `descriptorRef`) &&
Object.values<unknown>(rest).every((value) => value === undefined) &&
where.every((clause) =>
collectPropRefs(getWhereExpression(clause)).every(
(ref) => ref.bindingId === from.bindingId,
),
)
)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function getJoinRefAlias(ref: PropRef): string | undefined {
return getPropRefSourceAlias(ref) ?? ref.path[0]
}
Expand Down
28 changes: 18 additions & 10 deletions packages/db/src/query/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1049,8 +1049,8 @@ function remapWhereForSubquery(
whereClause: BasicExpression<boolean>,
outerAlias: string,
): BasicExpression<boolean> | undefined {
const firstFromAlias = getFirstFromAlias(subquery)
if (firstFromAlias === undefined) return undefined
const firstFrom = getFromSources(subquery.from)[0]
if (firstFrom === undefined) return undefined

const remapExpression = (expression: BasicExpression): BasicExpression => {
if (expression instanceof PropRef) {
Expand All @@ -1060,14 +1060,22 @@ function remapWhereForSubquery(
const projected = field ? subquery.select?.[field] : undefined
const hasNamespacedResult =
subquery.join !== undefined || subquery.from.type === `unionFrom`
const innerPath =
projected instanceof PropRef
? [...projected.path, ...expression.path.slice(2)]
: hasNamespacedResult
? expression.path.slice(1)
: [firstFromAlias, ...expression.path.slice(1)]

return new PropRef(innerPath)

if (projected instanceof PropRef) {
return new PropRef(
[...projected.path, ...expression.path.slice(2)],
undefined,
projected.bindingId,
)
}
if (hasNamespacedResult) {
return new PropRef(expression.path.slice(1))
}
return new PropRef(
[firstFrom.alias, ...expression.path.slice(1)],
undefined,
firstFrom.bindingId,
)
}

if (expression instanceof Func) {
Expand Down
Loading