From a599bfa0cbea3eea39f99d53997d6eebe7ada9dc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:37:04 +0000 Subject: [PATCH 1/6] fix(db): keep join-key demand when an include filters a join side The optimizer pushes a source's own `where` into a subquery over that source. Inside an include, the compiler routed every subquery source by parent, which turned off keyed lazy demand: a filtered joined side loaded every row matching its filter, and a filtered `from` side made the include scan the other side. A subquery that only filters its own source reads no parent value, so it now joins like its Collection and the filter narrows each keyed load. Law: live/ARCHITECTURE.md, Initial demand (lazy-demand growth loads only uncovered keys) and Work (irrelevant rows cause no scans). Reach: includes-work.correlated-links and includes-work.join-targets declare none/link/target join-filter states; one fixed example per state, so every state is reached in every run. RED: on the parent, 6 tests fail (target: 3 delivered/4 examined target rows at baseline vs keyed 2/3; link with one filler: 4 delivered vs 2). GREEN: work-counter oracle and focused on-demand test pass. Mutant: routing the filtered target by parent fails the target state; routing the filtered links by parent fails the link state. Limits: no generated subqueries that read a parent value, filters on both sides at once, or fn.where() filters (these stay parent-routed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LV1skwELp24QLwkaWTd9HB --- .changeset/lazy-join-keeps-key-filter.md | 5 + docs/contributing/oracle-coverage.md | 19 ++ packages/db/src/query/compiler/index.ts | 18 +- packages/db/src/query/compiler/joins.ts | 21 +- .../includes-work-counter-oracle.test.ts | 154 ++++++++----- .../query/includes-work-counter-support.ts | 78 ++++--- .../query/lazy-join-source-where.test.ts | 211 ++++++++++++++++++ 7 files changed, 424 insertions(+), 82 deletions(-) create mode 100644 .changeset/lazy-join-keeps-key-filter.md create mode 100644 packages/db/tests/query/lazy-join-source-where.test.ts diff --git a/.changeset/lazy-join-keeps-key-filter.md b/.changeset/lazy-join-keeps-key-filter.md new file mode 100644 index 0000000000..16357bf4fc --- /dev/null +++ b/.changeset/lazy-join-keeps-key-filter.md @@ -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 `type != 'generated' 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. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index fbea9cd98c..a5beeb3efa 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -1073,6 +1073,25 @@ group fail a pinned 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. + 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 diff --git a/packages/db/src/query/compiler/index.ts b/packages/db/src/query/compiler/index.ts index 150a8c0e20..634138104b 100644 --- a/packages/db/src/query/compiler/index.ts +++ b/packages/db/src/query/compiler/index.ts @@ -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' @@ -1653,6 +1658,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, @@ -1680,7 +1691,7 @@ function processFromClause( sourceWhereClauses, valueIdentity, `from`, - parentKeyStream, + isParentRouted ? parentKeyStream : undefined, ) return { ...result, @@ -1689,8 +1700,7 @@ function processFromClause( sourceAlias: source.alias, include, })) ?? [], - isParentRouted: - source.type === `queryRef` && parentKeyStream !== undefined, + isParentRouted, } } diff --git a/packages/db/src/query/compiler/joins.ts b/packages/db/src/query/compiler/joins.ts index 494ab28604..e44dd72655 100644 --- a/packages/db/src/query/compiler/joins.ts +++ b/packages/db/src/query/compiler/joins.ts @@ -24,6 +24,7 @@ import { collectPropRefs, getFromSources, getPropRefSourceAlias, + getWhereExpression, requireCollectionSource, } from '../ir.js' import { compileExpression } from './evaluators.js' @@ -244,7 +245,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) @@ -455,6 +457,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(rest).every((value) => value === undefined) && + where.every((clause) => + collectPropRefs(getWhereExpression(clause)).every( + (ref) => ref.bindingId === from.bindingId, + ), + ) + ) +} + function getJoinRefAlias(ref: PropRef): string | undefined { return getPropRefSourceAlias(ref) ?? ref.path[0] } diff --git a/packages/db/tests/query/includes-work-counter-oracle.test.ts b/packages/db/tests/query/includes-work-counter-oracle.test.ts index 0219ff873c..485d2b3ef2 100644 --- a/packages/db/tests/query/includes-work-counter-oracle.test.ts +++ b/packages/db/tests/query/includes-work-counter-oracle.test.ts @@ -2,6 +2,7 @@ import { fc, test as fcTest } from '@fast-check/vitest' import { beforeAll, describe, expect, it } from 'vitest' import { oraclePropertyOptions, oracleRuns } from '../oracle-config.js' import { declareOracle } from '../oracle-declaration.js' +import { createOracleReach } from '../oracle-reach.js' import { createCollection } from '../../src/collection/index.js' import { BTreeIndex } from '../../src/indexes/btree-index.js' import { @@ -25,6 +26,7 @@ import { import type { Collection } from '../../src/collection/index.js' import type { LoadSubsetOptions } from '../../src/types.js' import type { + JoinFilter, SourceWork, WorkObservation, } from './includes-work-counter-support.js' @@ -50,9 +52,15 @@ import type { * The input grammar varies an integer filler count from 1 through 24. Zero is * the ablated baseline; negative and fractional counts are invalid fixture * sizes. Joined queries vary unrelated links and join targets separately. - * The join-free query grows every source together. Counts 1, 2, and 3 pin the - * smallest valid boundary, 24 pins the upper bound, and fixed and random - * campaigns sample the range. + * Both joined laws also vary a join filter: none, a `where` on the links + * alone, or a `where` on the joined targets alone. The optimizer pushes each + * filter into its own source, and laws 2 and 3 must still hold: the targets + * stay keyed by the kept links' join values, so a filter narrows the keyed + * load and must not replace it or make the include scan a side + * (live/ARCHITECTURE.md, Initial demand and Work). The reference drops the + * filtered row's link. The join-free query grows every source together. Counts 1, 2, and 3 pin the smallest valid + * boundary, 24 pins the upper bound, and fixed and random campaigns sample the + * range. * * The boundary conditions matter. Collections preload before they receive * B-tree indexes. Filler rows never match a selected route. This suite checks @@ -69,6 +77,21 @@ const joinedBaselineWork: SourceWork = { links: { delivered: 2, examined: 2 }, } +// Each join filter drops one row after a keyed read. A target filter drops +// one of the two named targets: the root and both named targets are +// examined, the root and one target delivered. A link filter drops one of +// the group's two links, so only the kept link's target is named. +const joinedBaselineWorkByFilter: Record = { + none: joinedBaselineWork, + target: { ...joinedBaselineWork, terms: { delivered: 2, examined: 3 } }, + link: { + ...joinedBaselineWork, + terms: { delivered: 2, examined: 2 }, + links: { delivered: 1, examined: 2 }, + }, +} +const joinFilters = Object.keys(joinedBaselineWorkByFilter) as Array + const joinFreeBaselineWork: SourceWork = { terms: { delivered: 1, examined: 1 }, meanings: { delivered: 1, examined: 1 }, @@ -76,47 +99,50 @@ const joinFreeBaselineWork: SourceWork = { links: { delivered: 2, examined: 2 }, } -let joinedBaselineObservation: WorkObservation +const joinedBaselineObservations = new Map() let joinFreeBaselineObservation: WorkObservation -async function expectCorrelatedJoinWorkBound( - fillerCount: number, +// Both joined laws compare a scaled run with the minimal run of the same +// query, under each join filter. +async function expectJoinedWorkBound( + filler: { terms: number; links: number }, + joinFilter: JoinFilter, ): Promise { - const baseline = joinedBaselineObservation + const baseline = joinedBaselineObservations.get(joinFilter)! const scaled = await observeWork({ - filler: { - terms: 0, - meanings: 0, - groups: 0, - links: fillerCount, - }, + filler: { ...filler, meanings: 0, groups: 0 }, joinTargets: true, + joinFilter, }) - expect(baseline.result).toEqual(expectedResult({ joinTargets: true })) + expect(baseline.result).toEqual( + expectedResult({ joinTargets: true, joinFilter }), + ) expect(scaled.result).toEqual(baseline.result) - expect(baseline.sourceWork).toEqual(joinedBaselineWork) - + expect(baseline.sourceWork).toEqual(joinedBaselineWorkByFilter[joinFilter]) expectSourceWorkBound(scaled.sourceWork, baseline.sourceWork) } -async function expectJoinTargetWorkBound(fillerCount: number): Promise { - const baseline = joinedBaselineObservation - const scaled = await observeWork({ - filler: { - terms: fillerCount, - meanings: 0, - groups: 0, - links: 0, - }, - joinTargets: true, - }) +async function expectCorrelatedJoinWorkBound( + fillerCount: number, + joinFilter: JoinFilter = `none`, +): Promise { + await expectJoinedWorkBound({ terms: 0, links: fillerCount }, joinFilter) +} - expect(baseline.result).toEqual(expectedResult({ joinTargets: true })) - expect(scaled.result).toEqual(baseline.result) - expect(baseline.sourceWork).toEqual(joinedBaselineWork) - expectSourceWorkBound(scaled.sourceWork, baseline.sourceWork) +async function expectJoinTargetWorkBound( + fillerCount: number, + joinFilter: JoinFilter = `none`, +): Promise { + await expectJoinedWorkBound({ terms: fillerCount, links: 0 }, joinFilter) } +// The joined campaigns declare every join-filter state and fail unless their +// own generated runs enter each of them. +const joinedCase: fc.Arbitrary = fc.tuple( + fc.integer({ min: 1, max: 24 }), + fc.constantFrom(...joinFilters), +) + async function expectJoinFreeWorkBound(fillerCount: number): Promise { const baseline = joinFreeBaselineObservation const scaled = await observeWork({ @@ -150,22 +176,31 @@ function campaigns(fixedSeed: number, property: string, baseRuns = 6) { describe(`includes deterministic work-counter oracle`, () => { beforeAll(async () => { - const [joinedBaseline, joinFreeBaseline] = await Promise.all([ - observeWork({ filler: noFillers, joinTargets: true }), + const [joinFreeBaseline, ...joinedBaselines] = await Promise.all([ observeWork({ filler: noFillers, joinTargets: false }), + ...joinFilters.map((joinFilter) => + observeWork({ filler: noFillers, joinTargets: true, joinFilter }), + ), ]) - joinedBaselineObservation = joinedBaseline joinFreeBaselineObservation = joinFreeBaseline + joinFilters.forEach((joinFilter, index) => + joinedBaselineObservations.set(joinFilter, joinedBaselines[index]!), + ) }) it.each([1, 2, 3])( `pins the work bound at the small filler boundary (%i)`, - expectCorrelatedJoinWorkBound, + (fillerCount) => expectCorrelatedJoinWorkBound(fillerCount), ) it(`pins the joined-link filler range endpoint`, () => expectCorrelatedJoinWorkBound(24)) - it.each([1, 24])( - `pins join-target growth at filler count %i`, + it.each( + joinFilters.flatMap((joinFilter) => [ + [1, joinFilter] as const, + [24, joinFilter] as const, + ]), + )( + `pins join-target growth at filler count %i (join filter %s)`, expectJoinTargetWorkBound, ) it.each([1, 24])( @@ -173,18 +208,34 @@ describe(`includes deterministic work-counter oracle`, () => { expectJoinFreeWorkBound, ) - for (const campaign of campaigns(1709, `includes-work.correlated-links`)) { - fcTest.prop([fc.integer({ min: 1, max: 24 })], campaign.options)( - `a join preserves correlated source pushdown (${campaign.name})`, - expectCorrelatedJoinWorkBound, - ) - } - - for (const campaign of campaigns(170_900, `includes-work.join-targets`)) { - fcTest.prop([fc.integer({ min: 1, max: 24 })], campaign.options)( - `indexed join-target growth keeps source work flat (${campaign.name})`, - expectJoinTargetWorkBound, - ) + for (const [property, seed, check] of [ + [`includes-work.correlated-links`, 1709, expectCorrelatedJoinWorkBound], + [`includes-work.join-targets`, 170_900, expectJoinTargetWorkBound], + ] as const) { + for (const campaign of campaigns(seed, property)) { + it(`${property} keeps source work flat under each join filter (${campaign.name})`, async () => { + // One fixed example per join filter makes reach independent of the seed. + const fixed = joinFilters.map((joinFilter) => [1, joinFilter] as const) + const reach = createOracleReach( + `${property} (${campaign.name})`, + joinFilters, + { fixedHistories: fixed.length }, + ) + await fc.assert( + fc.asyncProperty(joinedCase, async (testCase) => { + const [fillerCount, joinFilter] = testCase + reach.beginHistory({ fixed: fixed.includes(testCase) }) + reach.reach(joinFilter) + await check(fillerCount, joinFilter) + }), + { + ...campaign.options, + examples: fixed.map((testCase) => [testCase]), + }, + ) + reach.assertReached() + }) + } } for (const campaign of campaigns(17_090, `includes-work.join-free`)) { @@ -1049,12 +1100,11 @@ async function checkWindowedIncludeWork(testCase: WindowCase): Promise { declareOracle({ check: [ checkWindowedIncludeWork, - expectCorrelatedJoinWorkBound, - expectJoinTargetWorkBound, + expectJoinedWorkBound, expectJoinFreeWorkBound, ], model: [windowUnits, modelKids], - grammar: [windowCase], + grammar: [windowCase, joinedCase], }) // Enough runs that each dimension appears at the default multiplier; the diff --git a/packages/db/tests/query/includes-work-counter-support.ts b/packages/db/tests/query/includes-work-counter-support.ts index 7cb30a5172..521f64830f 100644 --- a/packages/db/tests/query/includes-work-counter-support.ts +++ b/packages/db/tests/query/includes-work-counter-support.ts @@ -6,6 +6,7 @@ import { createLiveQueryCollection, eq, materialize, + not, } from '../../src/query/index.js' import type { Collection } from '../../src/collection/index.js' @@ -41,8 +42,18 @@ type FillerCounts = { type WorkScenario = { filler: FillerCounts joinTargets: boolean + joinFilter?: JoinFilter } +// A source-local filter on one side of the target join. The optimizer pushes +// it into that side's source. `link` filters the parent-correlated side and +// `target` the joined side, which stays the join's lazy side either way. +export type JoinFilter = `none` | `link` | `target` + +// Each filter keeps every row except one. +const excludedLinkId = `link-1` +const excludedTargetText = `second target` + type WorkCount = { delivered: number examined: number @@ -227,6 +238,7 @@ export function observeResult( export async function observeWork({ filler, joinTargets, + joinFilter = `none`, }: WorkScenario): Promise { const rows = createFixtureRows(filler) const sources = { @@ -282,21 +294,31 @@ export async function observeWork({ const selectedLinks = q .from({ link: sources.links }) .where(({ link }) => eq(link.groupId, group.id)) + const keptLinks = + joinFilter === `link` + ? selectedLinks.where(({ link }) => + not(eq(link.id, excludedLinkId)), + ) + : selectedLinks + const joinedTargets = keptLinks.innerJoin( + { target: sources.terms }, + ({ link, target }) => eq(link.targetId, target.id), + ) + const keptTargets = + joinFilter === `target` + ? joinedTargets.where(({ target }) => + not(eq(target.text, excludedTargetText)), + ) + : joinedTargets return { id: group.id, links: joinTargets ? materialize( - selectedLinks - .innerJoin( - { target: sources.terms }, - ({ link, target }) => - eq(link.targetId, target.id), - ) - .select(({ link, target }) => ({ - id: link.id, - text: target.text, - })), + keptTargets.select(({ link, target }) => ({ + id: link.id, + text: target.text, + })), ) : materialize( selectedLinks.select(({ link }) => ({ @@ -337,9 +359,28 @@ export async function observeWork({ } } +// The relational reference: an inner join keeps a link only when the link +// passes the link filter and its target exists and passes the target filter. export function expectedResult({ joinTargets, -}: Pick): WorkObservation[`result`] { + joinFilter = `none`, +}: Pick< + WorkScenario, + 'joinTargets' | 'joinFilter' +>): WorkObservation[`result`] { + const links: Array = joinTargets + ? [ + { id: `link-0`, text: `first target` }, + { id: `link-1`, text: `second target` }, + ].filter( + (link) => + !(joinFilter === `link` && link.id === excludedLinkId) && + !(joinFilter === `target` && link.text === excludedTargetText), + ) + : [ + { id: `link-0`, targetId: `term-1` }, + { id: `link-1`, targetId: `term-2` }, + ] return [ { id: `term-0`, @@ -349,20 +390,7 @@ export function expectedResult({ groups: [ { id: `group-0`, - links: [ - joinTargets - ? { id: `link-0`, text: `first target` } - : { id: `link-0`, targetId: `term-1` }, - joinTargets - ? { - id: `link-1`, - text: `second target`, - } - : { - id: `link-1`, - targetId: `term-2`, - }, - ], + links, }, ], }, diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts new file mode 100644 index 0000000000..7d3b3092da --- /dev/null +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -0,0 +1,211 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + createLiveQueryCollection, + eq, + not, + toArray, +} from '../../src/query/index.js' +import { createCollection } from '../../src/collection/index.js' +import { BasicIndex } from '../../src/indexes/basic-index.js' +import { flushPromises } from '../utils.js' +import type { LoadSubsetOptions } from '../../src/types.js' + +type Task = { id: number; title: string } +type TaskTag = { id: number; task_id: number; tag_id: number } +type Tag = { id: number; name: string; type: string } + +const taskRows: Array = [ + { id: 1, title: `one` }, + { id: 2, title: `two` }, +] +const taskTagRows: Array = [ + { id: 100, task_id: 1, tag_id: 7 }, + { id: 101, task_id: 1, tag_id: 8 }, + { id: 102, task_id: 2, tag_id: 9 }, +] +// Tags 10 and 11 are named by no tagging: a keyed load must not ask for them. +const tagRows: Array = [ + { id: 7, name: `seven`, type: `user` }, + { id: 8, name: `eight`, type: `generated` }, + { id: 9, name: `nine`, type: `user` }, + { id: 10, name: `ten`, type: `user` }, + { id: 11, name: `eleven`, type: `user` }, +] + +let sequence = 0 +const cleanups: Array<() => void | Promise> = [] + +function createEagerCollection( + name: string, + rows: Array, +) { + const collection = createCollection({ + id: `lazy-join-where-${name}-${sequence++}`, + getKey: (row) => row.id, + sync: { + sync: ({ begin, write, commit, markReady }) => { + begin() + for (const row of rows) write({ type: `insert`, value: row }) + commit() + markReady() + }, + }, + }) + cleanups.push(() => collection.cleanup()) + return collection +} + +// An on-demand source that serves every loadSubset from its full table, as +// a server would, and records the options each load receives. +function createOnDemandCollection( + name: string, + rows: Array, +) { + const loads: Array = [] + const collection = createCollection({ + id: `lazy-join-where-${name}-${sequence++}`, + getKey: (row) => row.id, + syncMode: `on-demand`, + autoIndex: `eager`, + defaultIndexType: BasicIndex, + sync: { + sync: ({ begin, write, commit, markReady }) => { + markReady() + return { + loadSubset: (options: LoadSubsetOptions) => { + loads.push(options) + begin() + for (const row of rows) { + if (collection.has(row.id)) continue + write({ type: `insert`, value: row }) + } + commit() + return Promise.resolve() + }, + } + }, + }, + }) + cleanups.push(() => collection.cleanup()) + return { collection, loads } +} + +// Lazy demand is the only part of a load that names join keys, so a keyed +// load is one whose predicate mentions `id IN (...)`. +function describeLoad(options: LoadSubsetOptions): string { + return JSON.stringify(options.where) +} + +function hasKeyFilter(options: LoadSubsetOptions, keys: Array) { + const where = describeLoad(options) + return where.includes(`"name":"in"`) && where.includes(JSON.stringify(keys)) +} + +describe(`lazy join source where`, () => { + afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() + }) + + it(`include: a where on the lazy joined side keeps the join-key filter`, async () => { + const tasks = createEagerCollection(`tasks`, taskRows) + const taskTags = createEagerCollection(`task-tags`, taskTagRows) + const { collection: tags, loads } = createOnDemandCollection( + `tags`, + tagRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ task: tasks }).select(({ task }) => ({ + id: task.id, + tags: toArray( + q + .from({ taskTag: taskTags }) + .where(({ taskTag }) => eq(taskTag.task_id, task.id)) + .innerJoin({ tag: tags }, ({ taskTag, tag }) => + eq(taskTag.tag_id, tag.id), + ) + .where(({ tag }) => not(eq(tag.type, `generated`))) + .select(({ tag }) => ({ id: tag.id, name: tag.name })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + expect( + live.toArray + .map((task) => ({ + id: task.id, + tags: [...task.tags].map((tag) => tag.id).sort(), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, tags: [7] }, + { id: 2, tags: [9] }, + ]) + }) + + it(`include: a where on the parent-filtered side keeps the join-key filter`, async () => { + const tasks = createEagerCollection(`tasks`, taskRows) + const taskTags = createEagerCollection(`task-tags`, taskTagRows) + const { collection: tags, loads } = createOnDemandCollection( + `tags`, + tagRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ task: tasks }).select(({ task }) => ({ + id: task.id, + tags: toArray( + q + .from({ taskTag: taskTags }) + .where(({ taskTag }) => eq(taskTag.task_id, task.id)) + .where(({ taskTag }) => not(eq(taskTag.tag_id, 8))) + .innerJoin({ tag: tags }, ({ taskTag, tag }) => + eq(taskTag.tag_id, tag.id), + ) + .select(({ tag }) => ({ id: tag.id, name: tag.name })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 9]), describeLoad(load)).toBe(true) + } + }) + + it(`leftJoin: a where on the lazy joined side keeps the join-key filter`, async () => { + const taskTags = createEagerCollection(`task-tags`, taskTagRows) + const { collection: tags, loads } = createOnDemandCollection( + `tags`, + tagRows, + ) + + const live = createLiveQueryCollection((q) => + q + .from({ taskTag: taskTags }) + .leftJoin({ tag: tags }, ({ taskTag, tag }) => + eq(taskTag.tag_id, tag.id), + ) + .where(({ tag }) => not(eq(tag.type, `generated`))) + .select(({ taskTag, tag }) => ({ id: taskTag.id, tagId: tag.id })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + }) +}) From c1771ca86dd65ffc3491e68692f20e3344392394 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:46:46 +0000 Subject: [PATCH 2/6] test(db): type the work-counter join-filter examples Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LV1skwELp24QLwkaWTd9HB --- packages/db/tests/query/includes-work-counter-oracle.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/db/tests/query/includes-work-counter-oracle.test.ts b/packages/db/tests/query/includes-work-counter-oracle.test.ts index 485d2b3ef2..7fa3850dee 100644 --- a/packages/db/tests/query/includes-work-counter-oracle.test.ts +++ b/packages/db/tests/query/includes-work-counter-oracle.test.ts @@ -215,7 +215,9 @@ describe(`includes deterministic work-counter oracle`, () => { for (const campaign of campaigns(seed, property)) { it(`${property} keeps source work flat under each join filter (${campaign.name})`, async () => { // One fixed example per join filter makes reach independent of the seed. - const fixed = joinFilters.map((joinFilter) => [1, joinFilter] as const) + const fixed = joinFilters.map( + (joinFilter): readonly [number, JoinFilter] => [1, joinFilter], + ) const reach = createOracleReach( `${property} (${campaign.name})`, joinFilters, From 44338babbc1fca6ef9974056053fb764d1201533 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:51:44 +0000 Subject: [PATCH 3/6] test(db): keep a parent-reading joined subquery routed by parent Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LV1skwELp24QLwkaWTd9HB --- docs/contributing/oracle-coverage.md | 7 ++- .../query/lazy-join-source-where.test.ts | 53 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index a5beeb3efa..1c4aa51aa7 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -1090,7 +1090,12 @@ 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. +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 diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts index 7d3b3092da..15e3a6b2b7 100644 --- a/packages/db/tests/query/lazy-join-source-where.test.ts +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -208,4 +208,57 @@ describe(`lazy join source where`, () => { expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) } }) + + // A joined subquery whose filter reads the parent is not a source filter: + // it must stay routed by parent, so each task sees only its own owner's tags. + it(`include: a joined subquery that reads the parent row keeps its parent filter`, async () => { + const tasks = createEagerCollection(`owned-tasks`, [ + { id: 1, owner: `a` }, + { id: 2, owner: `b` }, + ]) + const taskTags = createEagerCollection(`owned-task-tags`, [ + { id: 100, task_id: 1, tag_id: 7 }, + { id: 101, task_id: 1, tag_id: 8 }, + { id: 102, task_id: 2, tag_id: 7 }, + { id: 103, task_id: 2, tag_id: 8 }, + ]) + const tags = createEagerCollection(`owned-tags`, [ + { id: 7, owner: `a` }, + { id: 8, owner: `b` }, + ]) + + const live = createLiveQueryCollection((q) => + q.from({ task: tasks }).select(({ task }) => ({ + id: task.id, + tags: toArray( + q + .from({ taskTag: taskTags }) + .where(({ taskTag }) => eq(taskTag.task_id, task.id)) + .innerJoin( + { + tag: q + .from({ tag: tags }) + .where(({ tag }) => eq(tag.owner, task.owner)), + }, + ({ taskTag, tag }) => eq(taskTag.tag_id, tag.id), + ) + .select(({ tag }) => ({ id: tag.id })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + + expect( + live.toArray + .map((task) => ({ + id: task.id, + tags: [...task.tags].map((tag) => tag.id), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, tags: [7] }, + { id: 2, tags: [8] }, + ]) + }) }) From 416c702efb964d76da1876961fa216b12110dab4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 19:32:39 +0000 Subject: [PATCH 4/6] test(db): use a todo-list example in the lazy join filter tests Rename the focused lazy join tests and the changeset example to todo lists, todos and assignees. The tests check the same loads and rows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LV1skwELp24QLwkaWTd9HB --- .changeset/lazy-join-keeps-key-filter.md | 2 +- .../query/lazy-join-source-where.test.ts | 181 +++++++++--------- 2 files changed, 95 insertions(+), 88 deletions(-) diff --git a/.changeset/lazy-join-keeps-key-filter.md b/.changeset/lazy-join-keeps-key-filter.md index 16357bf4fc..2d42534fea 100644 --- a/.changeset/lazy-join-keeps-key-filter.md +++ b/.changeset/lazy-join-keeps-key-filter.md @@ -2,4 +2,4 @@ '@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 `type != 'generated' 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. +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. diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts index 15e3a6b2b7..ded619a5fa 100644 --- a/packages/db/tests/query/lazy-join-source-where.test.ts +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -10,26 +10,23 @@ import { BasicIndex } from '../../src/indexes/basic-index.js' import { flushPromises } from '../utils.js' import type { LoadSubsetOptions } from '../../src/types.js' -type Task = { id: number; title: string } -type TaskTag = { id: number; task_id: number; tag_id: number } -type Tag = { id: number; name: string; type: string } +type TodoList = { id: number } +type Todo = { id: number; listId: number; assigneeId: number } +type User = { id: number; active: boolean } -const taskRows: Array = [ - { id: 1, title: `one` }, - { id: 2, title: `two` }, +const todoListRows: Array = [{ id: 1 }, { id: 2 }] +const todoRows: Array = [ + { id: 1, listId: 1, assigneeId: 7 }, + { id: 2, listId: 1, assigneeId: 8 }, + { id: 3, listId: 2, assigneeId: 9 }, ] -const taskTagRows: Array = [ - { id: 100, task_id: 1, tag_id: 7 }, - { id: 101, task_id: 1, tag_id: 8 }, - { id: 102, task_id: 2, tag_id: 9 }, -] -// Tags 10 and 11 are named by no tagging: a keyed load must not ask for them. -const tagRows: Array = [ - { id: 7, name: `seven`, type: `user` }, - { id: 8, name: `eight`, type: `generated` }, - { id: 9, name: `nine`, type: `user` }, - { id: 10, name: `ten`, type: `user` }, - { id: 11, name: `eleven`, type: `user` }, +// Users 10 and 11 are assigned no todo: a keyed load must not ask for them. +const userRows: Array = [ + { id: 7, active: true }, + { id: 8, active: false }, + { id: 9, active: true }, + { id: 10, active: true }, + { id: 11, active: true }, ] let sequence = 0 @@ -107,25 +104,28 @@ describe(`lazy join source where`, () => { }) it(`include: a where on the lazy joined side keeps the join-key filter`, async () => { - const tasks = createEagerCollection(`tasks`, taskRows) - const taskTags = createEagerCollection(`task-tags`, taskTagRows) - const { collection: tags, loads } = createOnDemandCollection( - `tags`, - tagRows, + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, ) const live = createLiveQueryCollection((q) => - q.from({ task: tasks }).select(({ task }) => ({ - id: task.id, - tags: toArray( + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( q - .from({ taskTag: taskTags }) - .where(({ taskTag }) => eq(taskTag.task_id, task.id)) - .innerJoin({ tag: tags }, ({ taskTag, tag }) => - eq(taskTag.tag_id, tag.id), + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .innerJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), ) - .where(({ tag }) => not(eq(tag.type, `generated`))) - .select(({ tag }) => ({ id: tag.id, name: tag.name })), + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), ), })), ) @@ -139,37 +139,40 @@ describe(`lazy join source where`, () => { } expect( live.toArray - .map((task) => ({ - id: task.id, - tags: [...task.tags].map((tag) => tag.id).sort(), + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((todo) => todo.assignee).sort(), })) .sort((a, b) => a.id - b.id), ).toEqual([ - { id: 1, tags: [7] }, - { id: 2, tags: [9] }, + { id: 1, assignees: [7] }, + { id: 2, assignees: [9] }, ]) }) it(`include: a where on the parent-filtered side keeps the join-key filter`, async () => { - const tasks = createEagerCollection(`tasks`, taskRows) - const taskTags = createEagerCollection(`task-tags`, taskTagRows) - const { collection: tags, loads } = createOnDemandCollection( - `tags`, - tagRows, + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, ) const live = createLiveQueryCollection((q) => - q.from({ task: tasks }).select(({ task }) => ({ - id: task.id, - tags: toArray( + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( q - .from({ taskTag: taskTags }) - .where(({ taskTag }) => eq(taskTag.task_id, task.id)) - .where(({ taskTag }) => not(eq(taskTag.tag_id, 8))) - .innerJoin({ tag: tags }, ({ taskTag, tag }) => - eq(taskTag.tag_id, tag.id), + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .where(({ todo }) => not(eq(todo.assigneeId, 8))) + .innerJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), ) - .select(({ tag }) => ({ id: tag.id, name: tag.name })), + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), ), })), ) @@ -184,20 +187,23 @@ describe(`lazy join source where`, () => { }) it(`leftJoin: a where on the lazy joined side keeps the join-key filter`, async () => { - const taskTags = createEagerCollection(`task-tags`, taskTagRows) - const { collection: tags, loads } = createOnDemandCollection( - `tags`, - tagRows, + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, ) const live = createLiveQueryCollection((q) => q - .from({ taskTag: taskTags }) - .leftJoin({ tag: tags }, ({ taskTag, tag }) => - eq(taskTag.tag_id, tag.id), + .from({ todo: todos }) + .leftJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), ) - .where(({ tag }) => not(eq(tag.type, `generated`))) - .select(({ taskTag, tag }) => ({ id: taskTag.id, tagId: tag.id })), + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), ) cleanups.push(() => live.cleanup()) await live.preload() @@ -210,39 +216,40 @@ describe(`lazy join source where`, () => { }) // A joined subquery whose filter reads the parent is not a source filter: - // it must stay routed by parent, so each task sees only its own owner's tags. + // it must stay routed by parent, so each list sees only its own team's + // assignees. it(`include: a joined subquery that reads the parent row keeps its parent filter`, async () => { - const tasks = createEagerCollection(`owned-tasks`, [ - { id: 1, owner: `a` }, - { id: 2, owner: `b` }, + const todoLists = createEagerCollection(`team-todo-lists`, [ + { id: 1, team: `a` }, + { id: 2, team: `b` }, ]) - const taskTags = createEagerCollection(`owned-task-tags`, [ - { id: 100, task_id: 1, tag_id: 7 }, - { id: 101, task_id: 1, tag_id: 8 }, - { id: 102, task_id: 2, tag_id: 7 }, - { id: 103, task_id: 2, tag_id: 8 }, + const todos = createEagerCollection(`team-todos`, [ + { id: 1, listId: 1, assigneeId: 7 }, + { id: 2, listId: 1, assigneeId: 8 }, + { id: 3, listId: 2, assigneeId: 7 }, + { id: 4, listId: 2, assigneeId: 8 }, ]) - const tags = createEagerCollection(`owned-tags`, [ - { id: 7, owner: `a` }, - { id: 8, owner: `b` }, + const users = createEagerCollection(`team-users`, [ + { id: 7, team: `a` }, + { id: 8, team: `b` }, ]) const live = createLiveQueryCollection((q) => - q.from({ task: tasks }).select(({ task }) => ({ - id: task.id, - tags: toArray( + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( q - .from({ taskTag: taskTags }) - .where(({ taskTag }) => eq(taskTag.task_id, task.id)) + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) .innerJoin( { - tag: q - .from({ tag: tags }) - .where(({ tag }) => eq(tag.owner, task.owner)), + assignee: q + .from({ assignee: users }) + .where(({ assignee }) => eq(assignee.team, list.team)), }, - ({ taskTag, tag }) => eq(taskTag.tag_id, tag.id), + ({ todo, assignee }) => eq(todo.assigneeId, assignee.id), ) - .select(({ tag }) => ({ id: tag.id })), + .select(({ assignee }) => ({ id: assignee.id })), ), })), ) @@ -251,14 +258,14 @@ describe(`lazy join source where`, () => { expect( live.toArray - .map((task) => ({ - id: task.id, - tags: [...task.tags].map((tag) => tag.id), + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((assignee) => assignee.id), })) .sort((a, b) => a.id - b.id), ).toEqual([ - { id: 1, tags: [7] }, - { id: 2, tags: [8] }, + { id: 1, assignees: [7] }, + { id: 2, assignees: [8] }, ]) }) }) From 541ece412e5bf97bb602040c22a1cefd6626d29e Mon Sep 17 00:00:00 2001 From: Ben Guericke Date: Tue, 17 Nov 2026 09:50:58 -0700 Subject: [PATCH 5/6] fix(db): keep the inner binding on a where pushed into a subquery A where pushed into an existing subquery lost its binding ID, so isSourceFilter could not see it as a filter on the subquery's own source and the include routed the join by parent, dropping keyed lazy demand. Co-Authored-By: Claude Opus 5.5 --- packages/db/src/query/optimizer.ts | 28 +++++++---- .../query/lazy-join-source-where.test.ts | 48 +++++++++++++++++++ 2 files changed, 66 insertions(+), 10 deletions(-) diff --git a/packages/db/src/query/optimizer.ts b/packages/db/src/query/optimizer.ts index d214a737e8..950a694459 100644 --- a/packages/db/src/query/optimizer.ts +++ b/packages/db/src/query/optimizer.ts @@ -1049,8 +1049,8 @@ function remapWhereForSubquery( whereClause: BasicExpression, outerAlias: string, ): BasicExpression | 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) { @@ -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) { diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts index ded619a5fa..b86c725086 100644 --- a/packages/db/tests/query/lazy-join-source-where.test.ts +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -150,6 +150,54 @@ describe(`lazy join source where`, () => { ]) }) + it(`include: a where pushed into a joined subquery keeps the join-key filter`, async () => { + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( + q + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .innerJoin( + { assignee: q.from({ user: users }) }, + ({ todo, assignee }) => eq(todo.assigneeId, assignee.id), + ) + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + expect( + live.toArray + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((todo) => todo.assignee).sort(), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, assignees: [7] }, + { id: 2, assignees: [9] }, + ]) + }) + it(`include: a where on the parent-filtered side keeps the join-key filter`, async () => { const todoLists = createEagerCollection(`todo-lists`, todoListRows) const todos = createEagerCollection(`todos`, todoRows) From 4d9e571cbc9a4b3a22ff8f20e740f45df96f707e Mon Sep 17 00:00:00 2001 From: Ben Guericke Date: Tue, 17 Nov 2026 09:51:07 -0700 Subject: [PATCH 6/6] test(db): match the join-key filter by its id ref and keys Co-Authored-By: Claude Opus 5.5 --- .../query/lazy-join-source-where.test.ts | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts index b86c725086..1f0ecc595f 100644 --- a/packages/db/tests/query/lazy-join-source-where.test.ts +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -88,14 +88,34 @@ function createOnDemandCollection( } // Lazy demand is the only part of a load that names join keys, so a keyed -// load is one whose predicate mentions `id IN (...)`. +// load is one whose predicate holds `id IN (...)`. function describeLoad(options: LoadSubsetOptions): string { return JSON.stringify(options.where) } +type LoadPredicate = NonNullable + +function sortedKeys(keys: Array): string { + return JSON.stringify([...keys].sort()) +} + function hasKeyFilter(options: LoadSubsetOptions, keys: Array) { - const where = describeLoad(options) - return where.includes(`"name":"in"`) && where.includes(JSON.stringify(keys)) + const isKeyFilter = (expression: LoadPredicate): boolean => { + if (expression.type !== `func`) return false + if (expression.name === `and`) { + return expression.args.some((arg) => isKeyFilter(arg as LoadPredicate)) + } + const [ref, values] = expression.args + return ( + expression.name === `in` && + ref?.type === `ref` && + JSON.stringify(ref.path) === JSON.stringify([`id`]) && + values?.type === `val` && + Array.isArray(values.value) && + sortedKeys(values.value) === sortedKeys(keys) + ) + } + return options.where !== undefined && isKeyFilter(options.where) } describe(`lazy join source where`, () => {