Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

includes-work-counter-oracle.test.ts

623 lines19.7 KB

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