Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import {
3 BasicIndex,
4 createCollection,
5 createLiveQueryCollection,
6 eq,
7} from '@tanstack/db'
8import { describe, expect, it } from 'vitest'
9import { evaluateReferenceExpression } from '../../db/tests/reference-expression'
10import { queryCollectionOptions } from '../src/query'
11import type { Collection } from '@tanstack/db'
12
13/**
14 * The live-query architecture's nested propagation and initial-demand laws
15 * require a preloaded Query-backed tree to expose every reachable descendant.
16 *
17 * A deterministic four-level tree supplies the value model: traverse parent
18 * links from the selected roots to compute reachable rows and child collection
19 * counts. Source Collection change counters record rows delivered before and
20 * after public traversal. A bounded root-count matrix varies scale.
21 *
22 * The oracle checks both complete nested values and work bounds. Correct rows
23 * alone would allow duplicate source delivery; low counters alone could hide
24 * missing descendants. The eager matrix makes every source row reachable. A
25 * separate on-demand witness adds disconnected branches and checks acquisition
26 * attempts, Query provider calls, delivered rows, and the public tree at
27 * preload. Its controlled provider evaluates the requested predicate against
28 * its rows; the oracle does not measure provider scans, internal index
29 * traversal, facade allocations, or elapsed time.
30 */
31
32let nextCollectionId = 0
33
34type RootRow = { id: string; value: string }
35type BranchRow = { id: string; parentId: string; value: string }
36type TwigRow = { id: string; parentId: string; value: string }
37type LeafRow = { id: string; parentId: string; value: string }
38
39type TreeCounts = {
40 roots: number
41 branches: number
42 twigs: number
43 leaves: number
44}
45
46type ChildLevel = Exclude<keyof TreeCounts, 'roots'>
47
48type TreeEntry = {
49 level: keyof TreeCounts
50 parentId: string | null
51 id: string
52 value: string
53}
54
55type NodeRow = {
56 id: string
57 value: string
58 children?: NodeCollection
59}
60
61type NodeCollection = Pick<
62 Collection<NodeRow, string | number>,
63 'cleanup' | 'preload' | 'size' | 'toArray'
64>
65
66type NestedTreeShape = {
67 entries: Array<TreeEntry>
68 reachableTreeRows: number
69 sourceRowsDeliveredAtPreload: TreeCounts
70 sourceRowsDeliveredAfterTraversal: TreeCounts
71 providerCallsAtPreload: TreeCounts
72 providerCallsAfterTraversal: TreeCounts
73 acquisitionAttemptsAtPreload: TreeCounts
74 acquisitionAttemptsAfterTraversal: TreeCounts
75 reachableChildCollections: Record<ChildLevel, number>
76 reachableChildRows: Record<ChildLevel, number>
77}
78
79const branchesPerRoot = 2
80const twigsPerBranch = 5
81const leavesPerTwig = 10
82
83function createNestedTreeRows(rootCount: number, irrelevantBranchCount = 0) {
84 const roots: Array<RootRow> = []
85 const branches: Array<BranchRow> = []
86 const twigs: Array<TwigRow> = []
87 const leaves: Array<LeafRow> = []
88
89 for (let rootIndex = 0; rootIndex < rootCount; rootIndex++) {
90 const rootId = `root-${rootIndex}`
91 roots.push({ id: rootId, value: rootId })
92
93 for (let branchIndex = 0; branchIndex < branchesPerRoot; branchIndex++) {
94 const branchId = `branch-${rootIndex}-${branchIndex}`
95 branches.push({ id: branchId, parentId: rootId, value: branchId })
96
97 for (let twigIndex = 0; twigIndex < twigsPerBranch; twigIndex++) {
98 const twigId = `twig-${rootIndex}-${branchIndex}-${twigIndex}`
99 twigs.push({ id: twigId, parentId: branchId, value: twigId })
100
101 for (let leafIndex = 0; leafIndex < leavesPerTwig; leafIndex++) {
102 const leafId = `leaf-${rootIndex}-${branchIndex}-${twigIndex}-${leafIndex}`
103 leaves.push({ id: leafId, parentId: twigId, value: leafId })
104 }
105 }
106 }
107 }
108
109 // No root has this key. The extra branch and descendants cannot reach the
110 // selected public tree, but can expose unneeded source delivery or demand.
111 for (
112 let branchIndex = 0;
113 branchIndex < irrelevantBranchCount;
114 branchIndex++
115 ) {
116 const branchId = `irrelevant-branch-${branchIndex}`
117 const twigId = `irrelevant-twig-${branchIndex}`
118 branches.push({ id: branchId, parentId: `root-outside`, value: branchId })
119 twigs.push({ id: twigId, parentId: branchId, value: twigId })
120 leaves.push({
121 id: `irrelevant-leaf-${branchIndex}`,
122 parentId: twigId,
123 value: `irrelevant-leaf-${branchIndex}`,
124 })
125 }
126
127 return { roots, branches, twigs, leaves }
128}
129
130function createQuerySource<T extends { id: string }>(
131 name: string,
132 rows: Array<T>,
133 queryClient: QueryClient,
134 onProviderCall: () => void = () => {},
135 onDemand = false,
136) {
137 const id = `${name}-${nextCollectionId++}`
138 return createCollection(
139 queryCollectionOptions<T>({
140 id,
141 queryClient,
142 autoIndex: `eager`,
143 defaultIndexType: BasicIndex,
144 queryKey: [id],
145 syncMode: onDemand ? `on-demand` : `eager`,
146 startSync: true,
147 queryFn: (context) => {
148 onProviderCall()
149 if (!onDemand) return Promise.resolve(rows)
150 const where = context.meta?.loadSubsetOptions?.where
151 if (where === undefined) {
152 throw new Error(`On-demand tree source received no predicate`)
153 }
154 return Promise.resolve(
155 rows.filter((row) => evaluateReferenceExpression(where, row)),
156 )
157 },
158 getKey: (row) => row.id,
159 }),
160 )
161}
162
163function countDeliveredRows<T extends object>(collection: Collection<T>) {
164 let deliveredRows = 0
165 const originalSubscribeChanges = collection.subscribeChanges.bind(collection)
166
167 collection.subscribeChanges = (callback, options) => {
168 return originalSubscribeChanges((changes) => {
169 deliveredRows += changes.length
170 callback(changes)
171 }, options)
172 }
173
174 return () => deliveredRows
175}
176
177function expectedTreeCounts(rootCount: number): TreeCounts {
178 const branches = rootCount * branchesPerRoot
179 const twigs = branches * twigsPerBranch
180
181 return {
182 roots: rootCount,
183 branches,
184 twigs,
185 leaves: twigs * leavesPerTwig,
186 }
187}
188
189function requireChildren(row: NodeRow, level: string): NodeCollection {
190 if (row.children === undefined) {
191 throw new Error(`Expected ${level} row ${row.id} to have children`)
192 }
193 return row.children
194}
195
196function observeReachableTreeShape(
197 roots: NodeCollection,
198 rootRows: ReadonlyArray<NodeRow>,
199) {
200 const entries: Array<TreeEntry> = rootRows.map(({ id, value }) => ({
201 level: `roots`,
202 parentId: null,
203 id,
204 value,
205 }))
206 const reachableChildCollections = { branches: 0, twigs: 0, leaves: 0 }
207 const reachableChildRows = { branches: 0, twigs: 0, leaves: 0 }
208 let reachableTreeRows = roots.size
209
210 const countChildren = (
211 collection: NodeCollection,
212 level: ChildLevel,
213 parentId: string,
214 ): void => {
215 const children = collection.toArray
216 for (const { id, value } of children) {
217 entries.push({ level, parentId, id, value })
218 }
219 reachableChildCollections[level]++
220 reachableChildRows[level] += children.length
221 reachableTreeRows += children.length
222
223 const nextLevel =
224 level === `branches` ? `twigs` : level === `twigs` ? `leaves` : undefined
225 if (nextLevel === undefined) return
226
227 for (const child of children) {
228 countChildren(requireChildren(child, level), nextLevel, child.id)
229 }
230 }
231
232 for (const root of rootRows) {
233 countChildren(requireChildren(root, `root`), `branches`, root.id)
234 }
235
236 return {
237 entries,
238 reachableTreeRows,
239 reachableChildCollections,
240 reachableChildRows,
241 }
242}
243
244function expectedTreeEntries(rootCount: number): Array<TreeEntry> {
245 // Source foreign keys are the authority, not the nested query's routes.
246 // Build a separate world so source writes cannot alter the expected values.
247 const rows = createNestedTreeRows(rootCount)
248 return [
249 ...rows.roots.map((row) => ({
250 ...row,
251 level: `roots` as const,
252 parentId: null,
253 })),
254 ...rows.branches.map((row) => ({ ...row, level: `branches` as const })),
255 ...rows.twigs.map((row) => ({ ...row, level: `twigs` as const })),
256 ...rows.leaves.map((row) => ({ ...row, level: `leaves` as const })),
257 ]
258}
259
260function canonicalTreeEntries(entries: Array<TreeEntry>): Array<string> {
261 // No orderBy is requested. Sort for comparison, retaining duplicate entries.
262 return entries
263 .map(({ level, parentId, id, value }) =>
264 JSON.stringify([level, parentId, id, value]),
265 )
266 .sort()
267}
268
269function expectTreeEntries(entries: Array<TreeEntry>, rootCount: number): void {
270 expect(canonicalTreeEntries(entries)).toEqual(
271 canonicalTreeEntries(expectedTreeEntries(rootCount)),
272 )
273}
274
275function snapshotSourceRowsDelivered(
276 sourceCounters: Record<keyof TreeCounts, () => number>,
277): TreeCounts {
278 return {
279 roots: sourceCounters.roots(),
280 branches: sourceCounters.branches(),
281 twigs: sourceCounters.twigs(),
282 leaves: sourceCounters.leaves(),
283 }
284}
285
286async function checkNestedTreeShape(
287 rootCount: number,
288 verify: (observation: NestedTreeShape) => void,
289 transformRootRows: (
290 rows: ReadonlyArray<NodeRow>,
291 ) => ReadonlyArray<NodeRow> = (rows) => rows,
292 irrelevantBranchCount = 0,
293 onDemandChildren = false,
294): Promise<void> {
295 const rows = createNestedTreeRows(rootCount, irrelevantBranchCount)
296 const queryClient = new QueryClient({
297 defaultOptions: { queries: { retry: false } },
298 })
299 const providerCalls = { roots: 0, branches: 0, twigs: 0, leaves: 0 }
300 const acquisitionAttempts = { roots: 0, branches: 0, twigs: 0, leaves: 0 }
301 const sources = {
302 roots: createQuerySource(`tree-roots`, rows.roots, queryClient, () => {
303 providerCalls.roots++
304 }),
305 branches: createQuerySource(
306 `tree-branches`,
307 rows.branches,
308 queryClient,
309 () => {
310 providerCalls.branches++
311 },
312 onDemandChildren,
313 ),
314 twigs: createQuerySource(
315 `tree-twigs`,
316 rows.twigs,
317 queryClient,
318 () => {
319 providerCalls.twigs++
320 },
321 onDemandChildren,
322 ),
323 leaves: createQuerySource(
324 `tree-leaves`,
325 rows.leaves,
326 queryClient,
327 () => {
328 providerCalls.leaves++
329 },
330 onDemandChildren,
331 ),
332 }
333 let rootCollection: NodeCollection | undefined
334 let primaryFailure: unknown
335 let failed = false
336 const cleanupErrors: Array<unknown> = []
337
338 try {
339 if (onDemandChildren) {
340 for (const level of [`branches`, `twigs`, `leaves`] as const) {
341 const source = sources[level]
342 const loadSubset = source._sync.loadSubset.bind(source._sync)
343 source._sync.loadSubset = (options) => {
344 acquisitionAttempts[level]++
345 return loadSubset(options)
346 }
347 }
348 }
349 const sourceCounters = {
350 roots: countDeliveredRows(sources.roots),
351 branches: countDeliveredRows(sources.branches),
352 twigs: countDeliveredRows(sources.twigs),
353 leaves: countDeliveredRows(sources.leaves),
354 }
355
356 // This matches the nested result shape in #1634. Each children property
357 // remains a live Collection. The public result API exposes the reachable
358 // tree, not internal allocation counts, so this oracle constrains reachable
359 // cardinality, edges, values and source delivery, not allocations.
360 const roots: NodeCollection = createLiveQueryCollection({
361 startSync: true,
362 query: (q) =>
363 q.from({ root: sources.roots }).select(({ root }) => ({
364 id: root.id,
365 value: root.value,
366 children: q
367 .from({ branch: sources.branches })
368 .where(({ branch }) => eq(branch.parentId, root.id))
369 .select(({ branch }) => ({
370 id: branch.id,
371 value: branch.value,
372 children: q
373 .from({ twig: sources.twigs })
374 .where(({ twig }) => eq(twig.parentId, branch.id))
375 .select(({ twig }) => ({
376 id: twig.id,
377 value: twig.value,
378 children: q
379 .from({ leaf: sources.leaves })
380 .where(({ leaf }) => eq(leaf.parentId, twig.id))
381 .select(({ leaf }) => ({
382 id: leaf.id,
383 value: leaf.value,
384 })),
385 })),
386 })),
387 })),
388 })
389 rootCollection = roots
390 await roots.preload()
391
392 const sourceRowsDeliveredAtPreload =
393 snapshotSourceRowsDelivered(sourceCounters)
394 const providerCallsAtPreload = { ...providerCalls }
395 const acquisitionAttemptsAtPreload = { ...acquisitionAttempts }
396 const shape = observeReachableTreeShape(
397 roots,
398 transformRootRows(roots.toArray),
399 )
400
401 verify({
402 ...shape,
403 sourceRowsDeliveredAtPreload,
404 sourceRowsDeliveredAfterTraversal:
405 snapshotSourceRowsDelivered(sourceCounters),
406 providerCallsAtPreload,
407 providerCallsAfterTraversal: { ...providerCalls },
408 acquisitionAttemptsAtPreload,
409 acquisitionAttemptsAfterTraversal: { ...acquisitionAttempts },
410 })
411 } catch (error) {
412 primaryFailure = error
413 failed = true
414 } finally {
415 const results = await Promise.allSettled(
416 [
417 async () => rootCollection?.cleanup(),
418 ...Object.values(sources).map((source) => async () => source.cleanup()),
419 ].map(async (cleanup) => cleanup()),
420 )
421 cleanupErrors.push(
422 ...results.flatMap((result) =>
423 result.status === `rejected` ? [result.reason] : [],
424 ),
425 )
426 try {
427 queryClient.clear()
428 } catch (error) {
429 cleanupErrors.push(error)
430 }
431 }
432 if (cleanupErrors.length > 0) {
433 throw new AggregateError(cleanupErrors, `Nested-tree cleanup failed`, {
434 cause: failed ? primaryFailure : cleanupErrors[0],
435 })
436 }
437 if (failed) throw primaryFailure
438}
439
440function expectNestedTreeWork(
441 observation: NestedTreeShape,
442 rootCount: number,
443): void {
444 const expected = expectedTreeCounts(rootCount)
445 expect(observation.reachableTreeRows).toBe(
446 Object.values(expected).reduce((sum, count) => sum + count, 0),
447 )
448 expect(observation.sourceRowsDeliveredAtPreload).toEqual(expected)
449 expect(observation.sourceRowsDeliveredAfterTraversal).toEqual(
450 observation.sourceRowsDeliveredAtPreload,
451 )
452 expect(observation.providerCallsAfterTraversal).toEqual(
453 observation.providerCallsAtPreload,
454 )
455 expect(observation.acquisitionAttemptsAfterTraversal).toEqual(
456 observation.acquisitionAttemptsAtPreload,
457 )
458 expect(observation.reachableChildCollections).toEqual({
459 branches: expected.roots,
460 twigs: expected.branches,
461 leaves: expected.twigs,
462 })
463 expect(observation.reachableChildRows).toEqual({
464 branches: expected.branches,
465 twigs: expected.twigs,
466 leaves: expected.leaves,
467 })
468}
469
470function expectNestedTreeShape(
471 observation: NestedTreeShape,
472 rootCount: number,
473): void {
474 expectNestedTreeWork(observation, rootCount)
475 expectTreeEntries(observation.entries, rootCount)
476}
477
478function expectIrrelevantBranchWork(
479 baseline: NestedTreeShape,
480 scaled: NestedTreeShape,
481): void {
482 // The root uses one eager Query fetch. Each child level uses one on-demand
483 // acquisition attempt and one Query provider call for its reachable set.
484 const expectedProviderCalls = { roots: 1, branches: 1, twigs: 1, leaves: 1 }
485 const expectedAttempts = { roots: 0, branches: 1, twigs: 1, leaves: 1 }
486 expect(baseline.providerCallsAtPreload).toEqual(expectedProviderCalls)
487 expect(scaled.providerCallsAtPreload).toEqual(expectedProviderCalls)
488 expect(baseline.acquisitionAttemptsAtPreload).toEqual(expectedAttempts)
489 expect(scaled.acquisitionAttemptsAtPreload).toEqual(expectedAttempts)
490 expect(scaled.sourceRowsDeliveredAtPreload).toEqual(
491 baseline.sourceRowsDeliveredAtPreload,
492 )
493 expect(canonicalTreeEntries(scaled.entries)).toEqual(
494 canonicalTreeEntries(baseline.entries),
495 )
496}
497
498describe(`nested includes reachable-shape oracle`, () => {
499 // Keep every value from the former fixed-seed sample (2, 3, 4, 13, 17),
500 // plus nearby sizes. The empty and reported-size endpoints stay explicit.
501 it.each([1, 2, 3, 4, 5, 10, 13, 17])(
502 `preserves the complete reachable nested tree shape for %i roots`,
503 async (rootCount) => {
504 await checkNestedTreeShape(rootCount, (observation) =>
505 expectNestedTreeShape(observation, rootCount),
506 )
507 },
508 )
509
510 it(`exposes no nested collections for an empty root query`, async () => {
511 await checkNestedTreeShape(0, (observation) =>
512 expectNestedTreeShape(observation, 0),
513 )
514 })
515
516 it(`pins the reported 20-by-2-by-5-by-10 tree`, async () => {
517 // These semantic counters do not claim to measure elapsed time or internal
518 // allocations. They pin source delivery at preload and reachable shape.
519 await checkNestedTreeShape(20, (observation) =>
520 expectNestedTreeShape(observation, 20),
521 )
522 })
523
524 it(`does not deliver more source rows while traversing the result`, async () => {
525 await checkNestedTreeShape(20, (observation) => {
526 expect(observation.sourceRowsDeliveredAfterTraversal).toEqual(
527 observation.sourceRowsDeliveredAtPreload,
528 )
529 })
530 })
531
532 it.each([1, 3])(
533 `does not acquire or deliver %i disconnected branches at preload`,
534 async (irrelevantBranchCount) => {
535 const observations: Array<NestedTreeShape> = []
536 await checkNestedTreeShape(
537 2,
538 (observation) => {
539 expectNestedTreeShape(observation, 2)
540 observations.push(observation)
541 },
542 (rows) => rows,
543 0,
544 true,
545 )
546 await checkNestedTreeShape(
547 2,
548 (observation) => {
549 expectNestedTreeShape(observation, 2)
550 observations.push(observation)
551 },
552 (rows) => rows,
553 irrelevantBranchCount,
554 true,
555 )
556 const [baseline, scaled] = observations as [
557 NestedTreeShape,
558 NestedTreeShape,
559 ]
560 expectIrrelevantBranchWork(baseline, scaled)
561
562 // An extra acquisition for an unreachable branch could leave the public
563 // tree correct. It must still fail this comparison at preload.
564 const wrongWork: NestedTreeShape = {
565 ...scaled,
566 acquisitionAttemptsAtPreload: {
567 ...scaled.acquisitionAttemptsAtPreload,
568 branches: scaled.acquisitionAttemptsAtPreload.branches + 1,
569 },
570 }
571 expect(() => expectIrrelevantBranchWork(baseline, wrongWork)).toThrow()
572 },
573 )
574
575 it(`rejects a repeated source row delivery after traversal`, async () => {
576 await checkNestedTreeShape(2, (observation) => {
577 expectNestedTreeShape(observation, 2)
578 const repeatedDelivery: NestedTreeShape = {
579 ...observation,
580 sourceRowsDeliveredAfterTraversal: {
581 ...observation.sourceRowsDeliveredAfterTraversal,
582 branches: observation.sourceRowsDeliveredAfterTraversal.branches + 1,
583 },
584 }
585 expect(() => expectNestedTreeWork(repeatedDelivery, 2)).toThrow()
586 })
587 })
588
589 it.each([`subtree swap`, `value corruption`] as const)(
590 `rejects %s even when reachable cardinality and source work agree`,
591 async (fault) => {
592 await checkNestedTreeShape(2, (observation) =>
593 expectNestedTreeShape(observation, 2),
594 )
595 await checkNestedTreeShape(
596 2,
597 (observation) => {
598 expectNestedTreeWork(observation, 2)
599 expect(() => expectTreeEntries(observation.entries, 2)).toThrow()
600 },
601 (roots) => {
602 expect(roots).toHaveLength(2)
603 const [first, second] = roots as [NodeRow, NodeRow]
604 // Corrupt copied public rows before capture, not expected records or
605 // production state. Both branches still use real child Collections.
606 return fault === `subtree swap`
607 ? [
608 { ...first, children: second.children },
609 { ...second, children: first.children },
610 ]
611 : [{ ...first, value: `wrong root value` }, second]
612 },
613 )
614 },
615 )
616})