Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
3import { describe, expect, it, vi } from 'vitest'
4import { createDeferred } from '../../db/src/deferred.js'
5import { queryCollectionOptions } from '../src/query.js'
6import type { Collection } from '@tanstack/db'
7
8/**
9 * # Does Query settlement carry initial-query readiness?
10 *
11 * ARCHITECTURE.md law 10 makes a settled `loadSubset` the readiness evidence
12 * for an on-demand source, and law 7 says a successful load settles only after
13 * its rows are visible. These witnesses drive a real QueryClient under a real
14 * live query and record the rows visible at the first-ready transition.
15 */
16
17type Row = { id: string; group: string }
18
19let sequence = 0
20
21function createQueryClient(): QueryClient {
22 return new QueryClient({
23 defaultOptions: {
24 queries: {
25 gcTime: Number.POSITIVE_INFINITY,
26 retry: false,
27 staleTime: Number.POSITIVE_INFINITY,
28 },
29 },
30 })
31}
32
33function rowsAtFirstReady(query: Collection<any, any, any>) {
34 const seen: { rows?: Array<unknown> } = {}
35 query.onFirstReady(() => {
36 seen.rows = query.toArray.map((row: { id: string }) => row.id).sort()
37 })
38 return seen
39}
40
41function groupQuery(source: Collection<Row, string | number, any>) {
42 return createLiveQueryCollection((q) =>
43 q.from({ row: source }).where(({ row }) => eq(row.group, `a`)),
44 )
45}
46
47describe(`Query initial readiness follows applied subset settlement`, () => {
48 it(`an on-demand query is first ready with its subset rows visible`, async () => {
49 const id = `exposure-on-demand-${sequence++}`
50 const response = createDeferred<Array<Row>>()
51 const source = createCollection(
52 queryCollectionOptions<Row>({
53 id,
54 queryClient: createQueryClient(),
55 queryKey: [id],
56 queryFn: () => response.promise,
57 getKey: (row) => row.id,
58 syncMode: `on-demand`,
59 }),
60 )
61 const query = groupQuery(source)
62 const seen = rowsAtFirstReady(query)
63 const preload = query.preload()
64 await Promise.resolve()
65 expect(query.isReady()).toBe(false)
66
67 response.resolve([
68 { id: `1`, group: `a` },
69 { id: `2`, group: `a` },
70 ])
71 await preload
72 expect(seen.rows).toEqual([`1`, `2`])
73 })
74
75 it(`an empty on-demand result is authoritative absence`, async () => {
76 const id = `exposure-empty-${sequence++}`
77 const source = createCollection(
78 queryCollectionOptions<Row>({
79 id,
80 queryClient: createQueryClient(),
81 queryKey: [id],
82 queryFn: () => Promise.resolve([]),
83 getKey: (row) => row.id,
84 syncMode: `on-demand`,
85 }),
86 )
87 const query = groupQuery(source)
88 await query.preload()
89 expect(query.isReady()).toBe(true)
90 expect(query.toArray).toEqual([])
91 })
92
93 it(`a failed on-demand load errors the query and never readies it`, async () => {
94 const id = `exposure-failure-${sequence++}`
95 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
96 const source = createCollection(
97 queryCollectionOptions<Row>({
98 id,
99 queryClient: createQueryClient(),
100 queryKey: [id],
101 queryFn: () => Promise.reject(new Error(`query failed`)),
102 getKey: (row) => row.id,
103 syncMode: `on-demand`,
104 retry: false,
105 }),
106 )
107 const query = groupQuery(source)
108 const seen = rowsAtFirstReady(query)
109 await query.preload().catch(() => {})
110 await vi.waitFor(() => expect(query.status).toBe(`error`))
111 expect(seen.rows).toBeUndefined()
112 loggedError.mockRestore()
113 })
114
115 it(`an abandoned on-demand load installs no rows after its abort`, async () => {
116 const id = `exposure-abort-${sequence++}`
117 const response = createDeferred<Array<Row>>()
118 let signal: AbortSignal | undefined
119 const source = createCollection(
120 queryCollectionOptions<Row>({
121 id,
122 queryClient: createQueryClient(),
123 queryKey: [id],
124 queryFn: (context) => {
125 signal = context.signal
126 return response.promise
127 },
128 getKey: (row) => row.id,
129 syncMode: `on-demand`,
130 }),
131 )
132 const query = groupQuery(source)
133 void query.preload().catch(() => {})
134 await vi.waitFor(() => expect(signal).toBeDefined())
135 await query.cleanup()
136 response.resolve([{ id: `late`, group: `a` }])
137 await new Promise((resolve) => setTimeout(resolve, 0))
138 expect(source.has(`late`)).toBe(false)
139 })
140
141 it(`a source with no syncMode is eager and gates readiness`, async () => {
142 const id = `exposure-eager-default-${sequence++}`
143 const response = createDeferred<Array<Row>>()
144 const source = createCollection(
145 queryCollectionOptions<Row>({
146 id,
147 queryClient: createQueryClient(),
148 queryKey: [id],
149 queryFn: () => response.promise,
150 getKey: (row) => row.id,
151 }),
152 )
153 expect(source.config.syncMode).not.toBe(`on-demand`)
154 const query = groupQuery(source)
155 const seen = rowsAtFirstReady(query)
156 const preload = query.preload()
157 await new Promise((resolve) => setTimeout(resolve, 0))
158 expect(query.isReady()).toBe(false)
159 response.resolve([
160 { id: `1`, group: `a` },
161 { id: `2`, group: `b` },
162 ])
163 await preload
164 expect(seen.rows).toEqual([`1`])
165 })
166})