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

descriptor-query-binding-oracle.test.tsx

1,426 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 `id`,
425 `value`,
426 ].sort(),
427 )
428 }
429 }
430 })
431 }
432 await check()
433 expect(firstClient.collection(descriptor)).not.toBe(
434 secondClient.collection(descriptor),
435 )
436​
437 const write = (client: DbClient, model: Map<string, Row>, next: Row) => {
438 act(() => {
439 const collection = client.collection(descriptor)
440 if (model.has(next.id)) {
441 collection.update(next.id, (draft) => {
442 draft.value = next.value
443 })
444 } else {
445 collection.insert({ ...next })
446 }
447 })
448 applyModelWrite(model, next)
449 }
450​
451 write(firstClient, firstModel, writes.first)
452 await check()
453​
454 write(secondClient, secondModel, writes.second)
455 await check()
456​
457 firstReceivingClient = secondClient
458 first.rerender()
459 await check(secondModel)
460 firstReceivingClient = firstClient
461 first.rerender()
462 await check()
463​
464 first.unmount()
465 second.unmount()
466 },
467 )
468})
469​
470/**
471 * React receives the source-error premise through actual descriptor startup.
472 * The shared conformance contract exposes ordinary hook errors as a readable
473 * status. The start-handoff judgment distinguishes a returned fail() (a loading
474 * error) from a synchronous throw (a crash); neither permits a failed commit
475 * to retain ownership. A readable result shows the model's status through
476 * exactly one of `isLoadingError` and `isCrashed`.
477 * Each hook has independent campaigns and reach checks. The grammar varies
478 * defined/absent causes, callback return/throw, and failure before/during commit.
479 * Before-commit failures come from independent DbClient startup, whose throw
480 * belongs to that caller. We observe the boundary and result after commit,
481 * and Collection ownership immediately after unmount, before GC can hide a leak.
482 */
483describe(`descriptor error handoff at React commit`, () => {
484 class Boundary extends Component<
485 { children: ReactNode; caught: Array<unknown> },
486 { failed: boolean }
487 > {
488 state = { failed: false }
489 static getDerivedStateFromError() {
490 return { failed: true }
491 }
492 componentDidCatch(error: unknown) {
493 this.props.caught.push(error)
494 }
495 render() {
496 return this.state.failed ? null : this.props.children
497 }
498 }
499 const properties = {
500 'error-surface': `react.descriptor-error-surface`,
501 ownership: `react.descriptor-ownership`,
502 } as const
503 for (const hook of [`ordinary`, `infinite`] as const) {
504 for (const observation of [`error-surface`, `ownership`] as const) {
505 for (const campaign of [`fixed`, `random`] as const) {
506 it(`${hook} ${observation} after descriptor failure (${campaign})`, async () => {
507 const reach = createOracleReach(`react-error-handoff-${hook}`, [
508 `fail-before-release`,
509 `fail-during-release`,
510 `throw-before-release`,
511 `throw-during-release`,
512 `undefined-cause`,
513 ])
514 await fc.assert(
515 fc.asyncProperty(
516 fc.record({
517 outcome: fc.constantFrom(`fail` as const, `throw` as const),
518 cause: fc.constantFrom(`error` as const, `undefined` as const),
519 timing: fc.constantFrom(
520 `before-release` as const,
521 `during-release` as const,
522 ),
523 }),
524 async (history) => {
525 reach.beginHistory()
526 const failure =
527 history.cause === `error`
528 ? new Error(`source startup`)
529 : undefined
530 const client = new DbClient()
531 let starts = 0
532 const descriptor = collectionOptions(
533 `react-handoff-error`,
534 () => ({
535 id: `react-handoff-error`,
536 syncMode: `eager`,
537 autoIndex: `eager`,
538 defaultIndexType: BTreeIndex,
539 getKey: (row: Row) => row.id,
540 startSync: true,
541 gcTime: 0,
542 sync: {
543 sync: ({ fail }) => {
544 starts++
545 if (history.outcome === `throw`) throw failure
546 fail(failure)
547 },
548 },
549 }),
550 )
551 const query = new Query()
552 .from({ item: descriptor })
553 .orderBy(({ item }) => item.id)
554 const caught: Array<unknown> = []
555 let current:
556 | {
557 isLoadingError?: boolean
558 isCrashed?: boolean
559 status: string
560 collection?: {
561 subscriberCount: number
562 cleanup: () => Promise<void>
563 }
564 }
565 | undefined
566 function Consumer() {
567 current =
568 hook === `ordinary`
569 ? useLiveQuery({ query })
570 : useLiveInfiniteQuery(() => query, { pageSize: 1 })
571 return null
572 }
573 const consoleError = vi
574 .spyOn(console, `error`)
575 .mockImplementation(() => {})
576 let mounted: ReturnType<typeof render> | undefined
577 try {
578 if (history.timing === `before-release`) {
579 let threw = false
580 try {
581 client.collection(descriptor)
582 } catch (error) {
583 threw = true
584 expect(error).toBe(failure)
585 }
586 expect(
587 threw,
588 `independent startup owns its exception`,
589 ).toBe(history.outcome === `throw`)
590 expect(client.collection(descriptor).status).toBe(
591 expectedStartHandoff(history).status,
592 )
593 expect(starts).toBe(1)
594 }
595 mounted = render(
596 <DbProvider client={client}>
597 <Boundary caught={caught}>
598 <Consumer />
599 </Boundary>
600 </DbProvider>,
601 )
602 await act(async () => {})
603 expect(starts, `commit does not repeat source startup`).toBe(
604 expectedStartHandoff(history).starts,
605 )
606 reach.reach(`${history.outcome}-${history.timing}`)
607 if (history.cause === `undefined`)
608 reach.reach(`undefined-cause`)
609 if (observation === `error-surface`) {
610 const expected = expectedStartHandoff(history)
611 if (!expected.throws) {
612 expect(caught, `ordinary errors remain readable`).toEqual(
613 [],
614 )
615 expect(current?.status).toBe(expected.status)
616 expect(current?.isLoadingError).toBe(
617 expected.status === `error`,
618 )
619 expect(current?.isCrashed).toBe(
620 expected.status === `crashed`,
621 )
622 } else {
623 expect(
624 caught,
625 `a thrown start remains fail-fast`,
626 ).toHaveLength(1)
627 }
628 }
629 mounted.unmount()
630 expect(current?.collection).toBeDefined()
631 if (current?.collection)
632 expect(
633 current.collection.subscriberCount,
634 `commit/unmount releases every hook owner`,
635 ).toBe(0)
636 } finally {
637 mounted?.unmount()
638 consoleError.mockRestore()
639 await current?.collection?.cleanup()
640 await client.cleanup()
641 }
642 },
643 ),
644 campaign === `fixed`
645 ? { numRuns: oracleRuns(30), seed: 2229 }
646 : oraclePropertyOptions(30, properties[observation]),
647 )
648 reach.assertReached()
649 console.info(
650 `react-error-handoff ${hook} ${observation} ${campaign}`,
651 Object.fromEntries(reach.counts()),
652 )
653 })
654 }
655 }
656 }
657})
658​
659/**
660 * The shared SSR admission judgment rejects server-only rows/readiness, while
661 * cold loading, completed query results and normalized sources remain legal.
662 * Each hook independently generates the same preparation histories. Both real
663 * React server renders compare before browser commit; hydrateRoot must then
664 * report no recovery, and committed sync must replace the seed normally.
665 * Query-only infinite preparation includes its first-page peek-ahead window.
666 * This driver supplies host scheduling, not another expected-result model.
667 */
668describe(`SSR snapshot admission`, () => {
669 const properties = {
670 ordinary: `react.ssr-ordinary`,
671 infinite: `react.ssr-infinite`,
672 } as const
673 for (const hook of [`ordinary`, `infinite`] as const) {
674 const makeReach = () =>
675 createOracleReach(`ssr-${hook}`, [
676 `cold-loading`,
677 `unbacked-ready-empty`,
678 `unbacked-rows`,
679 `query-result`,
680 `normalized-ready`,
681 `normalized-partial`,
682 `pending-query`,
683 `server-write`,
684 `browser-write`,
685 `same-query-preload`,
686 ])
687 async function checkHistory(
688 history: SsrSnapshotHistory,
689 reach: ReturnType<typeof makeReach>,
690 ) {
691 reach.beginHistory()
692 const expected = expectedSsrSnapshot(history)
693 const starts = { server: 0, browser: 0 }
694 const writers = new Map<`server` | `browser`, (name: string) => void>()
695 const descriptor = collectionOptions(`ssr-admission`, (client) => ({
696 id: `ssr-admission`,
697 getKey: (row: { id: string; name: string }) => row.id,
698 autoIndex: `eager`,
699 defaultIndexType: BTreeIndex,
700 sync: {
701 sync: ({ begin, write, commit, markReady }) => {
702 const runtime = client.requireDependency<`server` | `browser`>(
703 `runtime`,
704 )
705 starts[runtime]++
706 writers.set(runtime, (name) => {
707 begin()
708 write({ type: `insert`, value: { id: `late`, name } })
709 commit()
710 })
711 begin()
712 for (const row of history.rows)
713 write({
714 type: `insert`,
715 value: {
716 ...row,
717 name: runtime === `server` ? row.name : `browser ${row.id}`,
718 },
719 })
720 commit()
721 if (runtime === `browser` || history.sourceState === `ready`)
722 markReady()
723 },
724 },
725 }))
726 const query = new Query()
727 .from({ person: descriptor })
728 .orderBy(({ person }) => person.id)
729 .select(({ person }) => ({ id: person.id, name: person.name }))
730 const server = new DbClient({ runtime: `server` })
731 const browser = new DbClient({ runtime: `browser` })
732 server._setSsrServerCleanupEnabled(true)
733 browser._setSsrServerCleanupEnabled(true)
734 let root: Root | undefined
735 const host = document.createElement(`div`)
736 const recoveries: Array<unknown> = []
737 let unmount: (() => void) | undefined
738 const useResult = () =>
739 hook === `ordinary`
740 ? useLiveQuery({ query })
741 : useLiveInfiniteQuery(() => query, { pageSize: 1 })
742 function Consumer() {
743 const result = useResult()
744 return (
745 <output
746 data-status={result.status}
747 data-ready={result.isReady}
748 data-loading={result.isLoading}
749 data-idle={result.isIdle}
750 data-loading-error={result.isLoadingError}
751 data-crashed={result.isCrashed}
752 >
753 {result.data.map((row) => (
754 <span key={row.id}>{row.name}</span>
755 ))}
756 </output>
757 )
758 }
759 const app = (client: DbClient) => (
760 <DbProvider client={client}>
761 <Consumer />
762 </DbProvider>
763 )
764 try {
765 if (history.sourceState !== `idle`) {
766 const warming = server.preloadLiveQuery({
767 query: new Query()
768 .from({ person: descriptor })
769 .select(({ person }) => ({ id: person.id })),
770 })
771 if (history.sourceState === `ready`) await warming
772 else void warming.catch(() => {})
773 }
774 // Explicit materialization registers normalized source rows for
775 // dehydration. The warming query established this fixture's rows;
776 // registration, rather than a second preload, makes them portable.
777 if (history.preparation === `source`) server.collection(descriptor)
778 if (
779 history.preparation === `query` ||
780 history.preparation === `pending-query`
781 ) {
782 const preload = server.preloadLiveQuery({
783 query: hook === `ordinary` ? query : query.limit(2).offset(0),
784 })
785 if (history.preparation === `query`) await preload
786 else void preload.catch(() => {})
787 }
788 let html: string | undefined
789 let failure: unknown
790 try {
791 html = renderSsr(app(server))
792 } catch (error) {
793 failure = error
794 }
795 if (expected.rejects) {
796 expect(
797 failure,
798 `SSR must reject untransported rows or readiness`,
799 ).toBeInstanceOf(Error)
800 expect(String(failure)).toMatch(/SSR.*(?:preload|hydrat)/i)
801 // The same warm source is ordinary valid browser usage.
802 const mounted = renderHook(useResult, {
803 wrapper: ({ children }: { children: ReactNode }) => (
804 <DbProvider client={server}>{children}</DbProvider>
805 ),
806 })
807 unmount = mounted.unmount
808 expect(
809 mounted.result.current.data.map((row) => ({
810 id: row.id,
811 name: row.name,
812 })),
813 ).toEqual(
814 hook === `ordinary` ? history.rows : history.rows.slice(0, 1),
815 )
816 reach.reach(
817 history.rows.length ? `unbacked-rows` : `unbacked-ready-empty`,
818 )
819 } else {
820 expect(failure, `prepared and cold SSR remain legal`).toBeUndefined()
821 if (history.serverWrite && history.sourceState !== `idle`) {
822 writers.get(`server`)!(`late server`)
823 reach.reach(`server-write`)
824 }
825 browser.hydrate(server.dehydrate())
826 if (history.browserWrite) {
827 if (history.browserPreload) {
828 await browser.preloadLiveQuery({
829 query: hook === `infinite` ? query.limit(2).offset(0) : query,
830 })
831 reach.reach(`same-query-preload`)
832 }
833 await browser.collection(descriptor).preload()
834 writers.get(`browser`)!(`late browser`)
835 reach.reach(`browser-write`)
836 }
837 let initialBrowserHtml: string | undefined, hydrationError: unknown
838 try {
839 initialBrowserHtml = renderToString(app(browser))
840 } catch (error) {
841 hydrationError = error
842 }
843 host.innerHTML = html!
844 expect(
845 host.querySelector(`output`)?.getAttribute(`data-status`),
846 ).toBe(expected.status)
847 expect(
848 [...host.querySelectorAll(`span`)].map((span) => span.textContent),
849 ).toEqual(
850 (hook === `ordinary`
851 ? expected.rows
852 : expected.rows.slice(0, 1)
853 ).map((row) => row.name),
854 )
855 expect(
856 starts.browser,
857 `hydration read starts no additional source`,
858 ).toBe(history.browserWrite ? 1 : 0)
859 document.body.append(host)
860 await act(async () => {
861 root = hydrateRoot(host, app(browser), {
862 onRecoverableError: (error) => recoveries.push(error),
863 })
864 await Promise.resolve()
865 })
866 expect(
867 hydrationError,
868 `browser activity cannot become an SSR programming error`,
869 ).toBeUndefined()
870 expect(
871 initialBrowserHtml,
872 `initial rows and every rendered status flag match`,
873 ).toBe(html)
874 expect(
875 recoveries,
876 `React receives the same snapshot without recovery`,
877 ).toEqual([])
878 expect(
879 starts.browser,
880 `committed browser demand starts the source`,
881 ).toBe(1)
882 expect(
883 host.querySelector(`output`)?.getAttribute(`data-status`),
884 ).toBe(`ready`)
885 expect(
886 [...host.querySelectorAll(`span`)].map((span) => span.textContent),
887 ).toEqual(
888 hook === `ordinary`
889 ? [
890 ...history.rows.map((row) => `browser ${row.id}`),
891 ...(history.browserWrite
892 ? [`late browser`]
893 : history.preparation === `source` &&
894 history.serverWrite &&
895 history.sourceState !== `idle`
896 ? [`late server`]
897 : []),
898 ]
899 : [
900 ...history.rows.map((row) => `browser ${row.id}`),
901 ...(history.browserWrite
902 ? [`late browser`]
903 : history.preparation === `source` &&
904 history.serverWrite &&
905 history.sourceState !== `idle`
906 ? [`late server`]
907 : []),
908 ].slice(0, 1),
909 )
910 if (history.preparation === `query`) reach.reach(`query-result`)
911 else if (
912 history.preparation === `source` &&
913 history.sourceState !== `idle`
914 )
915 reach.reach(
916 history.sourceState === `loading`
917 ? `normalized-partial`
918 : `normalized-ready`,
919 )
920 else reach.reach(`cold-loading`)
921 }
922 if (history.preparation === `pending-query`)
923 reach.reach(`pending-query`)
924 } finally {
925 unmount?.()
926 act(() => root?.unmount())
927 host.remove()
928 await browser.cleanup()
929 await server.cleanup()
930 }
931 }
932 for (const history of ssrSnapshotExamples) {
933 it(`replays ${hook} SSR ${history.preparation}/${history.sourceState}/${history.rows.length}`, async () => {
934 await checkHistory(history, makeReach())
935 })
936 }
937 for (const campaign of [`fixed`, `random`] as const) {
938 it(`${hook} admits reproducible SSR snapshots (${campaign})`, async () => {
939 const reach = makeReach()
940 await fc.assert(
941 fc.asyncProperty(ssrSnapshotHistoryArbitrary, (history) =>
942 checkHistory(history, reach),
943 ),
944 {
945 ...(campaign === `fixed`
946 ? { numRuns: oracleRuns(120), seed: 2229 }
947 : oraclePropertyOptions(120, properties[hook])),
948 examples: ssrSnapshotExamples.map((history) => [history]),
949 },
950 )
951 reach.assertReached()
952 console.info(
953 `ssr-admission ${hook} ${campaign}`,
954 Object.fromEntries(reach.counts()),
955 )
956 })
957 }
958 }
959})
960​
961// Streaming must capture the view it actually renders, even when the adapter
962// publishes again in the microtask before its preload promise captures a result.
963// This metamorphic observation compares the final host markup with transport.
964// An ordinary sibling may already have rendered loading before Suspense starts
965// the same query. Each reader owes its own rendered view during hydration;
966// preserving the earlier view cannot prevent the explicit preload completing.
967// Synchronous act permits the ordinary sibling's effects before React hydrates
968// its Suspense boundary. That sibling must not consume another reader's seed.
969// The readiness schedule also holds source writes and markReady until an ordinary
970// server read occurs. With Suspense first, the Router has already queued a pending
971// stream before that ordinary reader contributes its loading view. Both reader
972// orders must transfer each hook's own view; a final direct dehydrate is not a
973// substitute for the actual queued Router chunks. The provider and Router render
974// callback are controlled premises, not a deployed Start or Electric witness.
975// A held source may instead report an initial-sync error. The ordinary reader
976// already rendered loading, while Suspense renders its server fallback. Error
977// object fidelity is outside this relation; the ordinary first-view status is
978// still owed before browser commit, and the Suspense boundary may recover.
979async function checkStreamCut(
980 history: SsrStreamHistory,
981 reach: ReturnType<typeof createStreamReach>,
982) {
983 reach.beginHistory()
984 const authoredRows = Array.from({ length: history.count }, (_, i) => ({
985 id: String(i),
986 name: `first ${i}`,
987 }))
988 const client = new DbClient({ runtime: `server` })
989 const ordinaryRendered = createDeferred<void>()
990 let releaseServerSource: (() => void) | undefined
991 const sourceError = new Error(`stream source unavailable`)
992 const descriptor = collectionOptions(`stream-render-cut`, (owner) => ({
993 id: `stream-render-cut`,
994 getKey: (row: { id: string; name: string }) => row.id,
995 sync: {
996 sync: ({ begin, write, commit, markReady, fail }) => {
997 const rows =
998 owner !== client && history.browserWrite
999 ? [{ id: `0`, name: `browser only` }]
1000 : authoredRows
1001 const publish = () => {
1002 if (owner === client && history.sourceError) {
1003 fail(sourceError)
1004 return
1006 begin()
1007 for (const row of rows) write({ type: `insert`, value: row })
1008 commit()
1009 markReady()
1010 queueMicrotask(() => {
1011 for (let i = 0; i < history.writes; i++) {
1012 begin()
1013 write({
1014 type: rows.length || i ? `update` : `insert`,
1015 value: { id: `0`, name: `later ${i}` },
1016 })
1017 commit()
1019 })
1021 if (owner === client && history.holdSourceReadiness)
1022 releaseServerSource = publish
1023 else publish()
1024 },
1025 },
1026 }))
1027 client._setSsrStreamingEnabled(true)
1028 let finishRouterRender = () => {}
1029 const router: {
1030 isServer: boolean
1031 options: {
1032 context: { dbClient: DbClient }
1033 dehydrate?: () => Promise<DehydratedRouterDbState>
1035 serverSsr: {
1036 isDehydrated: () => boolean
1037 onRenderFinished: (callback: () => void) => void
1039 } = {
1040 isServer: true,
1041 options: { context: { dbClient: client } },
1042 serverSsr: {
1043 isDehydrated: () => true,
1044 onRenderFinished: (callback) => {
1045 finishRouterRender = callback
1046 },
1047 },
1049 // The real Router adapter supplies the transport for the same generated law.
1050 // Its SSR callback is controlled; this is not a deployed Start host witness.
1051 Reflect.apply(routerWithDbClient, undefined, [router, client])
1052 const initialRouterState = await router.options.dehydrate!()
1053 const query = new Query()
1054 .from({ row: descriptor })
1055 .select(({ row }) => ({ name: row.name }))
1056 const ordinaryReads: Array<{ status: string; names: Array<string> }> = []
1057 const suspenseReads: Array<Array<string>> = []
1058 function Consumer() {
1059 const result = useLiveSuspenseQuery({ query })
1060 suspenseReads.push(result.data.map((row) => row.name))
1061 return <span>{result.data.map((row) => row.name).join(`,`)}</span>
1063 function OrdinaryConsumer() {
1064 const result = useLiveQuery({ query })
1065 ordinaryReads.push({
1066 status: result.status,
1067 names: result.data.map((row) => row.name),
1068 })
1069 if (typeof window === `undefined`) ordinaryRendered.resolve()
1070 return (
1071 <output data-status={result.status}>
1072 {result.data.map((row) => row.name).join(`,`)}
1073 </output>
1076 class StreamBoundary extends Component<
1077 { children: ReactNode },
1078 { failed: boolean }
1079 > {
1080 state = { failed: false }
1081 static getDerivedStateFromError() {
1082 return { failed: true }
1084 render() {
1085 return this.state.failed ? <b>query failed</b> : this.props.children
1088 const browserWindow = globalThis.window
1089 vi.stubGlobal(`window`, undefined)
1090 try {
1091 const errors: Array<unknown> = []
1092 const renderedHtml = new Promise<string>((resolve, reject) => {
1093 let text = ``
1094 const sink = new Writable({
1095 write(chunk, _encoding, done) {
1096 text += chunk.toString()
1097 done()
1098 },
1099 })
1100 sink.on(`finish`, () => resolve(text))
1101 sink.on(`error`, reject)
1102 const stream = renderToPipeableStream(
1103 <DbProvider client={client}>
1104 {history.ordinaryFirst && <OrdinaryConsumer />}
1105 <StreamBoundary>
1106 <Suspense fallback={<span>loading</span>}>
1107 <Consumer />
1108 </Suspense>
1109 </StreamBoundary>
1110 {history.ordinaryLast && <OrdinaryConsumer />}
1111 </DbProvider>,
1113 onAllReady() {
1114 stream.pipe(sink)
1115 },
1116 onError(error) {
1117 errors.push(error)
1118 },
1119 },
1121 })
1122 if (history.holdSourceReadiness) {
1123 // Holding readiness is legal only with an ordinary sibling. Its actual
1124 // public read, rather than a delay, proves this source-loading cut ran.
1125 await ordinaryRendered.promise
1126 expect(ordinaryReads[0], `held source renders ordinary loading`).toEqual({
1127 status: `loading`,
1128 names: [],
1129 })
1130 expect(
1131 releaseServerSource,
1132 `Suspense entered the held source`,
1133 ).toBeTypeOf(`function`)
1134 reach.reach(
1135 history.ordinaryFirst ? `held-ordinary-first` : `held-suspense-first`,
1137 releaseServerSource!()
1138 releaseServerSource = undefined
1139 } else {
1140 reach.reach(`synchronous-readiness`)
1142 const html = await renderedHtml
1143 if (history.sourceError) {
1144 // Live-query startup may wrap the provider's error. The receiving
1145 // premise is failure before readiness, not cross-boundary error identity.
1146 expect(
1147 errors.length,
1148 `Suspense received the held provider failure`,
1149 ).toBeGreaterThan(0)
1150 reach.reach(`held-source-error`)
1151 } else {
1152 expect(errors).toEqual([])
1153 const rendered = html.match(/<span>([^<]*)<\/span>/)?.[1]
1154 expect(rendered).toBe(authoredRows.map((row) => row.name).join(`,`))
1155 const transport = client
1156 .dehydrate({ shouldDehydrateLiveQuery: () => true })
1157 .liveQueries!.find(
1158 (result) => result.queryHash === getLiveQueryHash({ query }),
1159 )!
1160 const snapshot = transport.snapshot ?? (await transport.promise)
1161 expect(
1162 snapshot?.rows.map((row) => (row.value as { name: string }).name),
1163 `stream transport reproduces its rendered view`,
1164 ).toEqual(authoredRows.map((row) => row.name))
1166 if (history.ordinaryFirst || history.ordinaryLast) {
1167 const firstServerRead = ordinaryReads[0]
1168 expect(
1169 firstServerRead,
1170 `ordinary server hook returned a view`,
1171 ).toBeDefined()
1172 ordinaryReads.length = 0
1173 const firstSuspenseRead = suspenseReads[0]
1174 if (!history.sourceError)
1175 expect(
1176 firstSuspenseRead,
1177 `Suspense server hook returned its ready view`,
1178 ).toBeDefined()
1179 suspenseReads.length = 0
1180 vi.stubGlobal(`window`, browserWindow)
1181 const browser = new DbClient({ runtime: `browser` })
1182 browser.hydrate(initialRouterState.dehydratedDbClient)
1183 const reader = initialRouterState.dbStream.getReader()
1184 finishRouterRender()
1185 try {
1186 for (;;) {
1187 const chunk = await reader.read()
1188 if (chunk.done) break
1189 browser.hydrate({
1190 ...chunk.value,
1191 liveQueries: chunk.value.liveQueries?.map(
1192 ({ promise, ...data }) => ({
1193 ...JSON.parse(JSON.stringify(data)),
1194 ...(promise
1195 ? {
1196 promise: promise.then((value) =>
1197 JSON.parse(JSON.stringify(value)),
1198 ),
1200 : {}),
1201 }),
1202 ),
1203 })
1205 } finally {
1206 reader.releaseLock()
1208 const host = document.createElement(`div`)
1209 host.innerHTML = html
1210 let root: Root | undefined
1211 const hydrationErrors: Array<unknown> = []
1212 try {
1213 const hydrate = () => {
1214 root = hydrateRoot(
1215 host,
1216 <DbProvider client={browser}>
1217 {history.ordinaryFirst && <OrdinaryConsumer />}
1218 <StreamBoundary>
1219 <Suspense fallback={<span>loading</span>}>
1220 <Consumer />
1221 </Suspense>
1222 </StreamBoundary>
1223 {history.ordinaryLast && <OrdinaryConsumer />}
1224 </DbProvider>,
1225 { onRecoverableError: (error) => hydrationErrors.push(error) },
1228 await act(
1229 history.splitHydration
1230 ? hydrate
1231 : async () => {
1232 hydrate()
1233 await Promise.resolve()
1234 },
1236 reach.reach(
1237 history.holdSourceReadiness
1238 ? `held-router-browser-handoff`
1239 : `synchronous-router-browser-handoff`,
1241 const firstBrowserSuspenseRead = suspenseReads[0]
1242 expect(
1243 ssrStreamHydrationMismatches([
1245 reader: `ordinary`,
1246 server: firstServerRead!,
1247 hydration: ordinaryReads[0],
1248 },
1249 ...(history.sourceError
1250 ? []
1251 : [
1253 reader: `Suspense`,
1254 server: { status: `ready`, names: firstSuspenseRead! },
1255 hydration: firstBrowserSuspenseRead
1256 ? { status: `ready`, names: firstBrowserSuspenseRead }
1257 : undefined,
1258 },
1259 ]),
1260 ]),
1261 `each reader's first hydration view matches its own server view`,
1262 ).toEqual([])
1263 if (!history.sourceError) {
1264 expect(hydrationErrors).toEqual([])
1266 } finally {
1267 await act(async () => {
1268 root?.unmount()
1269 await Promise.resolve()
1270 })
1271 await browser.cleanup()
1274 reach.reach(history.count ? `nonempty` : `empty`)
1275 reach.reach(history.writes ? `later-publication` : `unchanged`)
1276 reach.reach(
1277 history.ordinaryFirst
1278 ? `ordinary-first`
1279 : history.ordinaryLast
1280 ? `suspense-first`
1281 : `suspense-only`,
1283 if (history.ordinaryFirst || history.ordinaryLast) {
1284 reach.reach(
1285 history.splitHydration ? `split-hydration` : `together-hydration`,
1287 reach.reach(history.browserWrite ? `browser-different` : `browser-same`)
1289 } finally {
1290 releaseServerSource?.()
1291 vi.stubGlobal(`window`, browserWindow)
1292 finishRouterRender()
1293 await client.cleanup()
1296const createStreamReach = () =>
1297 createOracleReach(`react-stream-cut`, [
1298 `empty`,
1299 `nonempty`,
1300 `later-publication`,
1301 `unchanged`,
1302 `ordinary-first`,
1303 `suspense-first`,
1304 `suspense-only`,
1305 `browser-different`,
1306 `browser-same`,
1307 `split-hydration`,
1308 `together-hydration`,
1309 `synchronous-readiness`,
1310 `held-ordinary-first`,
1311 `held-suspense-first`,
1312 `held-router-browser-handoff`,
1313 `synchronous-router-browser-handoff`,
1314 `held-source-error`,
1315 ])
1316describe(`stream render snapshot cut`, () => {
1317 for (const ordinaryFirst of [false, true])
1318 for (const splitHydration of [false, true])
1319 it(`retains an ordinary loading view when its stream later fails, ordinaryFirst=${ordinaryFirst}, split=${splitHydration}`, () =>
1320 checkStreamCut(
1322 count: 0,
1323 writes: 0,
1324 ordinaryFirst,
1325 ordinaryLast: !ordinaryFirst,
1326 holdSourceReadiness: true,
1327 sourceError: true,
1328 splitHydration,
1329 },
1330 createStreamReach(),
1331 ))
1332 for (const count of [0, 1])
1333 for (const ordinaryFirst of [false, true])
1334 for (const splitHydration of [false, true])
1335 it(`hydrates each held-source view with count=${count}, ordinaryFirst=${ordinaryFirst}, split=${splitHydration}`, () =>
1336 checkStreamCut(
1338 count,
1339 writes: 0,
1340 ordinaryFirst,
1341 ordinaryLast: !ordinaryFirst,
1342 holdSourceReadiness: true,
1343 browserWrite: true,
1344 splitHydration,
1345 },
1346 createStreamReach(),
1347 ))
1348 it(`keeps an ordinary reader from blocking a shared Suspense preload`, () =>
1349 checkStreamCut(
1350 { count: 1, writes: 0, ordinaryFirst: true, browserWrite: true },
1351 createStreamReach(),
1352 ))
1353 it(`hydrates an ordinary reader rendered after its Suspense sibling`, () =>
1354 checkStreamCut(
1355 { count: 1, writes: 0, ordinaryLast: true, browserWrite: true },
1356 createStreamReach(),
1357 ))
1358 it(`retains the Suspense view after its ordinary sibling commits`, () =>
1359 checkStreamCut(
1361 count: 1,
1362 writes: 0,
1363 ordinaryFirst: true,
1364 browserWrite: true,
1365 splitHydration: true,
1366 },
1367 createStreamReach(),
1368 ))
1369 for (const history of [
1370 { count: 0, writes: 1 },
1371 { count: 1, writes: 1 },
1372 { count: 1, writes: 0 },
1373 ])
1374 it(`replays count=${history.count} later-writes=${history.writes}`, () =>
1375 checkStreamCut(history, createStreamReach()))
1376 for (const campaign of [`fixed`, `random`] as const)
1377 it(`transports the rendered view (${campaign})`, async () => {
1378 const reach = createStreamReach()
1379 try {
1380 await fc.assert(
1381 fc.asyncProperty(
1382 fc
1383 .record({
1384 count: fc.integer({ min: 0, max: 3 }),
1385 writes: fc.integer({ min: 0, max: 3 }),
1386 ordinaryFirst: fc.boolean(),
1387 ordinaryLast: fc.boolean(),
1388 browserWrite: fc.boolean(),
1389 splitHydration: fc.boolean(),
1390 holdSourceReadiness: fc.boolean(),
1391 sourceError: fc.boolean(),
1392 })
1393 .map((history) => {
1394 // A held provider needs an ordinary read to release it; a
1395 // Suspense-only history retains synchronous source readiness.
1396 const holdSourceReadiness =
1397 history.holdSourceReadiness &&
1398 (history.ordinaryFirst || history.ordinaryLast)
1399 // Failure is held until a real ordinary loading read. Empty
1400 // sources isolate lifecycle status from error-row retention.
1401 const sourceError = history.sourceError && holdSourceReadiness
1402 return {
1403 ...history,
1404 ordinaryLast: !history.ordinaryFirst && history.ordinaryLast,
1405 holdSourceReadiness,
1406 sourceError,
1407 count: sourceError ? 0 : history.count,
1408 writes: sourceError ? 0 : history.writes,
1410 }),
1411 (history) => checkStreamCut(history, reach),
1412 ),
1413 campaign === `fixed`
1414 ? { numRuns: oracleRuns(40), seed: 2229 }
1415 : oraclePropertyOptions(40, `react.ssr-stream-cut`),
1417 } finally {
1418 // Keep reached premises visible when the first refinement check fails.
1419 console.info(
1420 `react-stream-cut ${campaign}`,
1421 Object.fromEntries(reach.counts()),
1424 reach.assertReached()
1425 })