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

source-id-reuse-oracle.test.tsx

576 lines18.6 KB

1/**
2 * Source ID reuse contract for React's derived live-query identity.
3 *
4 * A Collection ID names one source object for the lifetime of a mounted
5 * derived-identity hook in one DbClient scope. Re-rendering that hook with a different object under
6 * the same ID must reject before it can return rows from the old source.
7 * Unmounting and cleaning up the old scope permits the ID in a new hook. Two
8 * independent client scopes may use the same ID at the same time.
9 *
10 * Model: each mounted hook remembers the source object first seen for an ID
11 * in each client scope. Same object and fresh ID transitions are legal. A
12 * different object for a remembered ID is rejected. A new hook starts a new
13 * model; switching clients selects that client's remembered bindings.
14 * A render that starts a live query claims its source before a descendant
15 * suspends, because the live query may still own that source until cleanup.
16 * Separate hooks can use same-ID objects: their client-scoped Suspense cache
17 * entries must remain distinct, including before the first hook commits.
18 * A rejected render must release any sync-start deferral it acquired for a
19 * shared client descriptor, so a later direct reader can start that Collection.
20 * This remains true when earlier deferred sync starts throw: each pending
21 * Collection is attempted before the first startup error is rethrown.
22 * The bounded histories below distinguish this law from a hash-only check,
23 * which would miss A(id=x) -> C(id=y) -> B(id=x), a changed predicate, and
24 * two different same-ID sources in one query.
25 *
26 * Driver and observation: render the public hook, then rerender it with each
27 * source. At the rerender boundary, compare a thrown error or the public row.
28 * This does not assert a process-wide Collection registry, legacy dependency
29 * arrays, or explicit-key semantics; explicit queryKey callers own their key.
30 */
31import { act, render, renderHook, waitFor } from '@testing-library/react'
32import {
33 DbClient,
34 collectionOptions,
35 createCollection,
36 eq,
37 gt,
38} from '@tanstack/db'
39import { describe, expect, it, vi } from 'vitest'
40import { Component, Suspense } from 'react'
41import { DbProvider } from '../src/DbProvider'
42import { useLiveQuery } from '../src/useLiveQuery'
43import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
44import { mockSyncCollectionOptions } from '../../db/tests/utils'
45import type { Context, QueryBuilder } from '@tanstack/db'
46import type { ReactNode } from 'react'
47​
48type Row = { id: string; value: string; rank: number }
49​
50class TestErrorBoundary extends Component<
51 { children: ReactNode },
52 { error?: Error }
53> {
54 state: { error?: Error } = {}
55​
56 static getDerivedStateFromError(error: Error) {
57 return { error }
58 }
59​
60 render() {
61 return this.state.error ? <div>Rejected</div> : this.props.children
62 }
64​
65function source(id: string, value: string) {
66 return createCollection(
67 mockSyncCollectionOptions<Row>({
68 id,
69 getKey: (row) => row.id,
70 initialData: [{ id: `one`, value, rank: 1 }],
71 }),
72 )
74​
75type Binding = { source: ReturnType<typeof source>; client?: DbClient }
76​
77// A prior source with the same ID in this client scope forbids a new object.
78// Pairwise history comparison is independent of the hook's token maps.
79function expectedCollision(history: ReadonlyArray<Binding>, next: Binding) {
80 return history.some(
81 (prior) =>
82 prior.client === next.client &&
83 prior.source.id === next.source.id &&
84 prior.source !== next.source,
85 )
87​
88function checkRerender(
89 history: ReadonlyArray<Binding>,
90 next: Binding,
91 rerender: () => void,
92) {
93 if (expectedCollision(history, next)) {
94 expect(rerender).toThrow(/source Collection .*same ID/i)
95 } else {
96 expect(rerender).not.toThrow()
97 }
99​
100describe(`React source ID reuse`, () => {
101 it(`releases a later shared source when earlier deferred sync starts fail`, async () => {
102 const client = new DbClient()
103 const first = source(`settings`, `first`)
104 const replacement = source(`settings`, `replacement`)
105 const failedStarts: [number, number] = [0, 0]
106 const failing = ([0, 1] as const).map((index) =>
107 collectionOptions(`failing-${index}`, () => ({
108 id: `failing-${index}`,
109 getKey: (row: Row) => row.id,
110 startSync: true,
111 sync: {
112 sync: () => {
113 failedStarts[index]++
114 throw new Error(`sync ${index} failed`)
115 },
116 },
117 })),
118 )
119 let healthyStarts = 0
120 const healthy = collectionOptions(`healthy-after-failures`, () => ({
121 id: `healthy-after-failures`,
122 getKey: (row: Row) => row.id,
123 startSync: true,
124 sync: {
125 sync: ({ begin, write, commit, markReady }) => {
126 healthyStarts++
127 begin()
128 write({
129 type: `insert`,
130 value: { id: `one`, value: `healthy`, rank: 1 },
131 })
132 commit()
133 markReady()
134 },
135 },
136 }))
137 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
138​
139 function View({
140 current,
141 include,
142 }: {
143 current: typeof first
144 include: boolean
145 }) {
146 useLiveQuery({
147 client,
148 query: (q): QueryBuilder<Context> =>
149 include
150 ? q
151 .from({ failingA: failing[0]! })
152 .join({ failingB: failing[1]! }, ({ failingA, failingB }) =>
153 eq(failingA.id, failingB.id),
154 )
155 .join({ healthy }, ({ failingA, healthy }) =>
156 eq(failingA.id, healthy.id),
157 )
158 .join({ settings: current }, ({ failingA, settings }) =>
159 eq(failingA.id, settings.id),
160 )
161 : q.from({ settings: current }),
162 })
163 return <div>Query</div>
164 }
165​
166 try {
167 const root = render(
168 <TestErrorBoundary>
169 <View current={first} include={false} />
170 </TestErrorBoundary>,
171 )
172 await act(async () => {})
173 root.rerender(
174 <TestErrorBoundary>
175 <View current={replacement} include={true} />
176 </TestErrorBoundary>,
177 )
178 expect(root.getByText(`Rejected`)).toBeDefined()
179 expect(failedStarts).toEqual([1, 1])
180​
181 const shared = client.collection(healthy)
182 const reader = renderHook(() => useLiveQuery(shared))
183 await act(async () => {})
184 expect(reader.result.current.status).toBe(`ready`)
185 expect(reader.result.current.data[0]?.value).toBe(`healthy`)
186 expect(healthyStarts).toBe(1)
187 } finally {
188 consoleError.mockRestore()
189 }
190 })
191​
192 it(`releases a shared descriptor's sync deferral when a collision tears down the hook`, async () => {
193 const client = new DbClient()
194 const first = source(`settings`, `first`)
195 const replacement = source(`settings`, `replacement`)
196 let syncStarts = 0
197 const descriptor = collectionOptions(`shared-after-collision`, () => ({
198 id: `shared-after-collision`,
199 getKey: (row: Row) => row.id,
200 sync: {
201 sync: ({ begin, write, commit, markReady }) => {
202 syncStarts++
203 begin()
204 write({
205 type: `insert`,
206 value: { id: `one`, value: `shared`, rank: 1 },
207 })
208 commit()
209 markReady()
210 },
211 },
212 }))
213 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
214​
215 function View({
216 current,
217 includeShared,
218 }: {
219 current: typeof first
220 includeShared: boolean
221 }) {
222 useLiveQuery({
223 client,
224 query: (q) =>
225 includeShared
226 ? q
227 .from({ settings: current })
228 .join({ shared: descriptor }, ({ settings, shared }) =>
229 eq(settings.id, shared.id),
230 )
231 : q.from({ settings: current }),
232 })
233 return <div>Query</div>
234 }
235​
236 try {
237 const root = render(
238 <TestErrorBoundary>
239 <View current={first} includeShared={false} />
240 </TestErrorBoundary>,
241 )
242 await act(async () => {})
243 root.rerender(
244 <TestErrorBoundary>
245 <View current={replacement} includeShared={true} />
246 </TestErrorBoundary>,
247 )
248 expect(root.getByText(`Rejected`)).toBeDefined()
249 expect(syncStarts).toBe(0)
250​
251 const shared = client.collection(descriptor)
252 const reader = renderHook(() => useLiveQuery(shared))
253 await act(async () => {})
254 expect(reader.result.current.status).toBe(`ready`)
255 expect(reader.result.current.data[0]?.value).toBe(`shared`)
256 expect(syncStarts).toBe(1)
257 } finally {
258 consoleError.mockRestore()
259 }
260 })
261​
262 it(`rejects a different active source with the same ID before exposing stale rows`, async () => {
263 const first = source(`settings`, `first`)
264 const second = source(`settings`, `second`)
265 const hook = renderHook(
266 ({ current }) =>
267 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
268 { initialProps: { current: first } },
269 )
270​
271 await waitFor(() =>
272 expect(hook.result.current.data[0]?.value).toBe(`first`),
273 )
274 checkRerender([{ source: first }], { source: second }, () =>
275 hook.rerender({ current: second }),
276 )
277 })
278​
279 it(`rejects a previously used ID after another source and a query change`, async () => {
280 const first = source(`settings`, `first`)
281 const other = source(`other`, `other`)
282 const second = source(`settings`, `second`)
283 const hook = renderHook(
284 ({ current, minimum }) =>
285 useLiveQuery({
286 query: (q) =>
287 q
288 .from({ settings: current })
289 .where(({ settings }) => gt(settings.rank, minimum)),
290 }),
291 { initialProps: { current: first, minimum: 0 } },
292 )
293​
294 await waitFor(() =>
295 expect(hook.result.current.data[0]?.value).toBe(`first`),
296 )
297 act(() => hook.rerender({ current: other, minimum: 0 }))
298 await waitFor(() =>
299 expect(hook.result.current.data[0]?.value).toBe(`other`),
300 )
301 checkRerender(
302 [{ source: first }, { source: other }],
303 { source: second },
304 () => hook.rerender({ current: second, minimum: -1 }),
305 )
306 })
307​
308 it(`accepts the same source object and a different source ID`, async () => {
309 const first = source(`settings`, `first`)
310 const other = source(`other`, `other`)
311 const hook = renderHook(
312 ({ current }) =>
313 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
314 { initialProps: { current: first } },
315 )
316​
317 await waitFor(() =>
318 expect(hook.result.current.data[0]?.value).toBe(`first`),
319 )
320 checkRerender([{ source: first }], { source: first }, () =>
321 hook.rerender({ current: first }),
322 )
323 expect(hook.result.current.data[0]?.value).toBe(`first`)
324 checkRerender([{ source: first }], { source: other }, () =>
325 hook.rerender({ current: other }),
326 )
327 await waitFor(() =>
328 expect(hook.result.current.data[0]?.value).toBe(`other`),
329 )
330 })
331​
332 it(`rejects two distinct source objects with one ID in a single query`, () => {
333 const leftSource = source(`settings`, `first`)
334 const rightSource = source(`settings`, `second`)
335 expect(() =>
336 renderHook(() =>
337 useLiveQuery({
338 query: (q) =>
339 q
340 .from({ first: leftSource })
341 .join({ second: rightSource }, ({ first, second }) =>
342 eq(first.id, second.id),
343 ),
344 }),
345 ),
346 ).toThrow(/source Collection .*same ID/i)
347 })
348​
349 it(`keeps a mounted hook's ID binding after source cleanup`, async () => {
350 const first = source(`settings`, `first`)
351 const second = source(`settings`, `second`)
352 const hook = renderHook(
353 ({ current }) =>
354 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
355 { initialProps: { current: first } },
356 )
357 await waitFor(() =>
358 expect(hook.result.current.data[0]?.value).toBe(`first`),
359 )
360 await act(async () => first.cleanup())
361 checkRerender([{ source: first }], { source: second }, () =>
362 hook.rerender({ current: second }),
363 )
364 })
365​
366 it(`permits the same ID in a new hook after unmount and cleanup`, async () => {
367 const first = source(`settings`, `first`)
368 const oldHook = renderHook(() =>
369 useLiveQuery({ query: (q) => q.from({ settings: first }) }),
370 )
371 await waitFor(() =>
372 expect(oldHook.result.current.data[0]?.value).toBe(`first`),
373 )
374 const oldQuery = oldHook.result.current.collection
375 oldHook.unmount()
376 await waitFor(() => expect(oldQuery.status).toBe(`cleaned-up`))
377 await first.cleanup()
378​
379 const second = source(`settings`, `second`)
380 const newHook = renderHook(() =>
381 useLiveQuery({ query: (q) => q.from({ settings: second }) }),
382 )
383 await waitFor(() =>
384 expect(newHook.result.current.data[0]?.value).toBe(`second`),
385 )
386 })
387​
388 it(`permits independent client scopes to use the same ID`, async () => {
389 const firstClient = new DbClient()
390 const secondClient = new DbClient()
391 const first = source(`settings`, `first`)
392 const second = source(`settings`, `second`)
393 const firstHook = renderHook(() =>
394 useLiveQuery({
395 client: firstClient,
396 query: (q) => q.from({ settings: first }),
397 }),
398 )
399 const secondHook = renderHook(() =>
400 useLiveQuery({
401 client: secondClient,
402 query: (q) => q.from({ settings: second }),
403 }),
404 )
405​
406 await waitFor(() => {
407 expect(firstHook.result.current.data[0]?.value).toBe(`first`)
408 expect(secondHook.result.current.data[0]?.value).toBe(`second`)
409 })
410 })
411​
412 it(`keeps separate client-scoped Suspense hooks bound to their own sources`, async () => {
413 const client = new DbClient()
414 const first = source(`settings`, `first`)
415 const second = source(`settings`, `second`)
416 const View = ({ current }: { current: typeof first }) => {
417 const { data } = useLiveSuspenseQuery({
418 client,
419 query: (q) => q.from({ settings: current }),
420 })
421 return <div>{data[0]?.value}</div>
422 }
423 const firstView = render(
424 <Suspense fallback={<div>First loading</div>}>
425 <View current={first} />
426 </Suspense>,
427 )
428 await waitFor(() => expect(firstView.getByText(`first`)).toBeDefined())
429 const secondView = render(
430 <Suspense fallback={<div>Second loading</div>}>
431 <View current={second} />
432 </Suspense>,
433 )
434 await waitFor(() => expect(secondView.getByText(`second`)).toBeDefined())
435 })
436​
437 it(`keeps a client-scoped Suspense retry bound to its new source`, async () => {
438 const client = new DbClient()
439 const first = source(`settings`, `first`)
440 const second = source(`settings`, `second`)
441 const never = new Promise<void>(() => {})
442 const View = ({
443 current,
444 suspend,
445 }: {
446 current: typeof first
447 suspend: boolean
448 }) => {
449 const { data } = useLiveSuspenseQuery({
450 client,
451 query: (q) => q.from({ settings: current }),
452 })
453 if (suspend) throw never
454 return <div>{data[0]?.value}</div>
455 }
456 const root = render(
457 <Suspense fallback={<div>Loading</div>}>
458 <View current={first} suspend={true} />
459 </Suspense>,
460 )
461 expect(root.getByText(`Loading`)).toBeDefined()
462 root.rerender(
463 <Suspense fallback={<div>Loading</div>}>
464 <View current={second} suspend={false} />
465 </Suspense>,
466 )
467 await waitFor(() => expect(root.getByText(`second`)).toBeDefined())
468 })
469​
470 it(`remembers IDs across DbProvider client switches`, async () => {
471 const firstClient = new DbClient()
472 const secondClient = new DbClient()
473 const first = source(`settings`, `first`)
474 const otherScope = source(`settings`, `other`)
475 const replacement = source(`settings`, `replacement`)
476 const View = ({ current }: { current: typeof first }) => {
477 const { data } = useLiveQuery({
478 query: (q) => q.from({ settings: current }),
479 })
480 return <div>{data[0]?.value}</div>
481 }
482 const root = render(
483 <DbProvider client={firstClient}>
484 <View current={first} />
485 </DbProvider>,
486 )
487 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
488 root.rerender(
489 <DbProvider client={secondClient}>
490 <View current={otherScope} />
491 </DbProvider>,
492 )
493 await waitFor(() => expect(root.getByText(`other`)).toBeDefined())
494 expect(() =>
495 root.rerender(
496 <DbProvider client={firstClient}>
497 <View current={replacement} />
498 </DbProvider>,
499 ),
500 ).toThrow(/source Collection .*same ID/i)
501 })
502​
503 it(`remembers each client scope when one mounted hook switches clients`, async () => {
504 const firstClient = new DbClient()
505 const secondClient = new DbClient()
506 const first = source(`settings`, `first`)
507 const otherScope = source(`settings`, `other`)
508 const replacement = source(`settings`, `replacement`)
509 const hook = renderHook(
510 ({ client, current }) =>
511 useLiveQuery({
512 client,
513 query: (q) => q.from({ settings: current }),
514 }),
515 { initialProps: { client: firstClient, current: first } },
516 )
517​
518 await waitFor(() =>
519 expect(hook.result.current.data[0]?.value).toBe(`first`),
520 )
521 hook.rerender({ client: secondClient, current: otherScope })
522 await waitFor(() =>
523 expect(hook.result.current.data[0]?.value).toBe(`other`),
524 )
525 checkRerender(
526 [
527 { source: first, client: firstClient },
528 { source: otherScope, client: secondClient },
529 ],
530 { source: replacement, client: firstClient },
531 () => hook.rerender({ client: firstClient, current: replacement }),
532 )
533 })
534​
535 it(`rejects same-ID reuse after a suspended render starts a source query`, async () => {
536 const first = source(`first`, `first`)
537 const abandoned = source(`candidate`, `abandoned`)
538 const replacement = source(`candidate`, `replacement`)
539 const never = new Promise<void>(() => {})
540 const View = ({
541 current,
542 suspend,
543 }: {
544 current: typeof first
545 suspend: boolean
546 }) => {
547 const { data } = useLiveQuery({
548 query: (q) => q.from({ settings: current }),
549 })
550 if (suspend) throw never
551 return <div>{data[0]?.value}</div>
552 }
553 const root = render(
554 <Suspense fallback={<div>Loading</div>}>
555 <View current={first} suspend={false} />
556 </Suspense>,
557 )
558 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
559​
560 root.rerender(
561 <Suspense fallback={<div>Loading</div>}>
562 <View current={abandoned} suspend={true} />
563 </Suspense>,
564 )
565 checkRerender(
566 [{ source: first }, { source: abandoned }],
567 { source: replacement },
568 () =>
569 root.rerender(
570 <Suspense fallback={<div>Loading</div>}>
571 <View current={replacement} suspend={false} />
572 </Suspense>,
573 ),
574 )
575 })
576})