Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import {
3 BasicIndex,
4 IR,
5 createCollection,
6 createLiveQueryCollection,
7 eq,
8} from '@tanstack/db'
9import { describe, expect, it, vi } from 'vitest'
10import { TraceAssertionError } from '../../db/tests/trace-runner.js'
11import { createDeferred } from '../../db/src/deferred.js'
12import { queryCollectionOptions } from '../src/query.js'
13import type { QueryFunctionContext } from '@tanstack/query-core'
14import type { LoadSubsetOptions, SyncMetadataApi } from '@tanstack/db'
15
16/**
17 * # Does Query-backed loadSubset preserve identity and lifecycle?
18 *
19 * Canonically equal demands share one Query transport. Distinct predicates,
20 * values, order, cursor, and scope remain distinct. The final live-query owner
21 * controls cancellation, and a replacement owner starts fresh after abort.
22 * Initial failure reaches existing and late dependents; recovery becomes public
23 * only after every failed source recovers. A later refetch failure retains the
24 * last ready snapshot.
25 *
26 * Small identity forms and lifecycle histories drive a real QueryClient and
27 * Collection. The oracle records query calls, values, request options, abort
28 * signals, metadata, source and dependent status, exact errors, and cleanup.
29 * Fault cases prove correct call counts cannot hide wrong returned values or a
30 * stale replacement snapshot.
31 */
32
33type Row = {
34 id: string
35 group?: string
36}
37
38let collectionSequence = 0
39
40function createQueryClient(): QueryClient {
41 return new QueryClient({
42 defaultOptions: {
43 queries: {
44 gcTime: Number.POSITIVE_INFINITY,
45 retry: false,
46 staleTime: Number.POSITIVE_INFINITY,
47 },
48 },
49 })
50}
51
52async function expectInitialQueryFailureStatus(): Promise<void> {
53 const error = new Error(`initial query failed`)
54 const queryClient = createQueryClient()
55 const id = `load-subset-error-status-${collectionSequence++}`
56 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
57 const queryFn = vi
58 .fn()
59 .mockRejectedValueOnce(error)
60 .mockResolvedValueOnce([{ id: `recovered` }])
61 const collection = createCollection(
62 queryCollectionOptions<Row>({
63 id,
64 queryClient,
65 queryKey: [id],
66 queryFn,
67 getKey: (row) => row.id,
68 startSync: true,
69 retry: false,
70 }),
71 )
72 const live = createLiveQueryCollection((query) =>
73 query.from({ row: collection }).select(({ row }) => ({ id: row.id })),
74 )
75 const preloadOutcomes = Promise.allSettled([
76 collection.preload(),
77 live.preload(),
78 ])
79
80 try {
81 await vi.waitFor(() => {
82 expect(collection.utils.lastError).toBe(error)
83 expect(collection.utils.isError).toBe(true)
84 })
85 expect(loggedError).toHaveBeenCalled()
86 try {
87 expect(collection.status).toBe(`error`)
88 expect(live.status).toBe(`error`)
89 expect((await preloadOutcomes).map(({ status }) => status)).toEqual([
90 `rejected`,
91 `rejected`,
92 ])
93 } catch (caught) {
94 throw new TraceAssertionError(0, caught)
95 }
96
97 await collection.utils.clearError()
98 await vi.waitFor(() => {
99 expect(collection.status).toBe(`ready`)
100 expect(collection.get(`recovered`)).toBeDefined()
101 expect(live.status).toBe(`ready`)
102 expect(live.get(`recovered`)).toBeDefined()
103 })
104 await expect(collection.preload()).resolves.toBeUndefined()
105 await expect(live.preload()).resolves.toBeUndefined()
106 } finally {
107 await live.cleanup()
108 await collection.cleanup()
109 queryClient.clear()
110 loggedError.mockRestore()
111 }
112}
113
114async function expectLateDependentObservesInitialFailure(): Promise<void> {
115 const error = new Error(`source failed before dependent construction`)
116 const queryClient = createQueryClient()
117 const id = `load-subset-late-dependent-error-${collectionSequence++}`
118 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
119 const collection = createCollection(
120 queryCollectionOptions<Row>({
121 id,
122 queryClient,
123 queryKey: [id],
124 queryFn: vi.fn().mockRejectedValue(error),
125 getKey: (row) => row.id,
126 startSync: true,
127 retry: false,
128 }),
129 )
130
131 await expect(collection.preload()).rejects.toBe(error)
132 expect(collection.status).toBe(`error`)
133
134 const live = createLiveQueryCollection((query) =>
135 query.from({ row: collection }).select(({ row }) => ({ id: row.id })),
136 )
137 const livePreload = live.preload()
138 void livePreload.catch(() => undefined)
139
140 try {
141 expect(live.status).toBe(`error`)
142 await expect(livePreload).rejects.toThrow()
143 } finally {
144 await live.cleanup()
145 await collection.cleanup()
146 await Promise.allSettled([livePreload])
147 queryClient.clear()
148 loggedError.mockRestore()
149 }
150}
151
152async function expectEveryFailedSourceToRecover(): Promise<void> {
153 const createControlledSource = (id: string) => {
154 let fail: () => void = () => {
155 throw new Error(`Source '${id}' has not started`)
156 }
157 let recover: (row: Row) => void = (_row) => {
158 throw new Error(`Source '${id}' has not started`)
159 }
160 const collection = createCollection<Row>({
161 id,
162 getKey: (row) => row.id,
163 startSync: false,
164 autoIndex: `eager`,
165 defaultIndexType: BasicIndex,
166 sync: {
167 sync: ({ begin, write, commit, markReady, markError }) => {
168 fail = markError
169 recover = (row) => {
170 begin()
171 write({ type: `insert`, value: row })
172 commit()
173 markReady()
174 }
175 },
176 },
177 })
178 return {
179 collection,
180 fail: () => fail(),
181 recover: (row: Row) => recover(row),
182 }
183 }
184
185 const left = createControlledSource(
186 `load-subset-multi-error-left-${collectionSequence++}`,
187 )
188 const right = createControlledSource(
189 `load-subset-multi-error-right-${collectionSequence++}`,
190 )
191 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
192 const live = createLiveQueryCollection((query) =>
193 query
194 .from({ left: left.collection })
195 .join({ right: right.collection }, ({ left: leftRow, right: rightRow }) =>
196 eq(leftRow.id, rightRow.id),
197 )
198 .select(({ left: row }) => ({ id: row.id })),
199 )
200 const preload = live.preload()
201 void preload.catch(() => undefined)
202
203 try {
204 left.fail()
205 right.fail()
206 await expect(preload).rejects.toThrow()
207 expect(live.status).toBe(`error`)
208
209 left.recover({ id: `shared` })
210 expect(left.collection.status).toBe(`ready`)
211 expect(right.collection.status).toBe(`error`)
212 expect(live.status).toBe(`error`)
213
214 right.recover({ id: `shared` })
215 await expect(live.preload()).resolves.toBeUndefined()
216 expect(live.status).toBe(`ready`)
217 expect(live.toArray.map((row) => row.id)).toEqual([`shared`])
218 } finally {
219 await live.cleanup()
220 await left.collection.cleanup()
221 await right.collection.cleanup()
222 await Promise.allSettled([preload])
223 loggedError.mockRestore()
224 }
225}
226
227async function expectRefetchFailureKeepsReadySnapshot(): Promise<void> {
228 const error = new Error(`refetch failed`)
229 const queryClient = createQueryClient()
230 const id = `load-subset-refetch-status-${collectionSequence++}`
231 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
232 const queryFn = vi
233 .fn()
234 .mockResolvedValueOnce([{ id: `cached` }])
235 .mockRejectedValueOnce(error)
236 const collection = createCollection(
237 queryCollectionOptions<Row>({
238 id,
239 queryClient,
240 queryKey: [id],
241 queryFn,
242 getKey: (row) => row.id,
243 startSync: true,
244 retry: false,
245 }),
246 )
247 const live = createLiveQueryCollection((query) =>
248 query.from({ row: collection }).select(({ row }) => ({ id: row.id })),
249 )
250
251 try {
252 await live.preload()
253 await collection.utils.refetch()
254 await vi.waitFor(() => {
255 expect(collection.utils.lastError).toBe(error)
256 })
257 expect(collection.status).toBe(`ready`)
258 expect(live.status).toBe(`ready`)
259 expect(collection.get(`cached`)).toBeDefined()
260 expect(live.get(`cached`)).toBeDefined()
261 } finally {
262 await live.cleanup()
263 await collection.cleanup()
264 queryClient.clear()
265 loggedError.mockRestore()
266 }
267}
268
269async function expectDeferredStartupReadyDoesNotOverrideError(): Promise<void> {
270 // Internal ordering seam: this deliberately reuses old sync controls and
271 // observers. It does not establish a public cleanup/restart path; real
272 // cleanup clears those observers before a new sync run starts.
273 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
274 const queryClient = createQueryClient()
275 const id = `load-subset-deferred-ready-${collectionSequence++}`
276 const queryError = new Error(`cached observer failed`)
277 const queryFn = vi.fn().mockRejectedValue(queryError)
278 const baseOptions = queryCollectionOptions<Row>({
279 id,
280 queryClient,
281 queryKey: [id],
282 queryFn,
283 getKey: (row) => row.id,
284 startSync: true,
285 syncMode: `on-demand`,
286 retry: false,
287 })
288 const originalSync = baseOptions.sync
289 let syncParams!: Parameters<typeof originalSync.sync>[0]
290 const collection = createCollection({
291 ...baseOptions,
292 sync: {
293 sync: (params) => {
294 syncParams = params
295 return originalSync.sync(params)
296 },
297 },
298 })
299
300 const firstLoad = collection._sync.loadSubset({})
301 if (!(firstLoad instanceof Promise)) {
302 throw new Error(`The failing query must be asynchronous`)
303 }
304 await expect(firstLoad).rejects.toBe(queryError)
305 expect(collection.status).toBe(`ready`)
306
307 let releaseScan!: () => void
308 const scanReleased = new Promise<void>((resolve) => {
309 releaseScan = resolve
310 })
311 let resolveMaintenanceDelete!: () => void
312 const maintenanceDeleted = new Promise<void>((resolve) => {
313 resolveMaintenanceDelete = resolve
314 })
315 type MetadataWithPersistedScan = SyncMetadataApi<string | number> & {
316 row: SyncMetadataApi<string | number>[`row`] & {
317 scanPersisted: () => Promise<
318 Array<{ key: string | number; value: Row; metadata?: unknown }>
319 >
320 }
321 }
322 const metadata: MetadataWithPersistedScan = {
323 row: {
324 get: () => undefined,
325 set: () => {},
326 delete: () => {},
327 scanPersisted: async () => {
328 await scanReleased
329 return []
330 },
331 },
332 collection: {
333 get: () => undefined,
334 set: () => {},
335 delete: () => {
336 resolveMaintenanceDelete()
337 },
338 list: () => [
339 {
340 key: `queryCollection:gc:expired`,
341 value: { queryHash: `expired`, mode: `ttl`, expiresAt: 0 },
342 },
343 ],
344 },
345 }
346
347 collection._lifecycle.setStatus(`cleaned-up`)
348 collection._lifecycle.setStatus(`loading`)
349 const secondSync = originalSync.sync({ ...syncParams, metadata })
350
351 try {
352 expect(collection.status).toBe(`error`)
353 releaseScan()
354 await maintenanceDeleted
355 for (let turn = 0; turn < 10; turn++) await Promise.resolve()
356 expect(collection.status).toBe(`error`)
357 expect(collection.utils.lastError).toBe(queryError)
358 } finally {
359 if (typeof secondSync === `function`) {
360 await secondSync()
361 } else {
362 await secondSync?.cleanup?.()
363 }
364 await collection.cleanup()
365 queryClient.clear()
366 loggedError.mockRestore()
367 }
368}
369
370async function expectEquivalentPredicatesShareOneLoad(
371 form: `commutative-and` | `commutative-or` | `reversed-equality`,
372): Promise<void> {
373 const { queryClient, collection, queryFn } = createOnDemandCollection(
374 `load-subset-canonical-predicate`,
375 [{ id: `a`, group: `x` }],
376 )
377 const firstComparison = new IR.Func<boolean>(`eq`, [
378 new IR.PropRef([`id`]),
379 new IR.Value(`a`),
380 ])
381 const secondComparison = new IR.Func<boolean>(`eq`, [
382 new IR.PropRef([`group`]),
383 new IR.Value(`x`),
384 ])
385 let first: IR.BasicExpression<boolean>
386 let second: IR.BasicExpression<boolean>
387 switch (form) {
388 case `commutative-and`:
389 first = new IR.Func(`and`, [firstComparison, secondComparison])
390 second = new IR.Func(`and`, [secondComparison, firstComparison])
391 break
392 case `commutative-or`:
393 first = new IR.Func(`or`, [firstComparison, secondComparison])
394 second = new IR.Func(`or`, [secondComparison, firstComparison])
395 break
396 case `reversed-equality`:
397 first = firstComparison
398 second = new IR.Func(`eq`, [new IR.Value(`a`), new IR.PropRef([`id`])])
399 break
400 }
401
402 try {
403 await collection._sync.loadSubset({ where: first })
404 await collection._sync.loadSubset({ where: second })
405 try {
406 expect(queryFn.mock.calls.length).toBe(1)
407 } catch (error) {
408 throw new TraceAssertionError(0, error)
409 }
410 } finally {
411 await collection.cleanup()
412 queryClient.clear()
413 }
414}
415
416async function expectEquivalentComparisonValuesShareOneLoad(
417 firstValue: unknown,
418 secondValue: unknown,
419): Promise<void> {
420 const { queryClient, collection, queryFn } = createOnDemandCollection(
421 `load-subset-comparison-value`,
422 [{ id: `a` }],
423 )
424 const value = new IR.PropRef([`value`])
425
426 try {
427 await collection._sync.loadSubset({
428 where: new IR.Func(`eq`, [value, new IR.Value(firstValue)]),
429 })
430 await collection._sync.loadSubset({
431 where: new IR.Func(`eq`, [value, new IR.Value(secondValue)]),
432 })
433 expect(queryFn).toHaveBeenCalledOnce()
434 } finally {
435 await collection.cleanup()
436 queryClient.clear()
437 }
438}
439
440function createOnDemandCollection(idPrefix: string, rows: Array<Row>) {
441 const queryClient = createQueryClient()
442 const id = `${idPrefix}-${collectionSequence++}`
443 const queryFn = vi.fn().mockResolvedValue(rows)
444 const collection = createCollection(
445 queryCollectionOptions<Row>({
446 id,
447 queryClient,
448 queryKey: [id],
449 queryFn,
450 getKey: (row) => row.id,
451 startSync: true,
452 syncMode: `on-demand`,
453 retry: false,
454 }),
455 )
456 return { queryClient, collection, queryFn }
457}
458
459type IdentityForm =
460 | `commutative-and`
461 | `commutative-or`
462 | `reversed-equality`
463 | `valid Date`
464 | `invalid Date`
465
466type IdentityRow = { id: string; group: string; value: Date }
467type IdentityCheckpoint = {
468 stage: string
469 calls: number
470 requests: Array<LoadSubsetOptions>
471 rows: Array<IdentityRow>
472}
473
474function identityDemandFixture(form: IdentityForm) {
475 const firstDate =
476 form === `invalid Date`
477 ? new Date(Number.NaN)
478 : new Date(`2024-01-15T00:00:00Z`)
479 const secondDate = new Date(`2024-01-16T00:00:00Z`)
480 const rows: Array<IdentityRow> = [
481 { id: `a`, group: `x`, value: firstDate },
482 { id: `b`, group: `y`, value: secondDate },
483 ]
484 const comparison = (field: string, value: unknown, reversed = false) => {
485 const operands = [new IR.PropRef([field]), new IR.Value(value)]
486 return new IR.Func<boolean>(`eq`, reversed ? operands.reverse() : operands)
487 }
488 const predicate = (index: number, reversed = false) => {
489 const row = rows[index]!
490 if (form === `valid Date` || form === `invalid Date`) {
491 return comparison(`value`, new Date(row.value.getTime()), reversed)
492 }
493 const id = comparison(`id`, row.id, reversed)
494 if (form === `reversed-equality`) return id
495 const group = comparison(`group`, row.group)
496 const operands = reversed ? [group, id] : [id, group]
497 return new IR.Func<boolean>(
498 form === `commutative-and` ? `and` : `or`,
499 operands,
500 )
501 }
502 return {
503 rows,
504 first: { where: predicate(0) },
505 equivalent: { where: predicate(0, true) },
506 distinct: { where: predicate(1) },
507 }
508}
509
510function validateIdentityRequest(options: LoadSubsetOptions): void {
511 if (
512 options.orderBy !== undefined ||
513 options.limit !== undefined ||
514 options.offset !== undefined ||
515 options.cursor !== undefined
516 ) {
517 throw new Error(`Identity fixture does not support ordering or windows`)
518 }
519 const validate = (expression: IR.BasicExpression): void => {
520 if (expression.type !== `func` || expression.args.length !== 2) {
521 throw new Error(`Unsupported identity fixture predicate`)
522 }
523 if (expression.name === `and` || expression.name === `or`) {
524 // Validation traverses both branches, even when evaluation short-circuits
525 // or there are no provider rows to evaluate.
526 expression.args.forEach(validate)
527 return
528 }
529 if (expression.name !== `eq`) {
530 throw new Error(`Unsupported identity fixture operator`)
531 }
532 const [left, right] = expression.args
533 const ref = left?.type === `ref` ? left : right
534 const constant = left?.type === `val` ? left : right
535 if (
536 ref?.type !== `ref` ||
537 ref.path.length !== 1 ||
538 constant?.type !== `val`
539 ) {
540 throw new Error(
541 `Identity fixture equality requires one field and one constant`,
542 )
543 }
544 const field = ref.path[0]
545 if (
546 ((field === `id` || field === `group`) &&
547 typeof constant.value === `string`) ||
548 (field === `value` && constant.value instanceof Date)
549 )
550 return
551 throw new Error(`Unsupported identity fixture field or value`)
552 }
553 if (!options.where) throw new Error(`Identity fixture requires a predicate`)
554 validate(options.where)
555}
556
557function selectIdentityRows(
558 options: LoadSubsetOptions,
559 rows: ReadonlyArray<IdentityRow>,
560): Array<IdentityRow> {
561 // This fixture accepts only eq/and/or over its three declared fields. It is
562 // not a SQL server and does not use the production evaluator or demand key.
563 validateIdentityRequest(options)
564 const operand = (
565 expression: IR.BasicExpression,
566 row: IdentityRow,
567 ): unknown => {
568 if (expression.type === `val`) return expression.value
569 if (expression.type === `ref` && expression.path.length === 1) {
570 const field = expression.path[0]
571 if (field === `id` || field === `group` || field === `value`) {
572 return row[field]
573 }
574 }
575 throw new Error(`Unsupported identity fixture operand`)
576 }
577 const matches = (
578 expression: IR.BasicExpression,
579 row: IdentityRow,
580 ): boolean => {
581 if (expression.type !== `func` || expression.args.length !== 2) {
582 throw new Error(`Unsupported identity fixture predicate`)
583 }
584 const [left, right] = expression.args as [
585 IR.BasicExpression,
586 IR.BasicExpression,
587 ]
588 if (expression.name === `and`)
589 return matches(left, row) && matches(right, row)
590 if (expression.name === `or`)
591 return matches(left, row) || matches(right, row)
592 if (expression.name !== `eq`) {
593 throw new Error(`Unsupported identity fixture operator`)
594 }
595 const a = operand(left, row)
596 const b = operand(right, row)
597 // The existing comparison contract treats invalid Dates as equal. Native
598 // Object.is on timestamps gives this fixture that declared finite relation.
599 return a instanceof Date && b instanceof Date
600 ? Object.is(a.getTime(), b.getTime())
601 : a === b
602 }
603 return rows
604 .filter((row) => matches(options.where!, row))
605 .map((row) => structuredClone(row))
606}
607
608async function observeDemandIdentity(
609 form: IdentityForm,
610 fault?: `constant key` | `wrong value`,
611): Promise<Array<IdentityCheckpoint>> {
612 const fixture = identityDemandFixture(form)
613 const providerRows = structuredClone(fixture.rows)
614 const queryClient = createQueryClient()
615 const id = `distinct-demand-${collectionSequence++}`
616 const requests: Array<LoadSubsetOptions> = []
617 const queryFn = vi.fn((context: QueryFunctionContext) => {
618 const options = context.meta?.loadSubsetOptions ?? {}
619 // Direct calls in this fixture supply only immutable request data, not a
620 // signal/subscription. Capture the complete received request before checks.
621 requests.push(structuredClone(options))
622 const result = selectIdentityRows(options, providerRows)
623 return Promise.resolve(
624 fault === `wrong value`
625 ? result.map((row) => ({ ...row, group: `wrong` }))
626 : result,
627 )
628 })
629 const collection = createCollection(
630 queryCollectionOptions<IdentityRow>({
631 id,
632 queryClient,
633 queryKey: fault === `constant key` ? () => [id] : [id],
634 queryFn,
635 getKey: (row) => row.id,
636 syncMode: `on-demand`,
637 startSync: true,
638 retry: false,
639 }),
640 )
641 const observations: Array<IdentityCheckpoint> = []
642 const capture = (stage: string): void => {
643 observations.push({
644 stage,
645 calls: queryFn.mock.calls.length,
646 requests: structuredClone(requests),
647 // Compare every provider field, excluding Collection's virtual metadata.
648 rows: collection.toArray
649 .map(({ id: rowId, group, value }) => ({
650 id: rowId,
651 group,
652 value: new Date(value.getTime()),
653 }))
654 .sort((a, b) => a.id.localeCompare(b.id)),
655 })
656 }
657 try {
658 await collection._sync.loadSubset(fixture.first)
659 capture(`first`)
660 await collection._sync.loadSubset(fixture.equivalent)
661 capture(`equivalent`)
662 await collection._sync.loadSubset(fixture.distinct)
663 capture(`distinct`)
664 collection._sync.unloadSubset(fixture.first)
665 capture(`one equivalent owner leaves`)
666 collection._sync.unloadSubset(fixture.equivalent)
667 capture(`final equivalent owner leaves`)
668 collection._sync.unloadSubset(fixture.distinct)
669 capture(`final distinct owner leaves`)
670 return observations
671 } finally {
672 try {
673 await collection.cleanup()
674 } finally {
675 queryClient.clear()
676 }
677 }
678}
679
680function expectDemandIdentity(
681 observations: Array<IdentityCheckpoint>,
682 form: IdentityForm,
683): void {
684 // Literal result sets are the authority; do not run the provider predicate
685 // against expected data or derive expected membership from collection keys.
686 const fixture = identityDemandFixture(form)
687 const [first, second] = fixture.rows
688 const initialRequests = [structuredClone(fixture.first)]
689 const bothRequests = [...initialRequests, structuredClone(fixture.distinct)]
690 expect(observations).toEqual([
691 { stage: `first`, calls: 1, requests: initialRequests, rows: [first] },
692 { stage: `equivalent`, calls: 1, requests: initialRequests, rows: [first] },
693 {
694 stage: `distinct`,
695 calls: 2,
696 requests: bothRequests,
697 rows: [first, second],
698 },
699 {
700 stage: `one equivalent owner leaves`,
701 calls: 2,
702 requests: bothRequests,
703 rows: [first, second],
704 },
705 {
706 stage: `final equivalent owner leaves`,
707 calls: 2,
708 requests: bothRequests,
709 rows: [second],
710 },
711 {
712 stage: `final distinct owner leaves`,
713 calls: 2,
714 requests: bothRequests,
715 rows: [],
716 },
717 ])
718}
719
720async function expectFinalOwnerCleanupAbortsQuery(): Promise<void> {
721 const queryClient = createQueryClient()
722 const id = `load-subset-cancel-final-owner-${collectionSequence++}`
723 let capturedSignal: AbortSignal | undefined
724 let resolveStarted!: () => void
725 const started = new Promise<void>((resolve) => {
726 resolveStarted = resolve
727 })
728 const queryFn = vi.fn((context: QueryFunctionContext) => {
729 capturedSignal = context.signal
730 resolveStarted()
731 return new Promise<Array<Row>>((_resolve, reject) => {
732 context.signal.addEventListener(`abort`, () => {
733 const error = new Error(`query aborted`)
734 error.name = `AbortError`
735 reject(error)
736 })
737 })
738 })
739 const source = createCollection(
740 queryCollectionOptions<Row>({
741 id,
742 queryClient,
743 queryKey: [id],
744 queryFn,
745 getKey: (row) => row.id,
746 startSync: true,
747 syncMode: `on-demand`,
748 retry: false,
749 }),
750 )
751 const live = createLiveQueryCollection((query) =>
752 query.from({ row: source }).select(({ row }) => ({ id: row.id })),
753 )
754 const preloadOutcome = live.preload().catch((error: unknown) => error)
755
756 try {
757 await started
758 expect(queryFn).toHaveBeenCalledOnce()
759 expect(capturedSignal?.aborted).toBe(false)
760
761 await live.cleanup()
762 expect(capturedSignal?.aborted).toBe(true)
763 } finally {
764 await live.cleanup()
765 await source.cleanup()
766 queryClient.clear()
767 await preloadOutcome
768 }
769}
770
771async function expectRemountAfterAbortStartsFreshQuery(): Promise<void> {
772 const queryClient = createQueryClient()
773 const id = `load-subset-remount-after-abort-${collectionSequence++}`
774 let resolveFirstStarted!: () => void
775 const firstStarted = new Promise<void>((resolve) => {
776 resolveFirstStarted = resolve
777 })
778 const queryFn = vi
779 .fn<(context: QueryFunctionContext) => Promise<Array<Row>>>()
780 .mockImplementationOnce((context) => {
781 resolveFirstStarted()
782 return new Promise<Array<Row>>((_resolve, reject) => {
783 context.signal.addEventListener(`abort`, () => {
784 const error = new Error(`first query aborted`)
785 error.name = `AbortError`
786 reject(error)
787 })
788 })
789 })
790 .mockResolvedValueOnce([{ id: `fresh` }])
791 const source = createCollection(
792 queryCollectionOptions<Row>({
793 id,
794 queryClient,
795 queryKey: [id],
796 queryFn,
797 getKey: (row) => row.id,
798 startSync: true,
799 syncMode: `on-demand`,
800 retry: false,
801 }),
802 )
803 const buildLive = () =>
804 createLiveQueryCollection((query) =>
805 query.from({ row: source }).select(({ row }) => ({ id: row.id })),
806 )
807 const first = buildLive()
808 const firstOutcome = first.preload().catch((error: unknown) => error)
809 let second: ReturnType<typeof buildLive> | undefined
810
811 try {
812 await firstStarted
813 await first.cleanup()
814 await firstOutcome
815
816 second = buildLive()
817 const rows = await second.toArrayWhenReady()
818 expect(queryFn).toHaveBeenCalledTimes(2)
819 expect(rows.map(({ id: rowId }) => rowId)).toEqual([`fresh`])
820 } finally {
821 await first.cleanup()
822 await second?.cleanup()
823 await source.cleanup()
824 queryClient.clear()
825 }
826}
827
828type RetiredOutcome =
829 | { status: `fulfilled` }
830 | { status: `rejected`; error: unknown }
831type ReplacementSnapshot = {
832 source: Array<Row>
833 live: Array<Row>
834 sourceStatus: string
835 liveStatus: string
836 sourceError: unknown
837}
838type RetiredQueryObservation = {
839 retired: RetiredOutcome
840 retiredStatus: string
841 aborted: boolean
842 calls: number
843 snapshots: Array<ReplacementSnapshot>
844}
845
846async function observeLateRetiredQuery(
847 settlement: `resolve` | `reject`,
848): Promise<RetiredQueryObservation> {
849 const queryClient = createQueryClient()
850 const id = `retired-query-completion-${collectionSequence++}`
851 const old = createDeferred<Array<Row>>()
852 const started = createDeferred<void>()
853 let signal: AbortSignal | undefined
854 const providerOutcome = old.promise.then(
855 () => `resolved`,
856 () => `rejected`,
857 )
858 const queryFn = vi
859 .fn<(context: QueryFunctionContext) => Promise<Array<Row>>>()
860 .mockImplementationOnce((context) => {
861 // Consuming the signal lets Query cancel its retryer, even though this
862 // simulated endpoint finishes its underlying promise later.
863 signal = context.signal
864 started.resolve()
865 return old.promise
866 })
867 .mockResolvedValueOnce([{ id: `fresh`, group: `current` }])
868 const source = createCollection(
869 queryCollectionOptions<Row>({
870 id,
871 queryClient,
872 queryKey: [id],
873 queryFn,
874 getKey: (row) => row.id,
875 syncMode: `on-demand`,
876 startSync: true,
877 retry: false,
878 }),
879 )
880 const buildLive = () =>
881 createLiveQueryCollection((query) =>
882 query
883 .from({ row: source })
884 .select(({ row }) => ({ id: row.id, group: row.group })),
885 )
886 const first = buildLive()
887 const firstOutcome = first.preload().then<RetiredOutcome, RetiredOutcome>(
888 () => ({ status: `fulfilled` }),
889 (error: unknown) => ({ status: `rejected`, error }),
890 )
891 let second: ReturnType<typeof buildLive> | undefined
892 const unsubscribe: Array<() => void> = []
893 try {
894 await started.promise
895 expect(signal?.aborted).toBe(false)
896 await first.cleanup()
897 const retired = await firstOutcome
898 // This cut precedes both the replacement and old provider settlement.
899 expect(retired).toMatchObject({
900 status: `rejected`,
901 error: { name: `AbortError` },
902 })
903 const retiredStatus = first.status
904 second = buildLive()
905 await second.preload()
906 const current = second
907 const snapshots: Array<ReplacementSnapshot> = []
908 const capture = (): void => {
909 const values = (rows: Array<Row>) =>
910 rows
911 .map(({ id: rowId, group }) => ({ id: rowId, group }))
912 .sort((a, b) => a.id.localeCompare(b.id))
913 snapshots.push({
914 source: values(source.toArray),
915 live: values(current.toArray),
916 sourceStatus: source.status,
917 liveStatus: current.status,
918 sourceError: source.utils.lastError,
919 })
920 }
921 const sourceSubscription = source.subscribeChanges(capture)
922 const liveSubscription = current.subscribeChanges(capture)
923 unsubscribe.push(
924 () => sourceSubscription.unsubscribe(),
925 () => liveSubscription.unsubscribe(),
926 )
927 capture()
928 if (settlement === `resolve`)
929 old.resolve([{ id: `obsolete`, group: `old` }])
930 else old.reject(new Error(`retired endpoint failed`))
931 expect(await providerOutcome).toBe(
932 settlement === `resolve` ? `resolved` : `rejected`,
933 )
934 // One host turn drains this controlled Query/native-promise continuation;
935 // it is not a network or scheduler fairness bound.
936 await new Promise<void>((resolve) => setTimeout(resolve, 0))
937 capture()
938 expect(await firstOutcome).toBe(retired)
939 return {
940 retired,
941 retiredStatus,
942 aborted: signal?.aborted === true,
943 calls: queryFn.mock.calls.length,
944 snapshots,
945 }
946 } finally {
947 old.resolve([])
948 unsubscribe.forEach((stop) => stop())
949 try {
950 await first.cleanup()
951 } finally {
952 try {
953 await second?.cleanup()
954 } finally {
955 try {
956 await source.cleanup()
957 } finally {
958 queryClient.clear()
959 }
960 }
961 }
962 }
963}
964
965function expectLateRetiredQuery(observation: RetiredQueryObservation): void {
966 expect(observation.retired).toMatchObject({
967 status: `rejected`,
968 error: { name: `AbortError` },
969 })
970 expect(observation.retiredStatus).toBe(`cleaned-up`)
971 expect(observation.aborted).toBe(true)
972 expect(observation.calls).toBe(2)
973 expect(observation.snapshots.length).toBeGreaterThanOrEqual(2)
974 for (const snapshot of observation.snapshots) {
975 expect(snapshot).toEqual({
976 source: [{ id: `fresh`, group: `current` }],
977 live: [{ id: `fresh`, group: `current` }],
978 sourceStatus: `ready`,
979 liveStatus: `ready`,
980 sourceError: undefined,
981 })
982 }
983}
984
985describe(`loadSubset lifecycle oracle`, () => {
986 it(`reports an initial query failure and recovers after a successful refetch`, async () => {
987 await expectInitialQueryFailureStatus()
988 })
989
990 it(`reports an initial failure to a dependent created after the source failed`, async () => {
991 await expectLateDependentObservesInitialFailure()
992 })
993
994 it(`recovers a dependent only after every failed source recovers`, async () => {
995 await expectEveryFailedSourceToRecover()
996 })
997
998 it(`keeps the last ready snapshot after a refetch failure`, async () => {
999 await expectRefetchFailureKeepsReadySnapshot()
1000 })
1001
1002 it(`does not let deferred startup readiness override a replayed error in the internal sync seam`, async () => {
1003 await expectDeferredStartupReadyDoesNotOverrideError()
1004 })
1005
1006 it.each([`commutative-and`, `commutative-or`] as const)(
1007 `%s predicate forms share one query-db transport load`,
1008 async (form) => {
1009 await expectEquivalentPredicatesShareOneLoad(form)
1010 },
1011 )
1012
1013 it(`reversed equality operands share one query-db transport load`, async () => {
1014 await expectEquivalentPredicatesShareOneLoad(`reversed-equality`)
1015 })
1016
1017 it.each([
1018 [
1019 `valid Date`,
1020 new Date(`2024-01-15T00:00:00Z`),
1021 new Date(`2024-01-15T00:00:00Z`),
1022 ],
1023 [`invalid Date`, new Date(Number.NaN), new Date(Number.NaN)],
1024 ])(
1025 `shares one query-db transport load for equivalent %s values`,
1026 async (_label, firstValue, secondValue) => {
1027 await expectEquivalentComparisonValuesShareOneLoad(
1028 firstValue,
1029 secondValue,
1030 )
1031 },
1032 )
1033
1034 const identityForms: Array<IdentityForm> = [
1035 `commutative-and`,
1036 `commutative-or`,
1037 `reversed-equality`,
1038 `valid Date`,
1039 `invalid Date`,
1040 ]
1041 it.each(identityForms)(
1042 `shares equivalent %s demands without collapsing distinct results or owners`,
1043 async (form) => {
1044 expectDemandIdentity(await observeDemandIdentity(form), form)
1045 },
1046 )
1047
1048 it.each(identityForms)(
1049 `rejects a constant demand key despite valid %s sharing`,
1050 async (form) => {
1051 const observations = await observeDemandIdentity(form, `constant key`)
1052 expect(observations.slice(0, 2).map(({ calls }) => calls)).toEqual([1, 1])
1053 expect(() => expectDemandIdentity(observations, form)).toThrow()
1054 },
1055 )
1056
1057 it(`rejects correct demand counts with wrong returned values`, async () => {
1058 const observations = await observeDemandIdentity(
1059 `commutative-and`,
1060 `wrong value`,
1061 )
1062 expect(observations.map(({ calls }) => calls)).toEqual([1, 1, 2, 2, 2, 2])
1063 expect(() =>
1064 expectDemandIdentity(observations, `commutative-and`),
1065 ).toThrow()
1066 })
1067
1068 it.each([`or`, `and`, `empty`] as const)(
1069 `validates unvisited predicate branches for %s provider evaluation`,
1070 (form) => {
1071 const fixture = identityDemandFixture(`reversed-equality`)
1072 const where = new IR.Func<boolean>(form === `and` ? `and` : `or`, [
1073 new IR.Func(`eq`, [
1074 new IR.PropRef([`id`]),
1075 new IR.Value(form === `and` ? `absent` : `a`),
1076 ]),
1077 new IR.Func(`unsupported`, [new IR.Value(1), new IR.Value(2)]),
1078 ])
1079 expect(() =>
1080 selectIdentityRows(
1081 { where },
1082 form === `empty` ? [] : [fixture.rows[0]!],
1083 ),
1084 ).toThrow(`Unsupported identity fixture operator`)
1085 expect(selectIdentityRows(fixture.first, fixture.rows)).toEqual([
1086 fixture.rows[0],
1087 ])
1088 },
1089 )
1090
1091 it.each([
1092 { limit: 0 },
1093 { offset: 0 },
1094 { orderBy: [] },
1095 {
1096 cursor: {
1097 whereFrom: new IR.Value(true),
1098 whereCurrent: new IR.Value(true),
1099 },
1100 },
1101 ] satisfies Array<LoadSubsetOptions>)(
1102 `rejects undeclared provider ordering/window requests: %j`,
1103 (extra) => {
1104 const fixture = identityDemandFixture(`reversed-equality`)
1105 expect(() =>
1106 selectIdentityRows({ ...fixture.first, ...extra }, fixture.rows),
1107 ).toThrow(`Identity fixture does not support ordering or windows`)
1108 },
1109 )
1110
1111 it(`aborts an in-flight query when its final live-query owner cleans up`, async () => {
1112 await expectFinalOwnerCleanupAbortsQuery()
1113 })
1114
1115 it(`starts a fresh query after an aborted owner immediately remounts`, async () => {
1116 await expectRemountAfterAbortStartsFreshQuery()
1117 })
1118
1119 it.each([`resolve`, `reject`] as const)(
1120 `settles the retired caller before a late endpoint can %s against its replacement`,
1121 async (settlement) => {
1122 expectLateRetiredQuery(await observeLateRetiredQuery(settlement))
1123 },
1124 )
1125
1126 it(`rejects lost caller cancellation and a stale replacement snapshot`, async () => {
1127 const observation = await observeLateRetiredQuery(`resolve`)
1128 expectLateRetiredQuery(observation)
1129 expect(() =>
1130 expectLateRetiredQuery({
1131 ...observation,
1132 retired: { status: `fulfilled` },
1133 }),
1134 ).toThrow()
1135 const snapshots = observation.snapshots.map((snapshot) => ({
1136 ...snapshot,
1137 source: [{ id: `obsolete`, group: `old` }],
1138 }))
1139 expect(() =>
1140 expectLateRetiredQuery({ ...observation, snapshots }),
1141 ).toThrow()
1142 })
1143})