Open History to see the last commit
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 * The release history grammar crosses every rejection cause (a source ID
21 * collision, a query without a stable IR identity, a descriptor factory that
22 * throws while the query binds its sources, a query the live query rejects
23 * when it compiles, a single-result query in an infinite hook, which pages
24 * many rows, a sibling that
25 * throws after the hook returns, and a render that suspends and never
26 * commits), every hook
27 * path (live, infinite and Suspense, derived and explicit queryKey forms),
28 * initial rejected mounts or rejected rerenders, and four direct readers
29 * (another hook, preload, a subscription and startSyncImmediate()). The
30 * release must also hold when earlier deferred sync starts throw: each pending
31 * Collection is attempted before the first startup error is rethrown.
32 * The bounded histories below distinguish this law from a hash-only check,
33 * which would miss A(id=x) -> C(id=y) -> B(id=x), a changed predicate, and
34 * two different same-ID sources in one query.
35 *
36 * Driver and observation: render the public hook, then rerender it with each
37 * source. At the rerender boundary, compare a thrown error or the public row.
38 * A nonempty queryKey owns its identity, so a keyed query skips the claim: a
39 * same-ID swap under a changed key reads the new source. The release grammar
40 * below runs explicit-key hook paths for rejection causes that remain valid. This does not assert a
41 * process-wide Collection registry or other explicit-key semantics.
42 */
43
44import {
45 act,
46 cleanup as cleanupReact,
47 render,
48 renderHook,
49 waitFor,
50} from '@testing-library/react'
51import {
52 DbClient,
53 SourceCollectionIdReuseError,
54 UnhashableQueryIRError,
55 UnsupportedRootScalarSelectError,
56 collectionOptions,
57 eq,
58 gt,
59} from '@tanstack/db'
60import { describe, expect, it, vi } from 'vitest'
61import { Suspense } from 'react'
62import { DbProvider } from '../src/DbProvider'
63import { useLiveQuery } from '../src/useLiveQuery'
64import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
65import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
66import { declareOracle } from '../../db/tests/oracle-declaration'
67import { createOracleReach } from '../../db/tests/oracle-reach'
68import {
69 boundOptionHistories,
70 captureBoundOptions,
71 checkBoundOptions,
72} from '../../db/tests/live-query-bound-options-oracle'
73import { withOracleCleanup } from '../../db/tests/utils'
74import { TestErrorBoundary, source } from './source-id-reuse-support'
75import type {
76 Collection,
77 InitialQueryBuilder,
78 NonSingleResult,
79} from '@tanstack/db'
80import type { Row } from './source-id-reuse-support'
81
82/**
83 * A render may allocate getKey/schema closures without changing the query.
84 * Maintainer decision: options bind until the query or explicit queryKey changes.
85 * This finite host grammar crosses both config-object hooks, each option and both identity
86 * changes. It observes Collection/config references, keys and rows after normal
87 * renders, a source update and identity replacement. A render budget catches a
88 * loop. React is the real receiving host; other frameworks are not claimed here.
89 */
90
91it.each(
92 [`live`, `suspense`].flatMap((hook) =>
93 boundOptionHistories.map((history) => ({ hook, ...history })),
94 ),
95)(
96 `retains inline options until identity changes: %j`,
97 async ({ hook, option, identity }) => {
98 const rows = source(
99 `inline-options-${hook}-${option}-${identity}`,
100 `before`,
101 )
102 let renders = 0
103 const reach = createOracleReach(`inline options ${hook}`, [
104 `rerender`,
105 `source-update`,
106 `identity-change`,
107 ])
108 reach.beginHistory()
109 const { result, rerender, unmount } = renderHook(
110 ({ revision }) => {
111 if (++renders > 30)
112 throw new Error(`inline options rebuilt on every render`)
113 const getKey = (row: Row) => row.id
114 const schema = {
115 '~standard': {
116 version: 1 as const,
117 vendor: `identity-oracle`,
118 validate: (value: unknown) => ({ value: value as Row }),
119 },
120 }
121 const config = {
122 query: (q: InitialQueryBuilder) =>
123 q
124 .from({ row: rows })
125 .where(({ row }) =>
126 gt(row.rank, identity === `query` ? -revision : 0),
127 ),
128 ...(identity === `queryKey` ? { queryKey: [revision] } : {}),
129 ...(option !== `schema` ? { getKey } : {}),
130 }
131 // Exercise schema at the JavaScript config boundary: its current
132 // public TS declaration is `never`, independently of runtime identity.
133 if (option !== `getKey`) Object.assign(config, { schema })
134 if (hook === `suspense`) return useLiveSuspenseQuery(config)
135 return useLiveQuery(config)
136 },
137 { initialProps: { revision: 0 } },
138 )
139 const collections = new Set<{ cleanup: () => Promise<void> }>()
140 await withOracleCleanup(async () => {
141 await waitFor(() =>
142 expect(result.current.collection.status).toBe(`ready`),
143 )
144 const initial = result.current.collection
145 const initialBinding = captureBoundOptions(initial)
146 collections.add(initial)
147 for (let turn = 0; turn < 3; turn++) {
148 rerender({ revision: 0 })
149 // Absent options have no binding to compare; the Collection still must stay.
150 checkBoundOptions(
151 initialBinding,
152 result.current.collection,
153 false,
154 option,
155 )
156 expect(result.current.data.map((row) => row.id)).toEqual([`one`])
157 reach.reach(`rerender`)
158 }
159 act(() => {
160 rows.utils.begin()
161 rows.utils.write({
162 type: `update`,
163 value: { id: `one`, value: `after`, rank: 1 },
164 })
165 rows.utils.commit()
166 })
167 expect(result.current.data[0]?.value).toBe(`after`)
168 expect(result.current.collection).toBe(initial)
169 checkBoundOptions(
170 initialBinding,
171 result.current.collection,
172 false,
173 option,
174 )
175 reach.reach(`source-update`)
176 rerender({ revision: 1 })
177 collections.add(result.current.collection)
178 await waitFor(() =>
179 expect(result.current.collection.status).toBe(`ready`),
180 )
181 // The comparison judges only configured options; absent options may be
182 // synthesized by the Collection and have no user binding contract.
183 expect(result.current.collection).not.toBe(initial)
184 checkBoundOptions(initialBinding, result.current.collection, true, option)
185 expect(result.current.data.map((row) => row.id)).toEqual([`one`])
186 reach.reach(`identity-change`)
187 reach.assertReached()
188 }, [
189 () => unmount(),
190 () =>
191 withOracleCleanup(() => {}, [
192 ...[...collections].map((collection) => () => collection.cleanup()),
193 () => rows.cleanup({ dependents: true }),
194 ]),
195 ])
196 },
197)
198
199type Binding = { source: ReturnType<typeof source>; client?: DbClient }
200
201// A prior source with the same ID in this client scope forbids a new object.
202// Pairwise history comparison is independent of the hook's token maps.
203function expectedCollision(history: ReadonlyArray<Binding>, next: Binding) {
204 return history.some(
205 (prior) =>
206 prior.client === next.client &&
207 prior.source.id === next.source.id &&
208 prior.source !== next.source,
209 )
210}
211
212function checkRerender(
213 history: ReadonlyArray<Binding>,
214 next: Binding,
215 rerender: () => void,
216) {
217 if (expectedCollision(history, next)) {
218 expect(rerender).toThrow(SourceCollectionIdReuseError)
219 } else {
220 expect(rerender).not.toThrow()
221 }
222}
223
224declareOracle({
225 check: [checkRerender, checkReleaseHistory, checkBoundOptions],
226 model: [expectedCollision],
227 grammar: [boundOptionHistories],
228})
229
230/*
231 * Release law. A hook in one DbClient scope first reads only its own source,
232 * then rerenders into a rejected query that also reads a shared descriptor.
233 * The rejected render may defer the shared Collection's sync start, and it
234 * must release that deferral: the source stays unstarted until a direct
235 * reader asks, and that reader then starts it exactly once and reads its row.
236 *
237 * Declared reach: every enumerated history must enter the state the law is
238 * about, a rejected render that materialized the shared descriptor. Each cell
239 * asserts that the descriptor factory ran once before the reader, so a
240 * history that rejects before binding the shared source fails instead of
241 * passing vacuously.
242 */
243type ReleaseStep = { current: ReturnType<typeof source>; reject: boolean }
244
245const releaseCauses: Record<
246 string,
247 (
248 shared: any,
249 failing: any,
250 failures?: { factory: Error; sibling: Error },
251 ) => {
252 matchesRejection?: (error: unknown) => boolean
253 rejected: (step: ReleaseStep) => ReleaseStep
254 query: (q: any, step: ReleaseStep, ordered: boolean) => any
255 /** Which hook paths the cause rejects in; all of them by default. */
256 rejectsIn?: (hook: ReleaseHook) => boolean
257 /** A source collision requires a prior mounted claim. */
258 requiresPriorClaim?: boolean
259 /**
260 * What the component does after the hook returns in the rejected step:
261 * throw to an error boundary, or suspend on a promise that never settles.
262 * Either way the render never commits; the hook itself rejected nothing.
263 */
264 afterHook?: `throw` | `suspend`
265 }
266> = {
267 'a source ID collision': (shared) => ({
268 matchesRejection: (error) => error instanceof SourceCollectionIdReuseError,
269 requiresPriorClaim: true,
270 rejectsIn: (hook) => !hook.keyed,
271 rejected: () => ({
272 current: source(`settings`, `replacement`),
273 reject: true,
274 }),
275 query: (q, step, ordered) =>
276 orderIf(
277 step.reject
278 ? q
279 .from({ settings: step.current })
280 .join({ shared }, ({ settings, shared: row }: any) =>
281 eq(settings.id, row.id),
282 )
283 : q.from({ settings: step.current }),
284 ordered,
285 ),
286 }),
287 'a query without a stable IR identity': (shared) => ({
288 matchesRejection: (error) => error instanceof UnhashableQueryIRError,
289 rejectsIn: (hook) => !hook.keyed,
290 rejected: (step) => ({ ...step, reject: true }),
291 query: (q, step, ordered) =>
292 orderIf(
293 step.reject
294 ? q
295 .from({ settings: step.current })
296 .join({ shared }, ({ settings, shared: row }: any) =>
297 eq(settings.id, row.id),
298 )
299 .fn.where(() => true)
300 : q.from({ settings: step.current }),
301 ordered,
302 ),
303 }),
304 'a descriptor factory that throws': (shared, failing, failures) => ({
305 matchesRejection: (error) => error === failures?.factory,
306 rejected: (step) => ({ ...step, reject: true }),
307 query: (q, step, ordered) =>
308 orderIf(
309 step.reject
310 ? q
311 .from({ settings: step.current })
312 .join({ shared }, ({ settings, shared: row }: any) =>
313 eq(settings.id, row.id),
314 )
315 .join({ failing }, ({ settings, failing: row }: any) =>
316 eq(settings.id, row.id),
317 )
318 : q.from({ settings: step.current }),
319 ordered,
320 ),
321 }),
322 'a query the live query rejects when it compiles': (shared) => ({
323 matchesRejection: (error) =>
324 error instanceof UnsupportedRootScalarSelectError,
325 rejected: (step) => ({ ...step, reject: true }),
326 // A root scalar select is valid IR that compilation refuses.
327 query: (q, step, ordered) =>
328 step.reject
329 ? orderIf(
330 q
331 .from({ settings: step.current })
332 .join({ shared }, ({ settings, shared: row }: any) =>
333 eq(settings.id, row.id),
334 ),
335 ordered,
336 ).select(({ settings }: any) => settings.value)
337 : orderIf(q.from({ settings: step.current }), ordered),
338 }),
339 'a single-result window query': (shared) => ({
340 matchesRejection: (error) =>
341 error instanceof Error &&
342 error.message.includes(
343 `Infinite queries do not support single-result queries`,
344 ),
345 rejected: (step) => ({ ...step, reject: true }),
346 query: (q, step, ordered) => {
347 const query = orderIf(
348 step.reject
349 ? q
350 .from({ settings: step.current })
351 .join({ shared }, ({ settings, shared: row }: any) =>
352 eq(settings.id, row.id),
353 )
354 : q.from({ settings: step.current }),
355 ordered,
356 )
357 return step.reject ? query.findOne() : query
358 },
359 // A live query may read one row; an infinite query must page many.
360 rejectsIn: (hook) => hook.ordered,
361 }),
362 'a sibling that throws after the hook returns': (
363 shared,
364 _failing,
365 failures,
366 ) => ({
367 matchesRejection: (error) => error === failures?.sibling,
368 rejected: (step) => ({ ...step, reject: true }),
369 query: (q, step, ordered) =>
370 orderIf(
371 step.reject
372 ? q
373 .from({ settings: step.current })
374 .join({ shared }, ({ settings, shared: row }: any) =>
375 eq(settings.id, row.id),
376 )
377 : q.from({ settings: step.current }),
378 ordered,
379 ),
380 afterHook: `throw`,
381 // A Suspense hook that returns has already preloaded its query, which
382 // starts its sources, so no deferral is left to release.
383 rejectsIn: (hook) => !hook.suspense,
384 }),
385 'a render that suspends and never commits': (shared) => ({
386 rejected: (step) => ({ ...step, reject: true }),
387 query: (q, step, ordered) =>
388 orderIf(
389 step.reject
390 ? q
391 .from({ settings: step.current })
392 .join({ shared }, ({ settings, shared: row }: any) =>
393 eq(settings.id, row.id),
394 )
395 : q.from({ settings: step.current }),
396 ordered,
397 ),
398 afterHook: `suspend`,
399 // As above: a Suspense hook's own read is a preload.
400 rejectsIn: (hook) => !hook.suspense,
401 }),
402}
403
404function orderIf(query: any, ordered: boolean) {
405 return ordered ? query.orderBy(({ settings }: any) => settings.rank) : query
406}
407
408type ReleaseHook = {
409 ordered: boolean
410 suspense: boolean
411 keyed: boolean
412 use: (query: (q: any) => any, rejectedIdentity: boolean) => void
413}
414
415const releaseHooks: Record<string, ReleaseHook> = {
416 'useLiveQuery with derived identity': {
417 ordered: false,
418 suspense: false,
419 keyed: false,
420 use: (query) => void useLiveQuery(query),
421 },
422
423 'useLiveInfiniteQuery with derived identity': {
424 ordered: true,
425 suspense: false,
426 keyed: false,
427 use: (query) => void useLiveInfiniteQuery(query, { pageSize: 1 }),
428 },
429
430 // A config can turn off the reclaim: gcTime 0 or Infinity disables GC, and
431 // startSync false never arms it. A render that never commits must still
432 // release its deferral.
433 'useLiveQuery with gcTime 0': {
434 ordered: false,
435 suspense: false,
436 keyed: false,
437 use: (query) => void useLiveQuery({ query, gcTime: 0 }),
438 },
439 'useLiveQuery with gcTime Infinity': {
440 ordered: false,
441 suspense: false,
442 keyed: false,
443 use: (query) => void useLiveQuery({ query, gcTime: Infinity }),
444 },
445 'useLiveQuery with startSync false': {
446 ordered: false,
447 suspense: false,
448 keyed: false,
449 use: (query) => void useLiveQuery({ query, startSync: false }),
450 },
451 'useLiveSuspenseQuery with derived identity': {
452 ordered: false,
453 suspense: true,
454 keyed: false,
455 use: (query) => void useLiveSuspenseQuery(query),
456 },
457}
458
459// Explicit keys skip source-ID and derived-IR guards. Factory, compiler,
460// window-shape and abandoned-render failures still owe release on these paths.
461// The key changes with the authored query; a constant key would legally retain
462// the accepted query and never acquire the rejected render's shared descriptor.
463releaseHooks[`useLiveQuery with queryKey`] = {
464 ordered: false,
465 suspense: false,
466 keyed: true,
467 use: (query, rejectedIdentity) =>
468 void useLiveQuery({
469 query,
470 queryKey: [`release-keyed-live`, rejectedIdentity],
471 }),
472}
473releaseHooks[`useLiveInfiniteQuery with queryKey`] = {
474 ordered: true,
475 suspense: false,
476 keyed: true,
477 use: (query, rejectedIdentity) =>
478 void useLiveInfiniteQuery(query, {
479 pageSize: 1,
480 queryKey: [`release-keyed-infinite`, rejectedIdentity],
481 }),
482}
483releaseHooks[`useLiveSuspenseQuery with queryKey`] = {
484 ordered: false,
485 suspense: true,
486 keyed: true,
487 use: (query, rejectedIdentity) =>
488 void useLiveSuspenseQuery({
489 query,
490 queryKey: [`release-keyed-suspense`, rejectedIdentity],
491 }),
492}
493
494type SharedReleaseCollection = Collection<Row, string, {}, never, Row> &
495 NonSingleResult
496type ReleaseObservation = { starts: number; status: string; rows: Array<Row> }
497type ReleaseReader = (shared: SharedReleaseCollection) => {
498 observe: () => Omit<ReleaseObservation, `starts`>
499 ready?: Promise<unknown>
500 dispose?: () => void
501}
502const projectReleaseRows = (rows: ReadonlyArray<Row>) =>
503 rows
504 .map(({ id, value, rank }) => ({ id, value, rank }))
505 .sort((a, b) => a.id.localeCompare(b.id))
506const releaseReaders: Record<string, ReleaseReader> = {
507 'another hook over the Collection': (shared) => {
508 const reader = renderHook(() => useLiveQuery(shared))
509 return {
510 observe: () => ({
511 status: reader.result.current.status,
512 rows: projectReleaseRows(reader.result.current.data),
513 }),
514 dispose: () => reader.unmount(),
515 }
516 },
517 'startSyncImmediate()': (shared) => {
518 shared.startSyncImmediate()
519 return {
520 observe: () => ({
521 status: shared.status,
522 rows: projectReleaseRows(shared.toArray),
523 }),
524 }
525 },
526 'preload()': (shared) => {
527 const ready = shared.preload()
528 void ready.catch(() => {})
529 return {
530 ready,
531 observe: () => ({
532 status: shared.status,
533 rows: projectReleaseRows(shared.toArray),
534 }),
535 }
536 },
537 'a direct subscription': (shared) => {
538 // Observe this receiving subscription's deliveries. Reading shared.toArray
539 // would let missing callbacks pass whenever Collection storage was correct.
540 const replica = new Map<string, Row>()
541 const subscription = shared.subscribeChanges(
542 (changes) => {
543 for (const change of changes) {
544 if (change.type === `delete`) replica.delete(change.key)
545 else {
546 const { id, value, rank } = change.value
547 replica.set(change.key, { id, value, rank })
548 }
549 }
550 },
551 {
552 includeInitialState: true,
553 },
554 )
555 return {
556 observe: () => ({
557 status: shared.status,
558 rows: projectReleaseRows([...replica.values()]),
559 }),
560 dispose: () => subscription.unsubscribe(),
561 }
562 },
563}
564
565/** The release judgment knows authored source facts, not hook/cache machinery.
566 * Independent demand starts one healthy source. A later source publication
567 * replaces the row's value, and every direct reader must receive that whole row.
568 * An after-hook throw/suspension can be reclaimed before or after the read; it
569 * owes the same final result. No synchronous reclaim deadline is imposed.
570 */
571function expectedReleaseObservation(row: Row): ReleaseObservation {
572 return { starts: 1, status: `ready`, rows: [{ ...row }] }
573}
574function checkReleaseObservation(
575 actual: ReleaseObservation,
576 expected: ReleaseObservation,
577): void {
578 expect(actual).toEqual(expected)
579}
580
581/** Every rendered history must first materialize its shared descriptor. The
582 * premise is checked before independent demand, rather than inferred from final
583 * rows. Initial mount and rerender are different receiving paths. The source-ID
584 * collision requires the rerender's prior claim; a keyed input intentionally
585 * bypasses that rejection and is excluded only from those identity causes.
586 *
587 * Cleanup registers React's native root inventory before calling render. It
588 * therefore releases a partially constructed mount even without a returned
589 * handle. Independent subscriptions, client ownership and plain source objects
590 * are released separately; one cleanup failure cannot erase the primary error.
591 */
592let releaseSequence = 0
593async function checkReleaseHistory(
594 makeCause: (typeof releaseCauses)[string],
595 hook: ReleaseHook,
596 read: ReleaseReader,
597 atMount: boolean,
598) {
599 const reach = createOracleReach(`React descriptor release`, [
600 `prepared`,
601 `reader-ready`,
602 `source-update`,
603 ])
604 reach.beginHistory()
605 const client = new DbClient()
606 const sources = new Set<ReturnType<typeof source>>()
607 const id = `release-shared-${releaseSequence++}`
608 let syncStarts = 0
609 let materialized = 0
610 const initialRow: Row = { id: `one`, value: `shared`, rank: 1 }
611 const nextRow: Row = { ...initialRow, value: `updated`, rank: 2 }
612 let publish!: (row: Row) => void
613 const shared = collectionOptions(id, () => {
614 materialized++
615 return {
616 id,
617 getKey: (row: Row) => row.id,
618 sync: {
619 sync: ({ begin, write, commit, markReady }) => {
620 syncStarts++
621 begin()
622 write({ type: `insert`, value: { ...initialRow } })
623 commit()
624 markReady()
625 publish = (row) => {
626 begin()
627 write({ type: `update`, value: { ...row } })
628 commit()
629 }
630 },
631 },
632 }
633 })
634 const failures = {
635 factory: new Error(`descriptor factory failed`),
636 sibling: new Error(`sibling failed`),
637 }
638 const failing = collectionOptions(`${id}-failing`, () => {
639 throw failures.factory
640 })
641 const cause = makeCause(shared, failing, failures)
642 const rejections: Array<unknown> = []
643 let afterHookReached = 0
644 class CaptureBoundary extends TestErrorBoundary {
645 componentDidCatch(error: Error) {
646 rejections.push(error)
647 }
648 }
649 const never = new Promise<void>(() => {})
650 function View({ step }: { step: ReleaseStep }) {
651 hook.use((q) => cause.query(q, step, hook.ordered), step.reject)
652 if (step.reject && cause.afterHook) {
653 afterHookReached++
654 if (cause.afterHook === `throw`) throw failures.sibling
655 throw never
656 }
657 return <div>Query</div>
658 }
659 const tree = (step: ReleaseStep) => (
660 <DbProvider client={client}>
661 <CaptureBoundary>
662 <Suspense fallback={<div>Loading</div>}>
663 <View step={step} />
664 </Suspense>
665 </CaptureBoundary>
666 </DbProvider>
667 )
668 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
669 let reader: ReturnType<ReleaseReader> | undefined
670 const cleanups: Array<() => unknown> = [
671 () => reader?.dispose?.(),
672 () => cleanupReact(),
673 () => client.cleanup(),
674 () => consoleError.mockRestore(),
675 ]
676 const remember = (collection: ReturnType<typeof source>) => {
677 if (!sources.has(collection)) cleanups.push(() => collection.cleanup())
678 sources.add(collection)
679 }
680 await withOracleCleanup(async () => {
681 const initial = { current: source(`settings`, `first`), reject: false }
682 remember(initial.current)
683 const rejected = cause.rejected(initial)
684 remember(rejected.current)
685 const root = render(tree(atMount ? rejected : initial))
686 await act(async () => {})
687 if (!atMount) root.rerender(tree(rejected))
688 expect(
689 root.getByText(cause.afterHook === `suspend` ? `Loading` : `Rejected`),
690 ).toBeDefined()
691 expect(materialized, `shared descriptor bound before rejected render`).toBe(
692 1,
693 )
694 if (cause.afterHook) expect(afterHookReached).toBeGreaterThan(0)
695 else expect(afterHookReached).toBe(0)
696 if (cause.afterHook === `suspend`) expect(rejections).toEqual([])
697 else {
698 expect(
699 rejections.length,
700 `authored rejection reached boundary`,
701 ).toBeGreaterThan(0)
702 for (const error of rejections)
703 expect(
704 cause.matchesRejection?.(error),
705 `intended rejection: ${String(error)}`,
706 ).toBe(true)
707 }
708 if (!cause.afterHook) expect(syncStarts).toBe(0)
709 reach.reach(`prepared`)
710 const collection = client.collection(shared)
711 act(() => {
712 reader = read(collection)
713 })
714 if (cause.afterHook) await waitFor(() => expect(syncStarts).toBe(1))
715 else expect(syncStarts).toBe(1)
716 await reader!.ready
717 await act(async () => {})
718 checkReleaseObservation(
719 { starts: syncStarts, ...reader!.observe() },
720 expectedReleaseObservation(initialRow),
721 )
722 reach.reach(`reader-ready`)
723 act(() => {
724 publish(nextRow)
725 })
726 await act(async () => {})
727 checkReleaseObservation(
728 { starts: syncStarts, ...reader!.observe() },
729 expectedReleaseObservation(nextRow),
730 )
731 reach.reach(`source-update`)
732 reach.assertReached()
733 }, cleanups)
734}
735
736describe(`React source ID reuse: rejected renders release deferred sync starts`, () => {
737 for (const [causeName, makeCause] of Object.entries(releaseCauses))
738 for (const [hookName, hook] of Object.entries(releaseHooks)) {
739 const probe = makeCause(undefined, undefined)
740 if (probe.rejectsIn && !probe.rejectsIn(hook)) continue
741 for (const [readerName, read] of Object.entries(releaseReaders))
742 for (const atMount of probe.requiresPriorClaim
743 ? [false]
744 : [false, true])
745 it(`after ${causeName} in ${hookName}, ${readerName} starts the shared source (${atMount ? `mount` : `rerender`})`, () =>
746 checkReleaseHistory(makeCause, hook, read, atMount))
747 }
748})
749it.each([
750 `missing-start`,
751 `extra-start`,
752 `wrong-row`,
753 `duplicate-row`,
754] as const)(`rejects wrong descriptor release observation: %s`, (fault) => {
755 const expected = expectedReleaseObservation({
756 id: `one`,
757 value: `authored`,
758 rank: 2,
759 })
760 const actual = { ...expected, rows: expected.rows.map((row) => ({ ...row })) }
761 checkReleaseObservation(actual, expected)
762 if (fault === `missing-start`) actual.starts = 0
763 if (fault === `extra-start`) actual.starts = 2
764 if (fault === `wrong-row`) actual.rows[0]!.rank++
765 if (fault === `duplicate-row`) actual.rows.push({ ...actual.rows[0]! })
766 expect(() => checkReleaseObservation(actual, expected)).toThrow()
767})
768
769declareOracle({
770 check: [checkReleaseObservation],
771 model: [expectedReleaseObservation],
772 grammar: [releaseCauses, releaseHooks, releaseReaders],
773})
774
775describe(`React source ID reuse`, () => {
776 it(`rejects a different active source with the same ID before exposing stale rows`, async () => {
777 const first = source(`settings`, `first`)
778 const second = source(`settings`, `second`)
779 const hook = renderHook(
780 ({ current }) =>
781 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
782 { initialProps: { current: first } },
783 )
784
785 await waitFor(() =>
786 expect(hook.result.current.data[0]?.value).toBe(`first`),
787 )
788 checkRerender([{ source: first }], { source: second }, () =>
789 hook.rerender({ current: second }),
790 )
791 })
792
793 it(`rejects a previously used ID after another source and a query change`, async () => {
794 const first = source(`settings`, `first`)
795 const other = source(`other`, `other`)
796 const second = source(`settings`, `second`)
797 const hook = renderHook(
798 ({ current, minimum }) =>
799 useLiveQuery({
800 query: (q) =>
801 q
802 .from({ settings: current })
803 .where(({ settings }) => gt(settings.rank, minimum)),
804 }),
805 { initialProps: { current: first, minimum: 0 } },
806 )
807
808 await waitFor(() =>
809 expect(hook.result.current.data[0]?.value).toBe(`first`),
810 )
811 act(() => hook.rerender({ current: other, minimum: 0 }))
812 await waitFor(() =>
813 expect(hook.result.current.data[0]?.value).toBe(`other`),
814 )
815 checkRerender(
816 [{ source: first }, { source: other }],
817 { source: second },
818 () => hook.rerender({ current: second, minimum: -1 }),
819 )
820 })
821
822 it(`accepts the same source object and a different source ID`, async () => {
823 const first = source(`settings`, `first`)
824 const other = source(`other`, `other`)
825 const hook = renderHook(
826 ({ current }) =>
827 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
828 { initialProps: { current: first } },
829 )
830
831 await waitFor(() =>
832 expect(hook.result.current.data[0]?.value).toBe(`first`),
833 )
834 checkRerender([{ source: first }], { source: first }, () =>
835 hook.rerender({ current: first }),
836 )
837 expect(hook.result.current.data[0]?.value).toBe(`first`)
838 checkRerender([{ source: first }], { source: other }, () =>
839 hook.rerender({ current: other }),
840 )
841 await waitFor(() =>
842 expect(hook.result.current.data[0]?.value).toBe(`other`),
843 )
844 })
845
846 it(`keeps a mounted hook's ID binding after source cleanup`, async () => {
847 const first = source(`settings`, `first`)
848 const second = source(`settings`, `second`)
849 const hook = renderHook(
850 ({ current }) =>
851 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
852 { initialProps: { current: first } },
853 )
854 await waitFor(() =>
855 expect(hook.result.current.data[0]?.value).toBe(`first`),
856 )
857 await act(async () => first.cleanup({ dependents: true }))
858 checkRerender([{ source: first }], { source: second }, () =>
859 hook.rerender({ current: second }),
860 )
861 })
862
863 it(`remembers each client scope when one mounted hook switches clients`, async () => {
864 const firstClient = new DbClient()
865 const secondClient = new DbClient()
866 const first = source(`settings`, `first`)
867 const otherScope = source(`settings`, `other`)
868 const replacement = source(`settings`, `replacement`)
869 const hook = renderHook(
870 ({ client, current }) =>
871 useLiveQuery({
872 client,
873 query: (q) => q.from({ settings: current }),
874 }),
875 { initialProps: { client: firstClient, current: first } },
876 )
877
878 await waitFor(() =>
879 expect(hook.result.current.data[0]?.value).toBe(`first`),
880 )
881 hook.rerender({ client: secondClient, current: otherScope })
882 await waitFor(() =>
883 expect(hook.result.current.data[0]?.value).toBe(`other`),
884 )
885 checkRerender(
886 [
887 { source: first, client: firstClient },
888 { source: otherScope, client: secondClient },
889 ],
890 { source: replacement, client: firstClient },
891 () => hook.rerender({ client: firstClient, current: replacement }),
892 )
893 })
894
895 it(`rejects same-ID reuse after a suspended render starts a source query`, async () => {
896 const first = source(`first`, `first`)
897 const abandoned = source(`candidate`, `abandoned`)
898 const replacement = source(`candidate`, `replacement`)
899 const never = new Promise<void>(() => {})
900 const View = ({
901 current,
902 suspend,
903 }: {
904 current: typeof first
905 suspend: boolean
906 }) => {
907 const { data } = useLiveQuery({
908 query: (q) => q.from({ settings: current }),
909 })
910 if (suspend) throw never
911 return <div>{data[0]?.value}</div>
912 }
913 const root = render(
914 <Suspense fallback={<div>Loading</div>}>
915 <View current={first} suspend={false} />
916 </Suspense>,
917 )
918 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
919
920 root.rerender(
921 <Suspense fallback={<div>Loading</div>}>
922 <View current={abandoned} suspend={true} />
923 </Suspense>,
924 )
925 checkRerender(
926 [{ source: first }, { source: abandoned }],
927 { source: replacement },
928 () =>
929 root.rerender(
930 <Suspense fallback={<div>Loading</div>}>
931 <View current={replacement} suspend={false} />
932 </Suspense>,
933 ),
934 )
935 })
936})
937
938/**
939 * ## useLiveInfiniteQuery
940 *
941 * The infinite hook derives its identity the same way, and keeps the window
942 * collection built by its latest render for a second render before commit.
943 * That cache is keyed by derived identity, which names sources by ID, so the
944 * same law applies: a different same-ID source must reject before the hook
945 * can publish the old source's rows, from a committed or a suspended render.
946 * This driver reuses the model above with the bounded histories that
947 * distinguish the law from a hash-only check.
948 */
949describe(`React source ID reuse: useLiveInfiniteQuery`, () => {
950 const useInfinite = (current: ReturnType<typeof source>) =>
951 useLiveInfiniteQuery(
952 (q) =>
953 q.from({ settings: current }).orderBy(({ settings }) => settings.rank),
954 { pageSize: 1 },
955 )
956
957 it(`rejects a different active source with the same ID before exposing stale rows`, async () => {
958 const first = source(`settings`, `first`)
959 const second = source(`settings`, `second`)
960 const hook = renderHook(({ current }) => useInfinite(current), {
961 initialProps: { current: first },
962 })
963 await waitFor(() =>
964 expect(hook.result.current.data[0]?.value).toBe(`first`),
965 )
966 checkRerender([{ source: first }], { source: second }, () =>
967 hook.rerender({ current: second }),
968 )
969 })
970
971 it(`rejects a previously used ID after another source`, async () => {
972 const first = source(`settings`, `first`)
973 const other = source(`other`, `other`)
974 const second = source(`settings`, `second`)
975 const hook = renderHook(({ current }) => useInfinite(current), {
976 initialProps: { current: first },
977 })
978 await waitFor(() =>
979 expect(hook.result.current.data[0]?.value).toBe(`first`),
980 )
981 act(() => hook.rerender({ current: other }))
982 await waitFor(() =>
983 expect(hook.result.current.data[0]?.value).toBe(`other`),
984 )
985 checkRerender(
986 [{ source: first }, { source: other }],
987 { source: second },
988 () => hook.rerender({ current: second }),
989 )
990 })
991
992 it(`accepts the same source object and a different source ID`, async () => {
993 const first = source(`settings`, `first`)
994 const other = source(`other`, `other`)
995 const hook = renderHook(({ current }) => useInfinite(current), {
996 initialProps: { current: first },
997 })
998 await waitFor(() =>
999 expect(hook.result.current.data[0]?.value).toBe(`first`),
1000 )
1001 checkRerender([{ source: first }], { source: first }, () =>
1002 hook.rerender({ current: first }),
1003 )
1004 checkRerender([{ source: first }], { source: other }, () =>
1005 hook.rerender({ current: other }),
1006 )
1007 await waitFor(() =>
1008 expect(hook.result.current.data[0]?.value).toBe(`other`),
1009 )
1010 })
1011
1012 it(`rejects same-ID reuse after a suspended render starts a source query`, async () => {
1013 const first = source(`first`, `first`)
1014 const abandoned = source(`candidate`, `abandoned`)
1015 const replacement = source(`candidate`, `replacement`)
1016 const never = new Promise<void>(() => {})
1017 const View = ({
1018 current,
1019 suspend,
1020 }: {
1021 current: typeof first
1022 suspend: boolean
1023 }) => {
1024 const { data } = useInfinite(current)
1025 if (suspend) throw never
1026 return <div>{data[0]?.value}</div>
1027 }
1028 const root = render(
1029 <Suspense fallback={<div>Loading</div>}>
1030 <View current={first} suspend={false} />
1031 </Suspense>,
1032 )
1033 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
1034 root.rerender(
1035 <Suspense fallback={<div>Loading</div>}>
1036 <View current={abandoned} suspend={true} />
1037 </Suspense>,
1038 )
1039 checkRerender(
1040 [{ source: first }, { source: abandoned }],
1041 { source: replacement },
1042 () =>
1043 root.rerender(
1044 <Suspense fallback={<div>Loading</div>}>
1045 <View current={replacement} suspend={false} />
1046 </Suspense>,
1047 ),
1048 )
1049 })
1050})