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

infinite-query-render-cuts-oracle.test.tsx

570 lines18.1 KB

1/**
2 * React's pre-commit cut for `useLiveInfiniteQuery`.
3 *
4 * React can render a component without committing it: a Suspense render that
5 * throws, a StrictMode double render, or a retry after an earlier attempt was
6 * discarded. The shared infinite-query suite cannot express that cut, because
7 * Vue's setup is its commit. These laws belong to the React driver:
8 *
9 * - For an on-demand source, the hook does what useLiveQuery does under the
10 * same history: it starts the source during render, so a render that never
11 * commits acquires it as often as useLiveQuery would, and a StrictMode double
12 * render requests the first window once and commits the same first value.
13 * This holds for a query callback and a supplied collection, with the source
14 * read directly or through a live-query Collection. useLiveQuery is the
15 * reference by decision: the two hooks must behave the same.
16 * - When GC has reclaimed an abandoned render's collection, the retry's first
17 * commit is the ready first page, after a fresh mount and after a mounted
18 * component's suspended update.
19 * - The hook agrees with `useLiveQuery`: for the same synchronous source, both
20 * commit the same ready rows first.
21 * - A collection kept from an abandoned render is reused only while it can
22 * still serve the query. When its source restarts after cleanup, that
23 * collection is in terminal error, so selecting its query again shows the
24 * restarted source's rows, ready, as useLiveQuery does.
25 * - A mounted replacement whose synchronous startup throws delivers that error
26 * to the error boundary, as useLiveQuery does. React retries the render; a
27 * retry that reused the failed render's collection would commit
28 * `status: error` instead.
29 *
30 * Expectations come from the source rows, page size, request counts, and
31 * useLiveQuery under the same history, never from the hook's controller state.
32 */
33import { Component, StrictMode, Suspense, useLayoutEffect } from 'react'
34import { act, render, renderHook, waitFor } from '@testing-library/react'
35import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
36import {
37 BTreeIndex,
38 createCollection,
39 createLiveQueryCollection,
40 gt,
41} from '@tanstack/db'
42import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
43import { mockSyncCollectionOptions } from '../../db/tests/utils'
44import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
45import { useLiveQuery } from '../src/useLiveQuery'
46import type { ReactNode } from 'react'
47​
48type Row = { id: string; label: string; rank: number }
49​
50class ErrorBoundary extends Component<
51 { children: ReactNode },
52 { error?: Error }
53> {
54 state: { error?: Error } = {}
55 static getDerivedStateFromError(error: Error) {
56 return { error }
57 }
58 render() {
59 return this.state.error ? (
60 <div>Rejected: {this.state.error.message}</div>
61 ) : (
62 this.props.children
63 )
64 }
66​
67let sequence = 0
68const cleanups: Array<() => Promise<void> | void> = []
69afterEach(async () => {
70 // Unmount hooks before cleaning up the sources they read.
71 for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
72})
73​
74function rows(count: number): Array<Row> {
75 return Array.from({ length: count }, (_, index) => ({
76 id: String(index + 1),
77 label: `row-${index + 1}`,
78 rank: count - index,
79 }))
81​
82function makeSyncSource(count: number) {
83 const source = createCollection(
84 mockSyncCollectionOptions<Row>({
85 id: `infinite-render-cuts-${sequence++}`,
86 getKey: (row) => row.id,
87 autoIndex: `eager`,
88 initialData: rows(count),
89 }),
90 )
91 cleanups.push(() => source.cleanup())
92 return source
94​
95type HookName = `live` | `infinite`
96type InputForm = `query` | `supplied`
97const PAGE_SIZE = 2
98​
99// Counts source acquisitions. The load never settles, so only the request
100// itself is observed. A wrapped source sits behind a live-query Collection,
101// which does not copy its source's sync mode.
102function makeCountingOnDemandSource(wrapped: boolean) {
103 let loads = 0
104 const source = createCollection<Row>({
105 id: `infinite-render-cuts-remote-${sequence++}`,
106 getKey: (row) => row.id,
107 syncMode: `on-demand`,
108 autoIndex: `eager`,
109 defaultIndexType: BTreeIndex,
110 sync: {
111 sync: ({ markReady }) => {
112 markReady()
113 return {
114 loadSubset: () => {
115 loads++
116 return new Promise<void>(() => {})
117 },
118 }
119 },
120 },
121 })
122 cleanups.push(() => source.cleanup())
123 if (!wrapped) return { target: source as any, loads: () => loads }
124 const intermediate = createLiveQueryCollection({
125 query: (q) =>
126 q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
127 startSync: false,
128 gcTime: 1,
129 })
130 cleanups.push(() => intermediate.cleanup())
131 return { target: intermediate as any, loads: () => loads }
133​
134// The same read through either hook. A query callback asks useLiveQuery for
135// the infinite hook's first window, so both build the same physical query.
136function useHookUnderTest(hook: HookName, form: InputForm, target: any) {
137 if (form === `supplied`) {
138 return hook === `live`
139 ? useLiveQuery(target)
140 : useLiveInfiniteQuery(target, { pageSize: PAGE_SIZE })
141 }
142 return hook === `live`
143 ? useLiveQuery((q: any) =>
144 q
145 .from({ items: target })
146 .orderBy(({ items }: any) => items.rank, `desc`)
147 .limit(PAGE_SIZE + 1),
148 )
149 : useLiveInfiniteQuery(
150 (q: any) =>
151 q
152 .from({ items: target })
153 .orderBy(({ items }: any) => items.rank, `desc`),
154 { pageSize: PAGE_SIZE },
155 )
157​
158async function acquisitionsForAbandonedRender(
159 hook: HookName,
160 form: InputForm,
161 wrapped: boolean,
162): Promise<number> {
163 const { target, loads } = makeCountingOnDemandSource(wrapped)
164 const never = new Promise<void>(() => {})
165 function Abandoned(): ReactNode {
166 useHookUnderTest(hook, form, target)
167 throw never
168 }
169 const view = render(
170 <Suspense fallback={null}>
171 <Abandoned />
172 </Suspense>,
173 )
174 cleanups.push(() => view.unmount())
175 await act(async () => {
176 await new Promise((resolve) => setTimeout(resolve, 0))
177 })
178 return loads()
180​
181async function firstWindowLoadsForStrictMount(hook: HookName) {
182 const source = makeInfiniteOnDemandSource(
183 { createCollection, BTreeIndex },
184 rows(8),
185 )
186 cleanups.push(() => source.collection.cleanup())
187 const commits: Array<{ status: string; ids: Array<string> }> = []
188 const hook_ = renderHook(
189 () => {
190 const result: any = useHookUnderTest(hook, `query`, source.collection)
191 useLayoutEffect(() => {
192 commits.push({
193 status: result.status,
194 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
195 })
196 })
197 return result
198 },
199 { wrapper: StrictMode },
200 )
201 cleanups.push(() => hook_.unmount())
202 await waitFor(() => expect(commits.length).toBeGreaterThan(0))
203 return {
204 loads: source.calls.filter((call) => call.limit === PAGE_SIZE + 1).length,
205 firstCommit: commits[0],
206 }
208​
209describe(`on-demand sources match useLiveQuery`, () => {
210 it.each([
211 { form: `query` as const, wrapped: false },
212 { form: `query` as const, wrapped: true },
213 { form: `supplied` as const, wrapped: true },
214 ])(
215 `acquires as useLiveQuery does for a render that never commits (%o)`,
216 async ({ form, wrapped }) => {
217 const reference = await acquisitionsForAbandonedRender(
218 `live`,
219 form,
220 wrapped,
221 )
222 expect(
223 await acquisitionsForAbandonedRender(`infinite`, form, wrapped),
224 ).toBe(reference)
225 },
226 )
227​
228 it(`requests the first window and commits the first value as useLiveQuery does across a StrictMode double render`, async () => {
229 const reference = await firstWindowLoadsForStrictMount(`live`)
230 expect(reference.firstCommit).toEqual({
231 status: `ready`,
232 ids: [`1`, `2`],
233 })
234 // React 19 keeps refs across the double render, so both hooks request the
235 // first window once. React 18 does not; see the coverage map.
236 expect(reference.loads).toBe(1)
237 expect(await firstWindowLoadsForStrictMount(`infinite`)).toEqual(reference)
238 })
239​
240 it.each([`live`, `infinite`] as const)(
241 `delivers a mounted replacement's startup error to the error boundary (%s)`,
242 async (hook) => {
243 const source = makeSyncSource(4)
244 const failure = new Error(`replacement failed to start`)
245 const commits: Array<{ fail: boolean; status: string }> = []
246 const consoleError = vi
247 .spyOn(console, `error`)
248 .mockImplementation(() => {})
249 function View({ fail }: { fail: boolean }): ReactNode {
250 const query = (q: any) =>
251 q
252 .from({ items: source })
253 .fn.where(() => {
254 if (fail) throw failure
255 return true
256 })
257 .orderBy(({ items }: any) => items.rank, `desc`)
258 const result: any =
259 hook === `live`
260 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1), [fail])
261 : useLiveInfiniteQuery(query, {
262 pageSize: PAGE_SIZE,
263 queryKey: [`startup-error`, fail],
264 })
265 useLayoutEffect(() => {
266 commits.push({ fail, status: result.status })
267 })
268 return null
269 }
270 try {
271 const view = render(
272 <ErrorBoundary>
273 <View fail={false} />
274 </ErrorBoundary>,
275 )
276 cleanups.push(() => view.unmount())
277 await waitFor(() =>
278 expect(commits.at(-1)).toEqual({ fail: false, status: `ready` }),
279 )
280 await act(async () => {
281 view.rerender(
282 <ErrorBoundary>
283 <View fail={true} />
284 </ErrorBoundary>,
285 )
286 })
287 // The error reaches the boundary; the replacement never commits.
288 expect(
289 view.getByText(`Rejected: replacement failed to start`),
290 ).toBeDefined()
291 expect(commits.filter((commit) => commit.fail)).toEqual([])
292 } finally {
293 consoleError.mockRestore()
294 }
295 },
296 )
297})
298​
299describe(`retries after GC`, () => {
300 beforeEach(() => vi.useFakeTimers())
301 afterEach(() => vi.useRealTimers())
302​
303 it(`shows the ready first page when a Suspense retry follows a GC-collected abandoned render`, async () => {
304 const source = makeSyncSource(10)
305 let suspend = true
306 let release!: () => void
307 const gate = new Promise<void>((resolve) => {
308 release = resolve
309 })
310 const commits: Array<{ status: string; ids: Array<string> }> = []
311 let abandonedCollection: { status: string } | undefined
312 let retryCollection: { status: string } | undefined
313​
314 function Query(): ReactNode {
315 const result = useLiveInfiniteQuery(
316 (q) =>
317 q.from({ items: source }).orderBy(({ items }) => items.rank, `desc`),
318 { pageSize: 3 },
319 )
320 if (suspend) {
321 abandonedCollection = result.collection as unknown as {
322 status: string
323 }
324 throw gate
325 }
326 retryCollection = result.collection as unknown as { status: string }
327 useLayoutEffect(() => {
328 commits.push({
329 status: result.status,
330 ids: result.data.map((row) => row.id),
331 })
332 })
333 return null
334 }
335​
336 const view = render(
337 <Suspense fallback={null}>
338 <Query />
339 </Suspense>,
340 )
341 cleanups.push(() => view.unmount())
342 // Let the 50 ms unsubscribed GC floor reclaim the abandoned collection.
343 await act(async () => {
344 await vi.advanceTimersByTimeAsync(100)
345 })
346​
347 suspend = false
348 await act(async () => {
349 release()
350 await vi.advanceTimersByTimeAsync(0)
351 })
352​
353 expect(abandonedCollection?.status).toBe(`cleaned-up`)
354 expect(retryCollection).not.toBe(abandonedCollection)
355 expect(commits[0]).toEqual({ status: `ready`, ids: [`1`, `2`, `3`] })
356 })
357​
358 it(`shows the ready first page when a mounted query's suspended update retries after GC`, async () => {
359 // A committed component keeps its hook refs across a suspended update. A
360 // retry that bound the update's collection after GC cleaned it up would
361 // commit an empty cleaned-up page before recovering.
362 const source = makeSyncSource(10)
363 let suspend = false
364 let release!: () => void
365 const gate = new Promise<void>((resolve) => {
366 release = resolve
367 })
368 const commits: Array<{
369 minimum: number
370 status: string
371 ranks: Array<number>
372 }> = []
373​
374 function Query({ minimum }: { minimum: number }): ReactNode {
375 const result = useLiveInfiniteQuery(
376 (q) =>
377 q
378 .from({ items: source })
379 .where(({ items }) => gt(items.rank, minimum))
380 .orderBy(({ items }) => items.rank, `desc`),
381 { pageSize: 3 },
382 [minimum],
383 )
384 useLayoutEffect(() => {
385 commits.push({
386 minimum,
387 status: result.status,
388 ranks: result.data.map((row) => row.rank),
389 })
390 })
391 if (suspend) throw gate
392 return null
393 }
394​
395 const view = render(
396 <Suspense fallback={null}>
397 <Query minimum={0} />
398 </Suspense>,
399 )
400 cleanups.push(() => view.unmount())
401 await act(async () => {
402 await vi.advanceTimersByTimeAsync(0)
403 })
404​
405 suspend = true
406 await act(async () => {
407 view.rerender(
408 <Suspense fallback={null}>
409 <Query minimum={5} />
410 </Suspense>,
411 )
412 await vi.advanceTimersByTimeAsync(0)
413 })
414 await act(async () => {
415 await vi.advanceTimersByTimeAsync(200)
416 })
417​
418 suspend = false
419 await act(async () => {
420 release()
421 await vi.advanceTimersByTimeAsync(0)
422 })
423​
424 expect(commits.find((commit) => commit.minimum === 5)).toEqual({
425 minimum: 5,
426 status: `ready`,
427 ranks: [10, 9, 8],
428 })
429 })
430})
431​
432describe(`agreement with useLiveQuery`, () => {
433 it(`commits the same ready rows first as useLiveQuery for a synchronous source`, async () => {
434 const source = makeSyncSource(10)
435 const firstCommit = (
436 useResult: () => { status: string; data: Array<Row> },
437 ) => {
438 const commits: Array<{ status: string; ids: Array<string> }> = []
439 const hook = renderHook(() => {
440 const result = useResult()
441 useLayoutEffect(() => {
442 commits.push({
443 status: result.status,
444 ids: result.data.map((row) => row.id),
445 })
446 })
447 return result
448 })
449 cleanups.push(() => hook.unmount())
450 return commits
451 }
452​
453 const live = firstCommit(() =>
454 useLiveQuery((q) =>
455 q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
456 ),
457 )
458 const infinite = firstCommit(() =>
459 useLiveInfiniteQuery(
460 (q) => q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
461 { pageSize: 20 },
462 ),
463 )
464 await waitFor(() => expect(infinite.length).toBeGreaterThan(0))
465​
466 const expected = { status: `ready`, ids: rows(10).map((row) => row.id) }
467 expect(live[0]).toEqual(expected)
468 expect(infinite[0]).toEqual(expected)
469 })
470})
471​
472describe(`collections kept from an abandoned render`, () => {
473 // An eager source that writes `current` each time its sync run starts, so a
474 // restart after cleanup serves new rows from the same source object.
475 function makeRestartableSource(initial: Array<Row>) {
476 let current = initial
477 const source = createCollection<Row>({
478 id: `infinite-render-cuts-restartable-${sequence++}`,
479 getKey: (row) => row.id,
480 autoIndex: `eager`,
481 defaultIndexType: BTreeIndex,
482 startSync: true,
483 sync: {
484 sync: ({ begin, write, commit, markReady }) => {
485 begin()
486 for (const row of current) write({ type: `insert`, value: row })
487 commit()
488 markReady()
489 },
490 },
491 })
492 cleanups.push(() => source.cleanup())
493 return {
494 source,
495 restartWith: async (next: Array<Row>) => {
496 await source.cleanup()
497 current = next
498 source.startSyncImmediate()
499 },
500 }
501 }
502 const byId = (ids: Array<number>): Array<Row> =>
503 ids.map((id) => ({ id: String(id), label: `row-${id}`, rank: id }))
504​
505 it.each([`live`, `infinite`] as const)(
506 `shows the restarted source's rows when an abandoned render's query is selected again (%s)`,
507 async (hook) => {
508 // Model: after the restart the source holds ids 4-8, so the query for
509 // ranks above 2, ascending, shows ids 4 and 5 on its first page.
510 const { source, restartWith } = makeRestartableSource(
511 byId([1, 2, 3, 4, 5]),
512 )
513 const never = new Promise<void>(() => {})
514 const commits: Array<{
515 minimum: number
516 status: string
517 ids: Array<string>
518 }> = []
519 function Query({
520 minimum,
521 suspend,
522 }: {
523 minimum: number
524 suspend: boolean
525 }): ReactNode {
526 const query = (q: any) =>
527 q
528 .from({ items: source })
529 .where(({ items }: any) => gt(items.rank, minimum))
530 .orderBy(({ items }: any) => items.rank, `asc`)
531 const result: any =
532 hook === `live`
533 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1))
534 : useLiveInfiniteQuery(query, { pageSize: PAGE_SIZE })
535 useLayoutEffect(() => {
536 commits.push({
537 minimum,
538 status: result.status,
539 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
540 })
541 })
542 if (suspend) throw never
543 return null
544 }
545 const tree = (minimum: number, suspend: boolean) => (
546 <Suspense fallback={null}>
547 <Query minimum={minimum} suspend={suspend} />
548 </Suspense>
549 )
550 const view = render(tree(0, false))
551 cleanups.push(() => view.unmount())
552 await act(async () => {})
553 // Render B and abandon it, then commit A again.
554 act(() => view.rerender(tree(2, true)))
555 act(() => view.rerender(tree(0, false)))
556 await act(async () => restartWith(byId([4, 5, 6, 7, 8])))
557 commits.length = 0
558 act(() => view.rerender(tree(2, false)))
559 await act(async () => {
560 await new Promise((resolve) => setTimeout(resolve, 0))
561 })
562​
563 expect(commits.filter((commit) => commit.minimum === 2).at(-1)).toEqual({
564 minimum: 2,
565 status: `ready`,
566 ids: [`4`, `5`],
567 })
568 },
569 )
570})