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

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

569 lines18.2 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 * - A live-query Collection starts no provider work before it has a
10 * subscriber or a preload. A render that never commits therefore starts no
11 * acquisition attempt on an on-demand source, whether a query callback or a
12 * supplied collection reads it, directly or through a live-query Collection.
13 * A StrictMode double render requests the first window once, after commit,
14 * and its first commit is a loading, unpublished window. The hook matches
15 * useLiveQuery under the same history in every case.
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 `starts no acquisition attempt for a render that never commits, as useLiveQuery does (%o)`,
216 async ({ form, wrapped }) => {
217 const reference = await acquisitionsForAbandonedRender(
218 `live`,
219 form,
220 wrapped,
221 )
222 expect(reference).toBe(0)
223 expect(
224 await acquisitionsForAbandonedRender(`infinite`, form, wrapped),
225 ).toBe(reference)
226 },
227 )
228​
229 it(`requests the first window and commits the first value as useLiveQuery does across a StrictMode double render`, async () => {
230 const reference = await firstWindowLoadsForStrictMount(`live`)
231 // No provider work before commit: the on-demand window is unpublished.
232 expect(reference.firstCommit).toEqual({ status: `loading`, ids: [] })
233 // React 19 keeps refs across the double render, so both hooks request the
234 // first window once, after commit. React 18 does not; see the coverage map.
235 expect(reference.loads).toBe(1)
236 expect(await firstWindowLoadsForStrictMount(`infinite`)).toEqual(reference)
237 })
238​
239 it.each([`live`, `infinite`] as const)(
240 `delivers a mounted replacement's startup error to the error boundary (%s)`,
241 async (hook) => {
242 const source = makeSyncSource(4)
243 const failure = new Error(`replacement failed to start`)
244 const commits: Array<{ fail: boolean; status: string }> = []
245 const consoleError = vi
246 .spyOn(console, `error`)
247 .mockImplementation(() => {})
248 function View({ fail }: { fail: boolean }): ReactNode {
249 const query = (q: any) =>
250 q
251 .from({ items: source })
252 .fn.where(() => {
253 if (fail) throw failure
254 return true
255 })
256 .orderBy(({ items }: any) => items.rank, `desc`)
257 const result: any =
258 hook === `live`
259 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1), [fail])
260 : useLiveInfiniteQuery(query, {
261 pageSize: PAGE_SIZE,
262 queryKey: [`startup-error`, fail],
263 })
264 useLayoutEffect(() => {
265 commits.push({ fail, status: result.status })
266 })
267 return null
268 }
269 try {
270 const view = render(
271 <ErrorBoundary>
272 <View fail={false} />
273 </ErrorBoundary>,
274 )
275 cleanups.push(() => view.unmount())
276 await waitFor(() =>
277 expect(commits.at(-1)).toEqual({ fail: false, status: `ready` }),
278 )
279 await act(async () => {
280 view.rerender(
281 <ErrorBoundary>
282 <View fail={true} />
283 </ErrorBoundary>,
284 )
285 })
286 // The error reaches the boundary; the replacement never commits.
287 expect(
288 view.getByText(`Rejected: replacement failed to start`),
289 ).toBeDefined()
290 expect(commits.filter((commit) => commit.fail)).toEqual([])
291 } finally {
292 consoleError.mockRestore()
293 }
294 },
295 )
296})
297​
298describe(`retries after GC`, () => {
299 beforeEach(() => vi.useFakeTimers())
300 afterEach(() => vi.useRealTimers())
301​
302 it(`shows the ready first page when a Suspense retry follows a GC-collected abandoned render`, async () => {
303 const source = makeSyncSource(10)
304 let suspend = true
305 let release!: () => void
306 const gate = new Promise<void>((resolve) => {
307 release = resolve
308 })
309 const commits: Array<{ status: string; ids: Array<string> }> = []
310 let abandonedCollection: { status: string } | undefined
311 let retryCollection: { status: string } | undefined
312​
313 function Query(): ReactNode {
314 const result = useLiveInfiniteQuery(
315 (q) =>
316 q.from({ items: source }).orderBy(({ items }) => items.rank, `desc`),
317 { pageSize: 3 },
318 )
319 if (suspend) {
320 abandonedCollection = result.collection as unknown as {
321 status: string
322 }
323 throw gate
324 }
325 retryCollection = result.collection as unknown as { status: string }
326 useLayoutEffect(() => {
327 commits.push({
328 status: result.status,
329 ids: result.data.map((row) => row.id),
330 })
331 })
332 return null
333 }
334​
335 const view = render(
336 <Suspense fallback={null}>
337 <Query />
338 </Suspense>,
339 )
340 cleanups.push(() => view.unmount())
341 // Let the 50 ms unsubscribed GC floor reclaim the abandoned collection.
342 await act(async () => {
343 await vi.advanceTimersByTimeAsync(100)
344 })
345​
346 suspend = false
347 await act(async () => {
348 release()
349 await vi.advanceTimersByTimeAsync(0)
350 })
351​
352 expect(abandonedCollection?.status).toBe(`cleaned-up`)
353 expect(retryCollection).not.toBe(abandonedCollection)
354 expect(commits[0]).toEqual({ status: `ready`, ids: [`1`, `2`, `3`] })
355 })
356​
357 it(`shows the ready first page when a mounted query's suspended update retries after GC`, async () => {
358 // A committed component keeps its hook refs across a suspended update. A
359 // retry that bound the update's collection after GC cleaned it up would
360 // commit an empty cleaned-up page before recovering.
361 const source = makeSyncSource(10)
362 let suspend = false
363 let release!: () => void
364 const gate = new Promise<void>((resolve) => {
365 release = resolve
366 })
367 const commits: Array<{
368 minimum: number
369 status: string
370 ranks: Array<number>
371 }> = []
372​
373 function Query({ minimum }: { minimum: number }): ReactNode {
374 const result = useLiveInfiniteQuery(
375 (q) =>
376 q
377 .from({ items: source })
378 .where(({ items }) => gt(items.rank, minimum))
379 .orderBy(({ items }) => items.rank, `desc`),
380 { pageSize: 3 },
381 [minimum],
382 )
383 useLayoutEffect(() => {
384 commits.push({
385 minimum,
386 status: result.status,
387 ranks: result.data.map((row) => row.rank),
388 })
389 })
390 if (suspend) throw gate
391 return null
392 }
393​
394 const view = render(
395 <Suspense fallback={null}>
396 <Query minimum={0} />
397 </Suspense>,
398 )
399 cleanups.push(() => view.unmount())
400 await act(async () => {
401 await vi.advanceTimersByTimeAsync(0)
402 })
403​
404 suspend = true
405 await act(async () => {
406 view.rerender(
407 <Suspense fallback={null}>
408 <Query minimum={5} />
409 </Suspense>,
410 )
411 await vi.advanceTimersByTimeAsync(0)
412 })
413 await act(async () => {
414 await vi.advanceTimersByTimeAsync(200)
415 })
416​
417 suspend = false
418 await act(async () => {
419 release()
420 await vi.advanceTimersByTimeAsync(0)
421 })
422​
423 expect(commits.find((commit) => commit.minimum === 5)).toEqual({
424 minimum: 5,
425 status: `ready`,
426 ranks: [10, 9, 8],
427 })
428 })
429})
430​
431describe(`agreement with useLiveQuery`, () => {
432 it(`commits the same ready rows first as useLiveQuery for a synchronous source`, async () => {
433 const source = makeSyncSource(10)
434 const firstCommit = (
435 useResult: () => { status: string; data: Array<Row> },
436 ) => {
437 const commits: Array<{ status: string; ids: Array<string> }> = []
438 const hook = renderHook(() => {
439 const result = useResult()
440 useLayoutEffect(() => {
441 commits.push({
442 status: result.status,
443 ids: result.data.map((row) => row.id),
444 })
445 })
446 return result
447 })
448 cleanups.push(() => hook.unmount())
449 return commits
450 }
451​
452 const live = firstCommit(() =>
453 useLiveQuery((q) =>
454 q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
455 ),
456 )
457 const infinite = firstCommit(() =>
458 useLiveInfiniteQuery(
459 (q) => q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
460 { pageSize: 20 },
461 ),
462 )
463 await waitFor(() => expect(infinite.length).toBeGreaterThan(0))
464​
465 const expected = { status: `ready`, ids: rows(10).map((row) => row.id) }
466 expect(live[0]).toEqual(expected)
467 expect(infinite[0]).toEqual(expected)
468 })
469})
470​
471describe(`collections kept from an abandoned render`, () => {
472 // An eager source that writes `current` each time its sync run starts, so a
473 // restart after cleanup serves new rows from the same source object.
474 function makeRestartableSource(initial: Array<Row>) {
475 let current = initial
476 const source = createCollection<Row>({
477 id: `infinite-render-cuts-restartable-${sequence++}`,
478 getKey: (row) => row.id,
479 autoIndex: `eager`,
480 defaultIndexType: BTreeIndex,
481 startSync: true,
482 sync: {
483 sync: ({ begin, write, commit, markReady }) => {
484 begin()
485 for (const row of current) write({ type: `insert`, value: row })
486 commit()
487 markReady()
488 },
489 },
490 })
491 cleanups.push(() => source.cleanup())
492 return {
493 source,
494 restartWith: async (next: Array<Row>) => {
495 await source.cleanup()
496 current = next
497 source.startSyncImmediate()
498 },
499 }
500 }
501 const byId = (ids: Array<number>): Array<Row> =>
502 ids.map((id) => ({ id: String(id), label: `row-${id}`, rank: id }))
503​
504 it.each([`live`, `infinite`] as const)(
505 `shows the restarted source's rows when an abandoned render's query is selected again (%s)`,
506 async (hook) => {
507 // Model: after the restart the source holds ids 4-8, so the query for
508 // ranks above 2, ascending, shows ids 4 and 5 on its first page.
509 const { source, restartWith } = makeRestartableSource(
510 byId([1, 2, 3, 4, 5]),
511 )
512 const never = new Promise<void>(() => {})
513 const commits: Array<{
514 minimum: number
515 status: string
516 ids: Array<string>
517 }> = []
518 function Query({
519 minimum,
520 suspend,
521 }: {
522 minimum: number
523 suspend: boolean
524 }): ReactNode {
525 const query = (q: any) =>
526 q
527 .from({ items: source })
528 .where(({ items }: any) => gt(items.rank, minimum))
529 .orderBy(({ items }: any) => items.rank, `asc`)
530 const result: any =
531 hook === `live`
532 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1))
533 : useLiveInfiniteQuery(query, { pageSize: PAGE_SIZE })
534 useLayoutEffect(() => {
535 commits.push({
536 minimum,
537 status: result.status,
538 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
539 })
540 })
541 if (suspend) throw never
542 return null
543 }
544 const tree = (minimum: number, suspend: boolean) => (
545 <Suspense fallback={null}>
546 <Query minimum={minimum} suspend={suspend} />
547 </Suspense>
548 )
549 const view = render(tree(0, false))
550 cleanups.push(() => view.unmount())
551 await act(async () => {})
552 // Render B and abandon it, then commit A again.
553 act(() => view.rerender(tree(2, true)))
554 act(() => view.rerender(tree(0, false)))
555 await act(async () => restartWith(byId([4, 5, 6, 7, 8])))
556 commits.length = 0
557 act(() => view.rerender(tree(2, false)))
558 await act(async () => {
559 await new Promise((resolve) => setTimeout(resolve, 0))
560 })
561​
562 expect(commits.filter((commit) => commit.minimum === 2).at(-1)).toEqual({
563 minimum: 2,
564 status: `ready`,
565 ids: [`4`, `5`],
566 })
567 },
568 )
569})