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

descriptor-query-binding-oracle.test.tsx

1,427 lines54.2 KB

1/**
2 * A Query assembled with a Collection descriptor is a reusable query plan.
3 * Its source Collection belongs to the DbClient that later consumes it, so
4 * construction outside DbProvider succeeds and two providers can consume the
5 * same plan without sharing rows. This follows the standalone Query contract
6 * and the SSR guide's factory-descriptor promise. Concrete-config descriptors
7 * are intentionally outside the two-client law. A committed Effect that first
8 * acquires a descriptor Collection also makes that source eligible for the
9 * DbClient's public dehydration snapshot.
10 *
11 * Model: each client owns a plain map of rows. A write to one map changes
12 * only that client's expected result. An Effect reports that client's row on
13 * entry, including after a mounted provider switch. The model never calls the
14 * query builder, materializer, or live-query engine to calculate expected rows.
15 *
16 * Legal histories: one has disjoint row keys across clients; the other has the
17 * same key with different values in both clients. Build once, mount under two
18 * clients, write independently to each, then switch one mounted hook to the
19 * other client and back. After an Effect switches providers, an old-source
20 * write produces no update event, while a new-source write produces one. The
21 * public observation at each settled cut is the
22 * complete projected row bag and row key from each useLiveQuery hook. A separate
23 * Effect history checks enter events from two clients with the same row key,
24 * then switches one mounted Effect to the other client. The
25 * colliding-key history rejects a row-ID-only cross-client cache that the
26 * disjoint history could miss. This bounded driver does not prove every query
27 * clause, on-demand load, or framework adapter. A separate Effect history
28 * observes dehydration after the committed Effect has reported its first row.
29 * A no-client history changes one mounted hook from a concrete query to a
30 * descriptor query with the same semantic hash. It must reject the unbound
31 * source before reusing the old live-query Collection. Both explicit identity
32 * forms of the ordinary and Suspense hooks owe the same React error naming
33 * DbProvider as the remedy; the core error remains framework neutral.
34 * A server-streaming history begins with a pending concrete-source hook and
35 * then preloads a descriptor with the same query hash over another source
36 * object. The client must reject that local source substitution before the
37 * stream's result can answer the second preload. This is one local hook-first
38 * order. A separate hydration-first history receives a server result whose
39 * Collection objects cannot cross the wire. The first committed browser hook
40 * claims its local source objects while the browser source is still loading;
41 * a later same-hash preload over another object must reject. The model expects
42 * the server row before browser readiness and the browser row after handoff.
43 * A hostile observer that omits the committed claim fails at the conflicting
44 * preload assertion while the source remains unready.
45 * A Suspense read is itself a preload, even if React abandons its render. With
46 * a pending hydrated stream, that first local preload starts the source and
47 * claims its object identity before commit. A later same-source preload is
48 * accepted and a different same-hash source is rejected at that cut. This
49 * demand is distinct from an ordinary hook's commit-owned subscription.
50 * A finite two-source grammar places the same standalone parent and child
51 * descriptors in a join, nested FROM, union, or include. Two clients supply
52 * different values under equal row keys. A plain per-client value model
53 * predicts the complete selected rows after initial publication, a first-
54 * client child write, and a second-client parent write. This detects binding
55 * either source to the wrong provider; it does not observe on-demand requests
56 * or arbitrary interleavings of source writes.
57 * A receiving include repeats those checkpoints with a child alias that
58 * shadows the parent alias and a renamed control. The child's projection
59 * includes the captured parent value, so alias-only lookup changes an
60 * observable field even when the correlation still admits the child. Its
61 * stable identity must also survive descriptor binding: changing source
62 * binding IDs while retaining captured references changes the public hash.
63 * A second receiving history combines descriptor binding with RIGHT/FULL
64 * outer joins, both correlation sides, shadowed and renamed aliases, and
65 * eager/on-demand source modes. Plain per-client maps predict joined rows,
66 * including an undefined missing side. Both clients use equal row IDs but
67 * distinct values. The public check runs after initial acquisition and each
68 * authored source write; source starts and on-demand requests are observed
69 * after acquisition. The finite grammar does not cover every join chain or
70 * arbitrary write order.
71 *
72 * A prepared query is a bound snapshot, not a lasting render resolver. Adding
73 * a descriptor source later changes the plan without starting a sync run. The
74 * next client-aware consumer binds that source. The independent start model is
75 * zero for an unconsumed continuation or a render that never commits, and one
76 * for the source after a committed hook consumes it. A fixed history prepares
77 * a base query, releases its render deferral, then extends and mounts it. A
78 * neighboring Suspense history extends a query during a render that is never
79 * committed. The sync callback count and public rows are checked at those
80 * cuts. Another suspended render leaves a source shared with a later direct
81 * reader. An ordinary subscription or preload is independent demand for data:
82 * it starts the source even though the earlier render never committed. A
83 * deferring subscription retains the zero-start cut. The finite grammar crosses
84 * all four readers with startSync true/false and eager/on-demand sources. It
85 * extends ordinary admission with loading/ready callback cleanup, including
86 * held resource cleanup. The shared lifecycle judgment predicts adapter entries
87 * and the complete status trace at admission return and cleanup settlement.
88 * Later demand restarts a retired source or reuses its existing run. Rows are
89 * checked only without callback cleanup; on-demand source preload alone does
90 * not request rows. These histories do not cover arbitrary concurrent render
91 * schedules or Electric transaction evidence.
92 */
93​
94import { Writable } from 'node:stream'
95import { act, render, renderHook, waitFor } from '@testing-library/react'
96import {
97 BTreeIndex,
98 DbClient,
99 Query,
100 collectionOptions,
101 getLiveQueryHash,
102 getStableQueryBuilderHash,
103} from '@tanstack/db'
104import { describe, expect, it, vi } from 'vitest'
105import { fc } from '@fast-check/vitest'
106import { Component, Suspense } from 'react'
107import { renderToPipeableStream, renderToString } from 'react-dom/server'
108import { hydrateRoot } from 'react-dom/client'
109import { routerWithDbClient } from '../../react-router-with-db/src'
110import {
111 expectedSsrSnapshot,
112 ssrSnapshotExamples,
113 ssrSnapshotHistoryArbitrary,
114} from '../../db/tests/ssr-snapshot-admission-oracle'
115import { ssrStreamHydrationMismatches } from '../../db/tests/ssr-stream-view-oracle'
116import { oraclePropertyOptions, oracleRuns } from '../../db/tests/oracle-config'
117import { createOracleReach } from '../../db/tests/oracle-reach'
118import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
119import { DbProvider } from '../src/DbProvider'
120import { useLiveQuery } from '../src/useLiveQuery'
121import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
122import { mockSyncCollectionOptions } from '../../db/tests/utils'
123import { createDeferred } from '../../db/src/deferred'
124import {
125 expectedStartHandoff,
126 modelSubscriberStartCleanup,
127 subscriberStartCleanupHistories,
128} from '../../db/tests/collection-subscription-lifecycle-grammar-oracle'
129import { declareOracle } from '../../db/tests/oracle-declaration'
130import { renderSsr } from './descriptor-query-binding-support'
131import type { Row } from './descriptor-query-binding-support'
132import type { DehydratedRouterDbState } from '../../react-router-with-db/src'
133import type { SsrSnapshotHistory } from '../../db/tests/ssr-snapshot-admission-oracle'
134import type { SsrStreamHistory } from '../../db/tests/ssr-stream-view-oracle'
135import type { ReactNode } from 'react'
136import type { Root } from 'react-dom/client'
137​
138const histories = [
139 {
140 name: `disjoint keys`,
141 initial: {
142 first: { id: `a`, value: `first` },
143 second: { id: `b`, value: `second` },
144 },
145 writes: {
146 first: { id: `c`, value: `first write` },
147 second: { id: `d`, value: `second write` },
148 },
149 },
150 {
151 name: `colliding keys`,
152 initial: {
153 first: { id: `shared`, value: `first` },
154 second: { id: `shared`, value: `second` },
155 },
156 writes: {
157 first: { id: `shared`, value: `first write` },
158 second: { id: `shared`, value: `second write` },
159 },
160 },
161] satisfies ReadonlyArray<{
162 name: string
163 initial: { first: Row; second: Row }
164 writes: { first: Row; second: Row }
165}>
166​
167function expectedRows(rows: ReadonlyMap<string, Row>): Array<Row> {
168 return [...rows.values()].sort((left, right) =>
169 left.id.localeCompare(right.id),
170 )
172​
173// The model reducer for one write: the row keyed by `next.id` takes its value.
174function applyModelWrite(model: Map<string, Row>, next: Row): void {
175 model.set(next.id, { ...next })
177​
178declareOracle({
179 check: [checkStreamCut],
180 model: [expectedRows, applyModelWrite],
181})
182​
183describe(`standalone descriptor query binding`, () => {
184 // A suspended render owns no provider demand. A later independent reader
185 // does: ordinary subscriptions and preloads start exactly one sync run,
186 // while a deferring subscription preserves the zero-start cut. Ordinary
187 // admission also crosses startup cleanup: cleanup retires this start, and
188 // only fresh later demand can restart it. Both startSync settings must work.
189 it.each(
190 (
191 [
192 { reader: `preload`, startSync: true },
193 { reader: `preload`, startSync: false },
194 { reader: `subscriber`, startSync: true },
195 { reader: `subscriber`, startSync: false },
196 { reader: `resumed subscriber`, startSync: true },
197 { reader: `resumed subscriber`, startSync: false },
198 { reader: `deferring subscriber`, startSync: true },
199 { reader: `deferring subscriber`, startSync: false },
200 ] as const
201 ).flatMap((history) =>
202 ([`eager`, `on-demand`] as const).flatMap((syncMode) =>
203 (history.reader === `subscriber` ||
204 history.reader === `resumed subscriber`
205 ? subscriberStartCleanupHistories
206 : [subscriberStartCleanupHistories[0]]
207 ).map((cleanupHistory) => ({
208 ...history,
209 syncMode,
210 ...cleanupHistory,
211 })),
212 ),
213 ),
214 )(
215 `$reader after an abandoned render (startSync=$startSync, $syncMode, cleanup=$cleanupAt, pending=$cleanupPending)`,
216 async (history) => {
217 const { reader, startSync, syncMode, cleanupAt, cleanupPending } = history
218 const expected = modelSubscriberStartCleanup(history)
219 const pendingCleanup = createDeferred<void>()
220 const client = new DbClient()
221 let starts = 0
222 let cleanups = 0
223 const descriptor = collectionOptions(`suspended-direct-reader`, () => ({
224 id: `suspended-direct-reader`,
225 getKey: (row: Row) => row.id,
226 startSync,
227 syncMode,
228 sync: {
229 sync: ({ begin, write, commit, markReady }) => {
230 starts++
231 const publish = () => {
232 begin()
233 write({ type: `insert`, value: { id: `one`, value: `live` } })
234 commit()
235 return true as const
236 }
237 if (syncMode === `eager`) publish()
238 markReady()
239 return {
240 loadSubset: publish,
241 cleanup: () => {
242 cleanups++
243 return cleanupPending ? pendingCleanup.promise : undefined
244 },
245 }
246 },
247 },
248 }))
249 const query = new Query().from({ item: descriptor })
250 const never = new Promise<void>(() => {})
251​
252 function Suspended(): ReactNode {
253 useLiveQuery({ query })
254 throw never
255 }
256​
257 const mounted = render(
258 <DbProvider client={client}>
259 <Suspense fallback={<div>Waiting</div>}>
260 <Suspended />
261 </Suspense>
262 </DbProvider>,
263 )
264 const source = client.collection(descriptor)
265 const statuses: Array<string> = []
266 let cleanup: Promise<void> | undefined
267 let cleanupRequested = false
268 const removeStatusListener = source.on(`status:change`, ({ status }) => {
269 statuses.push(status)
270 if (!cleanupRequested && status === cleanupAt) {
271 cleanupRequested = true
272 cleanup = source.cleanup()
273 }
274 })
275 let directRead: Promise<void> | undefined
276 let subscription: ReturnType<typeof source.subscribeChanges> | undefined
277 let peer: ReturnType<typeof source.subscribeChanges> | undefined
278 try {
279 expect(mounted.getByText(`Waiting`)).toBeDefined()
280 expect(starts, `before commit or direct demand`).toBe(0)
281​
282 if (reader === `preload`) {
283 directRead = source.preload()
284 void directRead.catch(() => {})
285 } else {
286 subscription = source.subscribeChanges(() => {}, {
287 deferAcquisition:
288 reader === `deferring subscriber` ||
289 reader === `resumed subscriber`,
290 includeInitialState: true,
291 })
292 if (reader === `resumed subscriber`) {
293 expect(
294 starts,
295 `deferred demand preserves the abandoned-render cut`,
296 ).toBe(0)
297 subscription.resumeDeferredAcquisition()
298 }
299 }
300 expect(starts, `direct demand starts the source`).toBe(
301 reader === `deferring subscriber` ? 0 : expected.starts,
302 )
303 expect(cleanups).toBe(expected.cleanups)
304 expect(source.status).toBe(
305 reader === `deferring subscriber` ? `idle` : expected.statusOnReturn,
306 )
307 expect(statuses).toEqual(
308 reader === `deferring subscriber` ? [] : expected.statusesOnReturn,
309 )
310 pendingCleanup.resolve()
311 await cleanup
312 await directRead
313 expect(source.status).toBe(
314 reader === `deferring subscriber`
315 ? `idle`
316 : expected.statusAfterCleanup,
317 )
318 expect(statuses).toEqual(
319 reader === `deferring subscriber`
320 ? []
321 : expected.statusesAfterCleanup,
322 )
323 if (cleanupAt === `none`) {
324 const expectsRow =
325 reader !== `deferring subscriber` &&
326 (syncMode === `eager` ||
327 reader === `subscriber` ||
328 reader === `resumed subscriber`)
329 expect(source.get(`one`)?.value).toBe(expectsRow ? `live` : undefined)
330 }
331 removeStatusListener()
332 if (reader !== `deferring subscriber`) {
333 peer = source.subscribeChanges(() => {})
334 expect(starts, `later demand reuses or restarts the source`).toBe(
335 expected.starts + (cleanupAt === `none` ? 0 : 1),
336 )
337 expect(source.status).toBe(`ready`)
338 }
339 } finally {
340 removeStatusListener()
341 pendingCleanup.resolve()
342 await cleanup
343 peer?.unsubscribe()
344 subscription?.unsubscribe()
345 mounted.unmount()
346 await client.cleanup()
347 await directRead?.catch(() => {})
348 }
349 },
350 )
351​
352 it.each(histories)(
353 `binds one prebuilt Query to each receiving DbClient with $name`,
354 async ({ name, initial, writes }) => {
355 const descriptor = collectionOptions(
356 `standalone-descriptor-rows-${name}`,
357 (client) =>
358 mockSyncCollectionOptions<Row>({
359 id: `standalone-descriptor-rows-${name}`,
360 getKey: (row) => row.id,
361 initialData: client.requireDependency<Array<Row>>(`rows`),
362 }),
363 )
364 // Definition happens outside React and before either DbClient exists.
365 const query = new Query()
366 .from({ item: descriptor })
367 .select(({ item }) => ({ id: item.id, value: item.value }))
368 const firstModel = new Map<string, Row>([
369 [initial.first.id, initial.first],
370 ])
371 const secondModel = new Map<string, Row>([
372 [initial.second.id, initial.second],
373 ])
374 const seedRows = (model: ReadonlyMap<string, Row>) =>
375 expectedRows(model).map((row) => ({ ...row }))
376 const firstClient = new DbClient({ rows: seedRows(firstModel) })
377 const secondClient = new DbClient({ rows: seedRows(secondModel) })
378 const planIdentity = getStableQueryBuilderHash(query)
379 const boundShape = (client: DbClient) =>
380 new Query()
381 .from({ item: client.collection(descriptor) })
382 .select(({ item }) => ({ id: item.id, value: item.value }))
383 expect(planIdentity).toBe(
384 getStableQueryBuilderHash(boundShape(firstClient)),
385 )
386 expect(planIdentity).toBe(
387 getStableQueryBuilderHash(boundShape(secondClient)),
388 )
389 let firstReceivingClient = firstClient
390 const first = renderHook(() => useLiveQuery({ query }), {
391 wrapper: ({ children }: { children: ReactNode }) => (
392 <DbProvider client={firstReceivingClient}>{children}</DbProvider>
393 ),
394 })
395 const second = renderHook(() => useLiveQuery({ query }), {
396 wrapper: ({ children }: { children: ReactNode }) => (
397 <DbProvider client={secondClient}>{children}</DbProvider>
398 ),
399 })
400​
401 // Compare after each publication. The same descriptor ID and query shape
402 // must not make either provider observe the other provider's Collection.
403 const check = async (
404 firstScopeModel: ReadonlyMap<string, Row> = firstModel,
405 ) => {
406 await waitFor(() => {
407 for (const [observed, model] of [
408 [first.result.current.data, firstScopeModel],
409 [second.result.current.data, secondModel],
410 ] as const) {
411 expect(
412 observed
413 .map(({ id, value }) => ({ id, value }))
414 .sort((left, right) => left.id.localeCompare(right.id)),
415 ).toEqual(expectedRows(model))
416 for (const row of observed) {
417 expect(row.$key).toBe(row.id)
418 expect(Object.keys(row).sort()).toEqual(
419 [
420 `$collectionId`,
421 `$hasPendingWrites`,
422 `$key`,
423 `$origin`,
424 `$synced`,
425 `id`,
426 `value`,
427 ].sort(),
428 )
429 }
430 }
431 })
432 }
433 await check()
434 expect(firstClient.collection(descriptor)).not.toBe(
435 secondClient.collection(descriptor),
436 )
437​
438 const write = (client: DbClient, model: Map<string, Row>, next: Row) => {
439 act(() => {
440 const collection = client.collection(descriptor)
441 if (model.has(next.id)) {
442 collection.update(next.id, (draft) => {
443 draft.value = next.value
444 })
445 } else {
446 collection.insert({ ...next })
447 }
448 })
449 applyModelWrite(model, next)
450 }
451​
452 write(firstClient, firstModel, writes.first)
453 await check()
454​
455 write(secondClient, secondModel, writes.second)
456 await check()
457​
458 firstReceivingClient = secondClient
459 first.rerender()
460 await check(secondModel)
461 firstReceivingClient = firstClient
462 first.rerender()
463 await check()
464​
465 first.unmount()
466 second.unmount()
467 },
468 )
469})
470​
471/**
472 * React receives the source-error premise through actual descriptor startup.
473 * The shared conformance contract exposes ordinary hook errors as a readable
474 * status. The start-handoff judgment distinguishes a returned fail() (a loading
475 * error) from a synchronous throw (a crash); neither permits a failed commit
476 * to retain ownership. A readable result shows the model's status through
477 * exactly one of `isLoadingError` and `isCrashed`.
478 * Each hook has independent campaigns and reach checks. The grammar varies
479 * defined/absent causes, callback return/throw, and failure before/during commit.
480 * Before-commit failures come from independent DbClient startup, whose throw
481 * belongs to that caller. We observe the boundary and result after commit,
482 * and Collection ownership immediately after unmount, before GC can hide a leak.
483 */
484describe(`descriptor error handoff at React commit`, () => {
485 class Boundary extends Component<
486 { children: ReactNode; caught: Array<unknown> },
487 { failed: boolean }
488 > {
489 state = { failed: false }
490 static getDerivedStateFromError() {
491 return { failed: true }
492 }
493 componentDidCatch(error: unknown) {
494 this.props.caught.push(error)
495 }
496 render() {
497 return this.state.failed ? null : this.props.children
498 }
499 }
500 const properties = {
501 'error-surface': `react.descriptor-error-surface`,
502 ownership: `react.descriptor-ownership`,
503 } as const
504 for (const hook of [`ordinary`, `infinite`] as const) {
505 for (const observation of [`error-surface`, `ownership`] as const) {
506 for (const campaign of [`fixed`, `random`] as const) {
507 it(`${hook} ${observation} after descriptor failure (${campaign})`, async () => {
508 const reach = createOracleReach(`react-error-handoff-${hook}`, [
509 `fail-before-release`,
510 `fail-during-release`,
511 `throw-before-release`,
512 `throw-during-release`,
513 `undefined-cause`,
514 ])
515 await fc.assert(
516 fc.asyncProperty(
517 fc.record({
518 outcome: fc.constantFrom(`fail` as const, `throw` as const),
519 cause: fc.constantFrom(`error` as const, `undefined` as const),
520 timing: fc.constantFrom(
521 `before-release` as const,
522 `during-release` as const,
523 ),
524 }),
525 async (history) => {
526 reach.beginHistory()
527 const failure =
528 history.cause === `error`
529 ? new Error(`source startup`)
530 : undefined
531 const client = new DbClient()
532 let starts = 0
533 const descriptor = collectionOptions(
534 `react-handoff-error`,
535 () => ({
536 id: `react-handoff-error`,
537 syncMode: `eager`,
538 autoIndex: `eager`,
539 defaultIndexType: BTreeIndex,
540 getKey: (row: Row) => row.id,
541 startSync: true,
542 gcTime: 0,
543 sync: {
544 sync: ({ fail }) => {
545 starts++
546 if (history.outcome === `throw`) throw failure
547 fail(failure)
548 },
549 },
550 }),
551 )
552 const query = new Query()
553 .from({ item: descriptor })
554 .orderBy(({ item }) => item.id)
555 const caught: Array<unknown> = []
556 let current:
557 | {
558 isLoadingError?: boolean
559 isCrashed?: boolean
560 status: string
561 collection?: {
562 subscriberCount: number
563 cleanup: () => Promise<void>
564 }
565 }
566 | undefined
567 function Consumer() {
568 current =
569 hook === `ordinary`
570 ? useLiveQuery({ query })
571 : useLiveInfiniteQuery(() => query, { pageSize: 1 })
572 return null
573 }
574 const consoleError = vi
575 .spyOn(console, `error`)
576 .mockImplementation(() => {})
577 let mounted: ReturnType<typeof render> | undefined
578 try {
579 if (history.timing === `before-release`) {
580 let threw = false
581 try {
582 client.collection(descriptor)
583 } catch (error) {
584 threw = true
585 expect(error).toBe(failure)
586 }
587 expect(
588 threw,
589 `independent startup owns its exception`,
590 ).toBe(history.outcome === `throw`)
591 expect(client.collection(descriptor).status).toBe(
592 expectedStartHandoff(history).status,
593 )
594 expect(starts).toBe(1)
595 }
596 mounted = render(
597 <DbProvider client={client}>
598 <Boundary caught={caught}>
599 <Consumer />
600 </Boundary>
601 </DbProvider>,
602 )
603 await act(async () => {})
604 expect(starts, `commit does not repeat source startup`).toBe(
605 expectedStartHandoff(history).starts,
606 )
607 reach.reach(`${history.outcome}-${history.timing}`)
608 if (history.cause === `undefined`)
609 reach.reach(`undefined-cause`)
610 if (observation === `error-surface`) {
611 const expected = expectedStartHandoff(history)
612 if (!expected.throws) {
613 expect(caught, `ordinary errors remain readable`).toEqual(
614 [],
615 )
616 expect(current?.status).toBe(expected.status)
617 expect(current?.isLoadingError).toBe(
618 expected.status === `error`,
619 )
620 expect(current?.isCrashed).toBe(
621 expected.status === `crashed`,
622 )
623 } else {
624 expect(
625 caught,
626 `a thrown start remains fail-fast`,
627 ).toHaveLength(1)
628 }
629 }
630 mounted.unmount()
631 expect(current?.collection).toBeDefined()
632 if (current?.collection)
633 expect(
634 current.collection.subscriberCount,
635 `commit/unmount releases every hook owner`,
636 ).toBe(0)
637 } finally {
638 mounted?.unmount()
639 consoleError.mockRestore()
640 await current?.collection?.cleanup()
641 await client.cleanup()
642 }
643 },
644 ),
645 campaign === `fixed`
646 ? { numRuns: oracleRuns(30), seed: 2229 }
647 : oraclePropertyOptions(30, properties[observation]),
648 )
649 reach.assertReached()
650 console.info(
651 `react-error-handoff ${hook} ${observation} ${campaign}`,
652 Object.fromEntries(reach.counts()),
653 )
654 })
655 }
656 }
657 }
658})
659​
660/**
661 * The shared SSR admission judgment rejects server-only rows/readiness, while
662 * cold loading, completed query results and normalized sources remain legal.
663 * Each hook independently generates the same preparation histories. Both real
664 * React server renders compare before browser commit; hydrateRoot must then
665 * report no recovery, and committed sync must replace the seed normally.
666 * Query-only infinite preparation includes its first-page peek-ahead window.
667 * This driver supplies host scheduling, not another expected-result model.
668 */
669describe(`SSR snapshot admission`, () => {
670 const properties = {
671 ordinary: `react.ssr-ordinary`,
672 infinite: `react.ssr-infinite`,
673 } as const
674 for (const hook of [`ordinary`, `infinite`] as const) {
675 const makeReach = () =>
676 createOracleReach(`ssr-${hook}`, [
677 `cold-loading`,
678 `unbacked-ready-empty`,
679 `unbacked-rows`,
680 `query-result`,
681 `normalized-ready`,
682 `normalized-partial`,
683 `pending-query`,
684 `server-write`,
685 `browser-write`,
686 `same-query-preload`,
687 ])
688 async function checkHistory(
689 history: SsrSnapshotHistory,
690 reach: ReturnType<typeof makeReach>,
691 ) {
692 reach.beginHistory()
693 const expected = expectedSsrSnapshot(history)
694 const starts = { server: 0, browser: 0 }
695 const writers = new Map<`server` | `browser`, (name: string) => void>()
696 const descriptor = collectionOptions(`ssr-admission`, (client) => ({
697 id: `ssr-admission`,
698 getKey: (row: { id: string; name: string }) => row.id,
699 autoIndex: `eager`,
700 defaultIndexType: BTreeIndex,
701 sync: {
702 sync: ({ begin, write, commit, markReady }) => {
703 const runtime = client.requireDependency<`server` | `browser`>(
704 `runtime`,
705 )
706 starts[runtime]++
707 writers.set(runtime, (name) => {
708 begin()
709 write({ type: `insert`, value: { id: `late`, name } })
710 commit()
711 })
712 begin()
713 for (const row of history.rows)
714 write({
715 type: `insert`,
716 value: {
717 ...row,
718 name: runtime === `server` ? row.name : `browser ${row.id}`,
719 },
720 })
721 commit()
722 if (runtime === `browser` || history.sourceState === `ready`)
723 markReady()
724 },
725 },
726 }))
727 const query = new Query()
728 .from({ person: descriptor })
729 .orderBy(({ person }) => person.id)
730 .select(({ person }) => ({ id: person.id, name: person.name }))
731 const server = new DbClient({ runtime: `server` })
732 const browser = new DbClient({ runtime: `browser` })
733 server._setSsrServerCleanupEnabled(true)
734 browser._setSsrServerCleanupEnabled(true)
735 let root: Root | undefined
736 const host = document.createElement(`div`)
737 const recoveries: Array<unknown> = []
738 let unmount: (() => void) | undefined
739 const useResult = () =>
740 hook === `ordinary`
741 ? useLiveQuery({ query })
742 : useLiveInfiniteQuery(() => query, { pageSize: 1 })
743 function Consumer() {
744 const result = useResult()
745 return (
746 <output
747 data-status={result.status}
748 data-ready={result.isReady}
749 data-loading={result.isLoading}
750 data-idle={result.isIdle}
751 data-loading-error={result.isLoadingError}
752 data-crashed={result.isCrashed}
753 >
754 {result.data.map((row) => (
755 <span key={row.id}>{row.name}</span>
756 ))}
757 </output>
758 )
759 }
760 const app = (client: DbClient) => (
761 <DbProvider client={client}>
762 <Consumer />
763 </DbProvider>
764 )
765 try {
766 if (history.sourceState !== `idle`) {
767 const warming = server.preloadLiveQuery({
768 query: new Query()
769 .from({ person: descriptor })
770 .select(({ person }) => ({ id: person.id })),
771 })
772 if (history.sourceState === `ready`) await warming
773 else void warming.catch(() => {})
774 }
775 // Explicit materialization registers normalized source rows for
776 // dehydration. The warming query established this fixture's rows;
777 // registration, rather than a second preload, makes them portable.
778 if (history.preparation === `source`) server.collection(descriptor)
779 if (
780 history.preparation === `query` ||
781 history.preparation === `pending-query`
782 ) {
783 const preload = server.preloadLiveQuery({
784 query: hook === `ordinary` ? query : query.limit(2).offset(0),
785 })
786 if (history.preparation === `query`) await preload
787 else void preload.catch(() => {})
788 }
789 let html: string | undefined
790 let failure: unknown
791 try {
792 html = renderSsr(app(server))
793 } catch (error) {
794 failure = error
795 }
796 if (expected.rejects) {
797 expect(
798 failure,
799 `SSR must reject untransported rows or readiness`,
800 ).toBeInstanceOf(Error)
801 expect(String(failure)).toMatch(/SSR.*(?:preload|hydrat)/i)
802 // The same warm source is ordinary valid browser usage.
803 const mounted = renderHook(useResult, {
804 wrapper: ({ children }: { children: ReactNode }) => (
805 <DbProvider client={server}>{children}</DbProvider>
806 ),
807 })
808 unmount = mounted.unmount
809 expect(
810 mounted.result.current.data.map((row) => ({
811 id: row.id,
812 name: row.name,
813 })),
814 ).toEqual(
815 hook === `ordinary` ? history.rows : history.rows.slice(0, 1),
816 )
817 reach.reach(
818 history.rows.length ? `unbacked-rows` : `unbacked-ready-empty`,
819 )
820 } else {
821 expect(failure, `prepared and cold SSR remain legal`).toBeUndefined()
822 if (history.serverWrite && history.sourceState !== `idle`) {
823 writers.get(`server`)!(`late server`)
824 reach.reach(`server-write`)
825 }
826 browser.hydrate(server.dehydrate())
827 if (history.browserWrite) {
828 if (history.browserPreload) {
829 await browser.preloadLiveQuery({
830 query: hook === `infinite` ? query.limit(2).offset(0) : query,
831 })
832 reach.reach(`same-query-preload`)
833 }
834 await browser.collection(descriptor).preload()
835 writers.get(`browser`)!(`late browser`)
836 reach.reach(`browser-write`)
837 }
838 let initialBrowserHtml: string | undefined, hydrationError: unknown
839 try {
840 initialBrowserHtml = renderToString(app(browser))
841 } catch (error) {
842 hydrationError = error
843 }
844 host.innerHTML = html!
845 expect(
846 host.querySelector(`output`)?.getAttribute(`data-status`),
847 ).toBe(expected.status)
848 expect(
849 [...host.querySelectorAll(`span`)].map((span) => span.textContent),
850 ).toEqual(
851 (hook === `ordinary`
852 ? expected.rows
853 : expected.rows.slice(0, 1)
854 ).map((row) => row.name),
855 )
856 expect(
857 starts.browser,
858 `hydration read starts no additional source`,
859 ).toBe(history.browserWrite ? 1 : 0)
860 document.body.append(host)
861 await act(async () => {
862 root = hydrateRoot(host, app(browser), {
863 onRecoverableError: (error) => recoveries.push(error),
864 })
865 await Promise.resolve()
866 })
867 expect(
868 hydrationError,
869 `browser activity cannot become an SSR programming error`,
870 ).toBeUndefined()
871 expect(
872 initialBrowserHtml,
873 `initial rows and every rendered status flag match`,
874 ).toBe(html)
875 expect(
876 recoveries,
877 `React receives the same snapshot without recovery`,
878 ).toEqual([])
879 expect(
880 starts.browser,
881 `committed browser demand starts the source`,
882 ).toBe(1)
883 expect(
884 host.querySelector(`output`)?.getAttribute(`data-status`),
885 ).toBe(`ready`)
886 expect(
887 [...host.querySelectorAll(`span`)].map((span) => span.textContent),
888 ).toEqual(
889 hook === `ordinary`
890 ? [
891 ...history.rows.map((row) => `browser ${row.id}`),
892 ...(history.browserWrite
893 ? [`late browser`]
894 : history.preparation === `source` &&
895 history.serverWrite &&
896 history.sourceState !== `idle`
897 ? [`late server`]
898 : []),
899 ]
900 : [
901 ...history.rows.map((row) => `browser ${row.id}`),
902 ...(history.browserWrite
903 ? [`late browser`]
904 : history.preparation === `source` &&
905 history.serverWrite &&
906 history.sourceState !== `idle`
907 ? [`late server`]
908 : []),
909 ].slice(0, 1),
910 )
911 if (history.preparation === `query`) reach.reach(`query-result`)
912 else if (
913 history.preparation === `source` &&
914 history.sourceState !== `idle`
915 )
916 reach.reach(
917 history.sourceState === `loading`
918 ? `normalized-partial`
919 : `normalized-ready`,
920 )
921 else reach.reach(`cold-loading`)
922 }
923 if (history.preparation === `pending-query`)
924 reach.reach(`pending-query`)
925 } finally {
926 unmount?.()
927 act(() => root?.unmount())
928 host.remove()
929 await browser.cleanup()
930 await server.cleanup()
931 }
932 }
933 for (const history of ssrSnapshotExamples) {
934 it(`replays ${hook} SSR ${history.preparation}/${history.sourceState}/${history.rows.length}`, async () => {
935 await checkHistory(history, makeReach())
936 })
937 }
938 for (const campaign of [`fixed`, `random`] as const) {
939 it(`${hook} admits reproducible SSR snapshots (${campaign})`, async () => {
940 const reach = makeReach()
941 await fc.assert(
942 fc.asyncProperty(ssrSnapshotHistoryArbitrary, (history) =>
943 checkHistory(history, reach),
944 ),
945 {
946 ...(campaign === `fixed`
947 ? { numRuns: oracleRuns(120), seed: 2229 }
948 : oraclePropertyOptions(120, properties[hook])),
949 examples: ssrSnapshotExamples.map((history) => [history]),
950 },
951 )
952 reach.assertReached()
953 console.info(
954 `ssr-admission ${hook} ${campaign}`,
955 Object.fromEntries(reach.counts()),
956 )
957 })
958 }
959 }
960})
961​
962// Streaming must capture the view it actually renders, even when the adapter
963// publishes again in the microtask before its preload promise captures a result.
964// This metamorphic observation compares the final host markup with transport.
965// An ordinary sibling may already have rendered loading before Suspense starts
966// the same query. Each reader owes its own rendered view during hydration;
967// preserving the earlier view cannot prevent the explicit preload completing.
968// Synchronous act permits the ordinary sibling's effects before React hydrates
969// its Suspense boundary. That sibling must not consume another reader's seed.
970// The readiness schedule also holds source writes and markReady until an ordinary
971// server read occurs. With Suspense first, the Router has already queued a pending
972// stream before that ordinary reader contributes its loading view. Both reader
973// orders must transfer each hook's own view; a final direct dehydrate is not a
974// substitute for the actual queued Router chunks. The provider and Router render
975// callback are controlled premises, not a deployed Start or Electric witness.
976// A held source may instead report an initial-sync error. The ordinary reader
977// already rendered loading, while Suspense renders its server fallback. Error
978// object fidelity is outside this relation; the ordinary first-view status is
979// still owed before browser commit, and the Suspense boundary may recover.
980async function checkStreamCut(
981 history: SsrStreamHistory,
982 reach: ReturnType<typeof createStreamReach>,
983) {
984 reach.beginHistory()
985 const authoredRows = Array.from({ length: history.count }, (_, i) => ({
986 id: String(i),
987 name: `first ${i}`,
988 }))
989 const client = new DbClient({ runtime: `server` })
990 const ordinaryRendered = createDeferred<void>()
991 let releaseServerSource: (() => void) | undefined
992 const sourceError = new Error(`stream source unavailable`)
993 const descriptor = collectionOptions(`stream-render-cut`, (owner) => ({
994 id: `stream-render-cut`,
995 getKey: (row: { id: string; name: string }) => row.id,
996 sync: {
997 sync: ({ begin, write, commit, markReady, fail }) => {
998 const rows =
999 owner !== client && history.browserWrite
1000 ? [{ id: `0`, name: `browser only` }]
1001 : authoredRows
1002 const publish = () => {
1003 if (owner === client && history.sourceError) {
1004 fail(sourceError)
1005 return
1007 begin()
1008 for (const row of rows) write({ type: `insert`, value: row })
1009 commit()
1010 markReady()
1011 queueMicrotask(() => {
1012 for (let i = 0; i < history.writes; i++) {
1013 begin()
1014 write({
1015 type: rows.length || i ? `update` : `insert`,
1016 value: { id: `0`, name: `later ${i}` },
1017 })
1018 commit()
1020 })
1022 if (owner === client && history.holdSourceReadiness)
1023 releaseServerSource = publish
1024 else publish()
1025 },
1026 },
1027 }))
1028 client._setSsrStreamingEnabled(true)
1029 let finishRouterRender = () => {}
1030 const router: {
1031 isServer: boolean
1032 options: {
1033 context: { dbClient: DbClient }
1034 dehydrate?: () => Promise<DehydratedRouterDbState>
1036 serverSsr: {
1037 isDehydrated: () => boolean
1038 onRenderFinished: (callback: () => void) => void
1040 } = {
1041 isServer: true,
1042 options: { context: { dbClient: client } },
1043 serverSsr: {
1044 isDehydrated: () => true,
1045 onRenderFinished: (callback) => {
1046 finishRouterRender = callback
1047 },
1048 },
1050 // The real Router adapter supplies the transport for the same generated law.
1051 // Its SSR callback is controlled; this is not a deployed Start host witness.
1052 Reflect.apply(routerWithDbClient, undefined, [router, client])
1053 const initialRouterState = await router.options.dehydrate!()
1054 const query = new Query()
1055 .from({ row: descriptor })
1056 .select(({ row }) => ({ name: row.name }))
1057 const ordinaryReads: Array<{ status: string; names: Array<string> }> = []
1058 const suspenseReads: Array<Array<string>> = []
1059 function Consumer() {
1060 const result = useLiveSuspenseQuery({ query })
1061 suspenseReads.push(result.data.map((row) => row.name))
1062 return <span>{result.data.map((row) => row.name).join(`,`)}</span>
1064 function OrdinaryConsumer() {
1065 const result = useLiveQuery({ query })
1066 ordinaryReads.push({
1067 status: result.status,
1068 names: result.data.map((row) => row.name),
1069 })
1070 if (typeof window === `undefined`) ordinaryRendered.resolve()
1071 return (
1072 <output data-status={result.status}>
1073 {result.data.map((row) => row.name).join(`,`)}
1074 </output>
1077 class StreamBoundary extends Component<
1078 { children: ReactNode },
1079 { failed: boolean }
1080 > {
1081 state = { failed: false }
1082 static getDerivedStateFromError() {
1083 return { failed: true }
1085 render() {
1086 return this.state.failed ? <b>query failed</b> : this.props.children
1089 const browserWindow = globalThis.window
1090 vi.stubGlobal(`window`, undefined)
1091 try {
1092 const errors: Array<unknown> = []
1093 const renderedHtml = new Promise<string>((resolve, reject) => {
1094 let text = ``
1095 const sink = new Writable({
1096 write(chunk, _encoding, done) {
1097 text += chunk.toString()
1098 done()
1099 },
1100 })
1101 sink.on(`finish`, () => resolve(text))
1102 sink.on(`error`, reject)
1103 const stream = renderToPipeableStream(
1104 <DbProvider client={client}>
1105 {history.ordinaryFirst && <OrdinaryConsumer />}
1106 <StreamBoundary>
1107 <Suspense fallback={<span>loading</span>}>
1108 <Consumer />
1109 </Suspense>
1110 </StreamBoundary>
1111 {history.ordinaryLast && <OrdinaryConsumer />}
1112 </DbProvider>,
1114 onAllReady() {
1115 stream.pipe(sink)
1116 },
1117 onError(error) {
1118 errors.push(error)
1119 },
1120 },
1122 })
1123 if (history.holdSourceReadiness) {
1124 // Holding readiness is legal only with an ordinary sibling. Its actual
1125 // public read, rather than a delay, proves this source-loading cut ran.
1126 await ordinaryRendered.promise
1127 expect(ordinaryReads[0], `held source renders ordinary loading`).toEqual({
1128 status: `loading`,
1129 names: [],
1130 })
1131 expect(
1132 releaseServerSource,
1133 `Suspense entered the held source`,
1134 ).toBeTypeOf(`function`)
1135 reach.reach(
1136 history.ordinaryFirst ? `held-ordinary-first` : `held-suspense-first`,
1138 releaseServerSource!()
1139 releaseServerSource = undefined
1140 } else {
1141 reach.reach(`synchronous-readiness`)
1143 const html = await renderedHtml
1144 if (history.sourceError) {
1145 // Live-query startup may wrap the provider's error. The receiving
1146 // premise is failure before readiness, not cross-boundary error identity.
1147 expect(
1148 errors.length,
1149 `Suspense received the held provider failure`,
1150 ).toBeGreaterThan(0)
1151 reach.reach(`held-source-error`)
1152 } else {
1153 expect(errors).toEqual([])
1154 const rendered = html.match(/<span>([^<]*)<\/span>/)?.[1]
1155 expect(rendered).toBe(authoredRows.map((row) => row.name).join(`,`))
1156 const transport = client
1157 .dehydrate({ shouldDehydrateLiveQuery: () => true })
1158 .liveQueries!.find(
1159 (result) => result.queryHash === getLiveQueryHash({ query }),
1160 )!
1161 const snapshot = transport.snapshot ?? (await transport.promise)
1162 expect(
1163 snapshot?.rows.map((row) => (row.value as { name: string }).name),
1164 `stream transport reproduces its rendered view`,
1165 ).toEqual(authoredRows.map((row) => row.name))
1167 if (history.ordinaryFirst || history.ordinaryLast) {
1168 const firstServerRead = ordinaryReads[0]
1169 expect(
1170 firstServerRead,
1171 `ordinary server hook returned a view`,
1172 ).toBeDefined()
1173 ordinaryReads.length = 0
1174 const firstSuspenseRead = suspenseReads[0]
1175 if (!history.sourceError)
1176 expect(
1177 firstSuspenseRead,
1178 `Suspense server hook returned its ready view`,
1179 ).toBeDefined()
1180 suspenseReads.length = 0
1181 vi.stubGlobal(`window`, browserWindow)
1182 const browser = new DbClient({ runtime: `browser` })
1183 browser.hydrate(initialRouterState.dehydratedDbClient)
1184 const reader = initialRouterState.dbStream.getReader()
1185 finishRouterRender()
1186 try {
1187 for (;;) {
1188 const chunk = await reader.read()
1189 if (chunk.done) break
1190 browser.hydrate({
1191 ...chunk.value,
1192 liveQueries: chunk.value.liveQueries?.map(
1193 ({ promise, ...data }) => ({
1194 ...JSON.parse(JSON.stringify(data)),
1195 ...(promise
1196 ? {
1197 promise: promise.then((value) =>
1198 JSON.parse(JSON.stringify(value)),
1199 ),
1201 : {}),
1202 }),
1203 ),
1204 })
1206 } finally {
1207 reader.releaseLock()
1209 const host = document.createElement(`div`)
1210 host.innerHTML = html
1211 let root: Root | undefined
1212 const hydrationErrors: Array<unknown> = []
1213 try {
1214 const hydrate = () => {
1215 root = hydrateRoot(
1216 host,
1217 <DbProvider client={browser}>
1218 {history.ordinaryFirst && <OrdinaryConsumer />}
1219 <StreamBoundary>
1220 <Suspense fallback={<span>loading</span>}>
1221 <Consumer />
1222 </Suspense>
1223 </StreamBoundary>
1224 {history.ordinaryLast && <OrdinaryConsumer />}
1225 </DbProvider>,
1226 { onRecoverableError: (error) => hydrationErrors.push(error) },
1229 await act(
1230 history.splitHydration
1231 ? hydrate
1232 : async () => {
1233 hydrate()
1234 await Promise.resolve()
1235 },
1237 reach.reach(
1238 history.holdSourceReadiness
1239 ? `held-router-browser-handoff`
1240 : `synchronous-router-browser-handoff`,
1242 const firstBrowserSuspenseRead = suspenseReads[0]
1243 expect(
1244 ssrStreamHydrationMismatches([
1246 reader: `ordinary`,
1247 server: firstServerRead!,
1248 hydration: ordinaryReads[0],
1249 },
1250 ...(history.sourceError
1251 ? []
1252 : [
1254 reader: `Suspense`,
1255 server: { status: `ready`, names: firstSuspenseRead! },
1256 hydration: firstBrowserSuspenseRead
1257 ? { status: `ready`, names: firstBrowserSuspenseRead }
1258 : undefined,
1259 },
1260 ]),
1261 ]),
1262 `each reader's first hydration view matches its own server view`,
1263 ).toEqual([])
1264 if (!history.sourceError) {
1265 expect(hydrationErrors).toEqual([])
1267 } finally {
1268 await act(async () => {
1269 root?.unmount()
1270 await Promise.resolve()
1271 })
1272 await browser.cleanup()
1275 reach.reach(history.count ? `nonempty` : `empty`)
1276 reach.reach(history.writes ? `later-publication` : `unchanged`)
1277 reach.reach(
1278 history.ordinaryFirst
1279 ? `ordinary-first`
1280 : history.ordinaryLast
1281 ? `suspense-first`
1282 : `suspense-only`,
1284 if (history.ordinaryFirst || history.ordinaryLast) {
1285 reach.reach(
1286 history.splitHydration ? `split-hydration` : `together-hydration`,
1288 reach.reach(history.browserWrite ? `browser-different` : `browser-same`)
1290 } finally {
1291 releaseServerSource?.()
1292 vi.stubGlobal(`window`, browserWindow)
1293 finishRouterRender()
1294 await client.cleanup()
1297const createStreamReach = () =>
1298 createOracleReach(`react-stream-cut`, [
1299 `empty`,
1300 `nonempty`,
1301 `later-publication`,
1302 `unchanged`,
1303 `ordinary-first`,
1304 `suspense-first`,
1305 `suspense-only`,
1306 `browser-different`,
1307 `browser-same`,
1308 `split-hydration`,
1309 `together-hydration`,
1310 `synchronous-readiness`,
1311 `held-ordinary-first`,
1312 `held-suspense-first`,
1313 `held-router-browser-handoff`,
1314 `synchronous-router-browser-handoff`,
1315 `held-source-error`,
1316 ])
1317describe(`stream render snapshot cut`, () => {
1318 for (const ordinaryFirst of [false, true])
1319 for (const splitHydration of [false, true])
1320 it(`retains an ordinary loading view when its stream later fails, ordinaryFirst=${ordinaryFirst}, split=${splitHydration}`, () =>
1321 checkStreamCut(
1323 count: 0,
1324 writes: 0,
1325 ordinaryFirst,
1326 ordinaryLast: !ordinaryFirst,
1327 holdSourceReadiness: true,
1328 sourceError: true,
1329 splitHydration,
1330 },
1331 createStreamReach(),
1332 ))
1333 for (const count of [0, 1])
1334 for (const ordinaryFirst of [false, true])
1335 for (const splitHydration of [false, true])
1336 it(`hydrates each held-source view with count=${count}, ordinaryFirst=${ordinaryFirst}, split=${splitHydration}`, () =>
1337 checkStreamCut(
1339 count,
1340 writes: 0,
1341 ordinaryFirst,
1342 ordinaryLast: !ordinaryFirst,
1343 holdSourceReadiness: true,
1344 browserWrite: true,
1345 splitHydration,
1346 },
1347 createStreamReach(),
1348 ))
1349 it(`keeps an ordinary reader from blocking a shared Suspense preload`, () =>
1350 checkStreamCut(
1351 { count: 1, writes: 0, ordinaryFirst: true, browserWrite: true },
1352 createStreamReach(),
1353 ))
1354 it(`hydrates an ordinary reader rendered after its Suspense sibling`, () =>
1355 checkStreamCut(
1356 { count: 1, writes: 0, ordinaryLast: true, browserWrite: true },
1357 createStreamReach(),
1358 ))
1359 it(`retains the Suspense view after its ordinary sibling commits`, () =>
1360 checkStreamCut(
1362 count: 1,
1363 writes: 0,
1364 ordinaryFirst: true,
1365 browserWrite: true,
1366 splitHydration: true,
1367 },
1368 createStreamReach(),
1369 ))
1370 for (const history of [
1371 { count: 0, writes: 1 },
1372 { count: 1, writes: 1 },
1373 { count: 1, writes: 0 },
1374 ])
1375 it(`replays count=${history.count} later-writes=${history.writes}`, () =>
1376 checkStreamCut(history, createStreamReach()))
1377 for (const campaign of [`fixed`, `random`] as const)
1378 it(`transports the rendered view (${campaign})`, async () => {
1379 const reach = createStreamReach()
1380 try {
1381 await fc.assert(
1382 fc.asyncProperty(
1383 fc
1384 .record({
1385 count: fc.integer({ min: 0, max: 3 }),
1386 writes: fc.integer({ min: 0, max: 3 }),
1387 ordinaryFirst: fc.boolean(),
1388 ordinaryLast: fc.boolean(),
1389 browserWrite: fc.boolean(),
1390 splitHydration: fc.boolean(),
1391 holdSourceReadiness: fc.boolean(),
1392 sourceError: fc.boolean(),
1393 })
1394 .map((history) => {
1395 // A held provider needs an ordinary read to release it; a
1396 // Suspense-only history retains synchronous source readiness.
1397 const holdSourceReadiness =
1398 history.holdSourceReadiness &&
1399 (history.ordinaryFirst || history.ordinaryLast)
1400 // Failure is held until a real ordinary loading read. Empty
1401 // sources isolate lifecycle status from error-row retention.
1402 const sourceError = history.sourceError && holdSourceReadiness
1403 return {
1404 ...history,
1405 ordinaryLast: !history.ordinaryFirst && history.ordinaryLast,
1406 holdSourceReadiness,
1407 sourceError,
1408 count: sourceError ? 0 : history.count,
1409 writes: sourceError ? 0 : history.writes,
1411 }),
1412 (history) => checkStreamCut(history, reach),
1413 ),
1414 campaign === `fixed`
1415 ? { numRuns: oracleRuns(40), seed: 2229 }
1416 : oraclePropertyOptions(40, `react.ssr-stream-cut`),
1418 } finally {
1419 // Keep reached premises visible when the first refinement check fails.
1420 console.info(
1421 `react-stream-cut ${campaign}`,
1422 Object.fromEntries(reach.counts()),
1425 reach.assertReached()
1426 })