Open History to see the last commit
1import { fc, test as fcTest } from '@fast-check/vitest'
2import { QueryClient } from '@tanstack/query-core'
3import {
4 BasicIndex,
5 createCollection,
6 createLiveQueryCollection,
7 eq,
8} from '@tanstack/db'
9import { describe, expect, it } from 'vitest'
10import { queryCollectionOptions } from '../src/query'
11import type { Collection } from '@tanstack/db'
12
13/**
14 * Nested Query-backed includes should acquire work proportional to reachable
15 * demand, not to the cartesian size of the backing tree.
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. Independent loadSubset counters record physical rows delivered before
20 * and after public traversal. Generated root counts vary scale while fixed
21 * branching exposes accidental full-tree acquisition.
22 *
23 * The oracle checks both complete nested values and work bounds. Correct rows
24 * alone would allow an implementation that scans every branch; low counters
25 * alone could hide missing descendants or leaked child collections.
26 */
27
28let nextCollectionId = 0
29
30type RootRow = { id: string; value: string }
31type BranchRow = { id: string; parentId: string; value: string }
32type TwigRow = { id: string; parentId: string; value: string }
33type LeafRow = { id: string; parentId: string; value: string }
34
35type TreeCounts = {
36 roots: number
37 branches: number
38 twigs: number
39 leaves: number
40}
41
42type ChildLevel = Exclude<keyof TreeCounts, 'roots'>
43
44type TreeEntry = {
45 level: keyof TreeCounts
46 parentId: string | null
47 id: string
48 value: string
49}
50
51type NodeRow = {
52 id: string
53 value: string
54 children?: NodeCollection
55}
56
57type NodeCollection = Pick<
58 Collection<NodeRow, string | number>,
59 'cleanup' | 'preload' | 'size' | 'toArray'
60>
61
62type NestedTreeShape = {
63 entries: Array<TreeEntry>
64 reachableTreeRows: number
65 sourceRowsDeliveredAtPreload: TreeCounts
66 sourceRowsDeliveredAfterTraversal: TreeCounts
67 reachableChildCollections: Record<ChildLevel, number>
68 reachableChildRows: Record<ChildLevel, number>
69}
70
71const branchesPerRoot = 2
72const twigsPerBranch = 5
73const leavesPerTwig = 10
74
75function createNestedTreeRows(rootCount: number) {
76 const roots: Array<RootRow> = []
77 const branches: Array<BranchRow> = []
78 const twigs: Array<TwigRow> = []
79 const leaves: Array<LeafRow> = []
80
81 for (let rootIndex = 0; rootIndex < rootCount; rootIndex++) {
82 const rootId = `root-${rootIndex}`
83 roots.push({ id: rootId, value: rootId })
84
85 for (let branchIndex = 0; branchIndex < branchesPerRoot; branchIndex++) {
86 const branchId = `branch-${rootIndex}-${branchIndex}`
87 branches.push({ id: branchId, parentId: rootId, value: branchId })
88
89 for (let twigIndex = 0; twigIndex < twigsPerBranch; twigIndex++) {
90 const twigId = `twig-${rootIndex}-${branchIndex}-${twigIndex}`
91 twigs.push({ id: twigId, parentId: branchId, value: twigId })
92
93 for (let leafIndex = 0; leafIndex < leavesPerTwig; leafIndex++) {
94 const leafId = `leaf-${rootIndex}-${branchIndex}-${twigIndex}-${leafIndex}`
95 leaves.push({ id: leafId, parentId: twigId, value: leafId })
96 }
97 }
98 }
99 }
100
101 return { roots, branches, twigs, leaves }
102}
103
104function createQuerySource<T extends { id: string }>(
105 name: string,
106 rows: Array<T>,
107 queryClient: QueryClient,
108) {
109 const id = `${name}-${nextCollectionId++}`
110 return createCollection(
111 queryCollectionOptions<T>({
112 id,
113 queryClient,
114 autoIndex: `eager`,
115 defaultIndexType: BasicIndex,
116 queryKey: [id],
117 queryFn: () => Promise.resolve(rows),
118 getKey: (row) => row.id,
119 }),
120 )
121}
122
123function countDeliveredRows<T extends object>(collection: Collection<T>) {
124 let deliveredRows = 0
125 const originalSubscribeChanges = collection.subscribeChanges.bind(collection)
126
127 collection.subscribeChanges = (callback, options) => {
128 return originalSubscribeChanges((changes) => {
129 deliveredRows += changes.length
130 callback(changes)
131 }, options)
132 }
133
134 return () => deliveredRows
135}
136
137function expectedTreeCounts(rootCount: number): TreeCounts {
138 const branches = rootCount * branchesPerRoot
139 const twigs = branches * twigsPerBranch
140
141 return {
142 roots: rootCount,
143 branches,
144 twigs,
145 leaves: twigs * leavesPerTwig,
146 }
147}
148
149function requireChildren(row: NodeRow, level: string): NodeCollection {
150 if (row.children === undefined) {
151 throw new Error(`Expected ${level} row ${row.id} to have children`)
152 }
153 return row.children
154}
155
156function observeReachableTreeShape(
157 roots: NodeCollection,
158 rootRows: ReadonlyArray<NodeRow>,
159) {
160 const entries: Array<TreeEntry> = rootRows.map(({ id, value }) => ({
161 level: `roots`,
162 parentId: null,
163 id,
164 value,
165 }))
166 const reachableChildCollections = { branches: 0, twigs: 0, leaves: 0 }
167 const reachableChildRows = { branches: 0, twigs: 0, leaves: 0 }
168 let reachableTreeRows = roots.size
169
170 const countChildren = (
171 collection: NodeCollection,
172 level: ChildLevel,
173 parentId: string,
174 ): void => {
175 const children = collection.toArray
176 for (const { id, value } of children) {
177 entries.push({ level, parentId, id, value })
178 }
179 reachableChildCollections[level]++
180 reachableChildRows[level] += children.length
181 reachableTreeRows += children.length
182
183 const nextLevel =
184 level === `branches` ? `twigs` : level === `twigs` ? `leaves` : undefined
185 if (nextLevel === undefined) return
186
187 for (const child of children) {
188 countChildren(requireChildren(child, level), nextLevel, child.id)
189 }
190 }
191
192 for (const root of rootRows) {
193 countChildren(requireChildren(root, `root`), `branches`, root.id)
194 }
195
196 return {
197 entries,
198 reachableTreeRows,
199 reachableChildCollections,
200 reachableChildRows,
201 }
202}
203
204function expectedTreeEntries(rootCount: number): Array<TreeEntry> {
205 // Source foreign keys are the authority, not the nested query's routes.
206 // Build a separate world so source writes cannot alter the expected values.
207 const rows = createNestedTreeRows(rootCount)
208 return [
209 ...rows.roots.map((row) => ({
210 ...row,
211 level: `roots` as const,
212 parentId: null,
213 })),
214 ...rows.branches.map((row) => ({ ...row, level: `branches` as const })),
215 ...rows.twigs.map((row) => ({ ...row, level: `twigs` as const })),
216 ...rows.leaves.map((row) => ({ ...row, level: `leaves` as const })),
217 ]
218}
219
220function expectTreeEntries(entries: Array<TreeEntry>, rootCount: number): void {
221 // No orderBy is requested. Sort for comparison, retaining duplicate entries.
222 const canonical = (rows: Array<TreeEntry>) =>
223 rows
224 .map(({ level, parentId, id, value }) =>
225 JSON.stringify([level, parentId, id, value]),
226 )
227 .sort()
228 expect(canonical(entries)).toEqual(canonical(expectedTreeEntries(rootCount)))
229}
230
231function snapshotSourceRowsDelivered(
232 sourceCounters: Record<keyof TreeCounts, () => number>,
233): TreeCounts {
234 return {
235 roots: sourceCounters.roots(),
236 branches: sourceCounters.branches(),
237 twigs: sourceCounters.twigs(),
238 leaves: sourceCounters.leaves(),
239 }
240}
241
242async function runCleanups(
243 cleanups: ReadonlyArray<() => void | Promise<void>>,
244): Promise<void> {
245 const results = await Promise.allSettled(
246 cleanups.map(async (cleanup) => cleanup()),
247 )
248 const firstRejection = results.find(
249 (result): result is PromiseRejectedResult => result.status === `rejected`,
250 )
251 if (firstRejection !== undefined) throw firstRejection.reason
252}
253
254function rethrowFirstCleanupError(
255 results: ReadonlyArray<{ rejected: boolean; error: unknown }>,
256): void {
257 const firstRejection = results.find((result) => result.rejected)
258 if (firstRejection !== undefined) throw firstRejection.error
259}
260
261async function observeNestedTreeShape(
262 rootCount: number,
263 transformRootRows: (
264 rows: ReadonlyArray<NodeRow>,
265 ) => ReadonlyArray<NodeRow> = (rows) => rows,
266): Promise<NestedTreeShape> {
267 const rows = createNestedTreeRows(rootCount)
268 const queryClient = new QueryClient({
269 defaultOptions: { queries: { retry: false } },
270 })
271 const sources = {
272 roots: createQuerySource(`tree-roots`, rows.roots, queryClient),
273 branches: createQuerySource(`tree-branches`, rows.branches, queryClient),
274 twigs: createQuerySource(`tree-twigs`, rows.twigs, queryClient),
275 leaves: createQuerySource(`tree-leaves`, rows.leaves, queryClient),
276 }
277 let rootCollection: NodeCollection | undefined
278
279 try {
280 const sourceCounters = {
281 roots: countDeliveredRows(sources.roots),
282 branches: countDeliveredRows(sources.branches),
283 twigs: countDeliveredRows(sources.twigs),
284 leaves: countDeliveredRows(sources.leaves),
285 }
286
287 // This matches the nested result shape in #1634. Each children property
288 // remains a live Collection. The public result API exposes the reachable
289 // tree, not internal allocation counts, so this oracle constrains reachable
290 // cardinality, edges, values and source delivery, not allocations.
291 const roots: NodeCollection = createLiveQueryCollection({
292 startSync: true,
293 query: (q) =>
294 q.from({ root: sources.roots }).select(({ root }) => ({
295 id: root.id,
296 value: root.value,
297 children: q
298 .from({ branch: sources.branches })
299 .where(({ branch }) => eq(branch.parentId, root.id))
300 .select(({ branch }) => ({
301 id: branch.id,
302 value: branch.value,
303 children: q
304 .from({ twig: sources.twigs })
305 .where(({ twig }) => eq(twig.parentId, branch.id))
306 .select(({ twig }) => ({
307 id: twig.id,
308 value: twig.value,
309 children: q
310 .from({ leaf: sources.leaves })
311 .where(({ leaf }) => eq(leaf.parentId, twig.id))
312 .select(({ leaf }) => ({
313 id: leaf.id,
314 value: leaf.value,
315 })),
316 })),
317 })),
318 })),
319 })
320 rootCollection = roots
321 await roots.preload()
322
323 const sourceRowsDeliveredAtPreload =
324 snapshotSourceRowsDelivered(sourceCounters)
325 const shape = observeReachableTreeShape(
326 roots,
327 transformRootRows(roots.toArray),
328 )
329
330 return {
331 ...shape,
332 sourceRowsDeliveredAtPreload,
333 sourceRowsDeliveredAfterTraversal:
334 snapshotSourceRowsDelivered(sourceCounters),
335 }
336 } finally {
337 let cleanupRejected = false
338 let cleanupError: unknown
339 try {
340 await runCleanups([
341 async () => rootCollection?.cleanup(),
342 ...Object.values(sources).map((source) => async () => source.cleanup()),
343 ])
344 } catch (error) {
345 cleanupRejected = true
346 cleanupError = error
347 }
348
349 let clearRejected = false
350 let clearError: unknown
351 try {
352 queryClient.clear()
353 } catch (error) {
354 clearRejected = true
355 clearError = error
356 }
357
358 rethrowFirstCleanupError([
359 { rejected: cleanupRejected, error: cleanupError },
360 { rejected: clearRejected, error: clearError },
361 ])
362 }
363}
364
365function expectNestedTreeWork(
366 observation: NestedTreeShape,
367 rootCount: number,
368): void {
369 const expected = expectedTreeCounts(rootCount)
370 expect(observation.reachableTreeRows).toBe(
371 Object.values(expected).reduce((sum, count) => sum + count, 0),
372 )
373 expect(observation.sourceRowsDeliveredAtPreload).toEqual(expected)
374 expect(observation.sourceRowsDeliveredAfterTraversal).toEqual(
375 observation.sourceRowsDeliveredAtPreload,
376 )
377 expect(observation.reachableChildCollections).toEqual({
378 branches: expected.roots,
379 twigs: expected.branches,
380 leaves: expected.twigs,
381 })
382 expect(observation.reachableChildRows).toEqual({
383 branches: expected.branches,
384 twigs: expected.twigs,
385 leaves: expected.leaves,
386 })
387}
388
389function expectNestedTreeShape(
390 observation: NestedTreeShape,
391 rootCount: number,
392): void {
393 expectNestedTreeWork(observation, rootCount)
394 expectTreeEntries(observation.entries, rootCount)
395}
396
397describe(`nested includes reachable-shape oracle`, () => {
398 // Fixed structural campaign; shared random/seed/multiplier options do not
399 // apply to this property. The empty and reported-size witnesses stay explicit.
400 fcTest.prop([fc.integer({ min: 0, max: 20 })], {
401 numRuns: 6,
402 seed: 1634,
403 })(
404 `preserves the complete reachable nested tree shape (#1634)`,
405 async (rootCount) => {
406 expectNestedTreeShape(await observeNestedTreeShape(rootCount), rootCount)
407 },
408 )
409
410 it(`exposes no nested collections for an empty root query`, async () => {
411 expectNestedTreeShape(await observeNestedTreeShape(0), 0)
412 })
413
414 it(`pins #1634's reported 20-by-2-by-5-by-10 tree`, async () => {
415 // These semantic counters do not claim to measure elapsed time or internal
416 // allocations. They pin source delivery at preload and reachable shape.
417 expectNestedTreeShape(await observeNestedTreeShape(20), 20)
418 })
419
420 it(`does not deliver more source rows while traversing the result`, async () => {
421 const observation = await observeNestedTreeShape(20)
422 expect(observation.sourceRowsDeliveredAfterTraversal).toEqual(
423 observation.sourceRowsDeliveredAtPreload,
424 )
425 })
426
427 it.each([`subtree swap`, `value corruption`] as const)(
428 `rejects %s even when reachable cardinality and source work agree`,
429 async (fault) => {
430 expectNestedTreeShape(await observeNestedTreeShape(2), 2)
431 const observation = await observeNestedTreeShape(2, (roots) => {
432 expect(roots).toHaveLength(2)
433 const [first, second] = roots as [NodeRow, NodeRow]
434 // Corrupt copied public rows before capture, not expected records or
435 // production state. Both branches still use real child Collections.
436 return fault === `subtree swap`
437 ? [
438 { ...first, children: second.children },
439 { ...second, children: first.children },
440 ]
441 : [{ ...first, value: `wrong root value` }, second]
442 })
443 expectNestedTreeWork(observation, 2)
444 expect(() => expectTreeEntries(observation.entries, 2)).toThrow()
445 },
446 )
447})