Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import {
3 BTreeIndex,
4 createCollection,
5 createLiveQueryCollection,
6 eq,
7} from '@tanstack/db'
8import { expect, it, vi } from 'vitest'
9import { createDeferred } from '../../db/src/deferred.js'
10import { queryCollectionOptions } from '../src/query.js'
11import { applyPredicates } from '../e2e/query-filter.js'
12import { declareOracle } from '../../db/tests/oracle-declaration.js'
13import { isNarrowRankTieProbe } from './optimistic-ordered-refetch-probe.js'
14import type { LoadSubsetOptions } from '@tanstack/db'
15import type { Row } from './optimistic-ordered-refetch-probe.js'
16
17type ProviderPhase =
18 `initial` | `optimistic` | `held-invalidation` | `handler-refetch`
19
20/**
21 * # Does a Query DB refetch preserve an optimistic ordered departure?
22 *
23 * The public window is the first two inbox rows by descending `at`. An
24 * optimistic move from inbox to archive removes its row synchronously, even
25 * when only the old two-row prefix is installed. A missing replacement may
26 * arrive through a bounded provider request, but its Collection write cannot
27 * become public before it applies behind the pending mutation. After the
28 * mutation's authoritative write and refill apply, the window is `[2, 1]`.
29 * The mutation handler calls `utils.refetch()` after changing the provider,
30 * matching the receiving path reported in #2169. A second history adds a new
31 * provider head and invalidates the Query while persistence is held. Query DB
32 * reports shifted loaded subsets, but the resulting repair must not retract
33 * the immediate `[2]` publication. It settles as `[5, 2]` after persistence.
34 *
35 * The reference is the plain remote row ledger and filter/sort/slice below.
36 * The real QueryClient and queryCollectionOptions adapter receive each request
37 * through their public API. The backend applies LoadSubsetOptions, while the
38 * assertions compare public live-query rows and callback snapshots at the
39 * immediate, held-refetch, and settled checkpoints. The backend evaluator is
40 * only driver wiring: it never computes the expected window.
41 */
42async function checkOptimisticOrderedRefetch(
43 reportDuringHold: boolean,
44): Promise<void> {
45 const queryClient = new QueryClient({
46 defaultOptions: {
47 queries: { retry: false, staleTime: Infinity, gcTime: Infinity },
48 },
49 })
50 const remote: Array<Row> = [-1, 0, 1, 2, 3, 4].map((id) => ({
51 id,
52 folder: id === 4 ? `archive` : `inbox`,
53 at: id,
54 }))
55 const persistence = createDeferred<void>()
56 let providerPhase: ProviderPhase = `initial`
57 const requests: Array<{
58 options: LoadSubsetOptions
59 ids: Array<number>
60 phase: ProviderPhase
61 }> = []
62 const source = createCollection(
63 queryCollectionOptions<Row>({
64 id: `optimistic-query-refetch`,
65 queryKey: [`optimistic-query-refetch`],
66 queryClient,
67 getKey: (row) => row.id,
68 syncMode: `on-demand`,
69 startSync: true,
70 queryFn: ({ meta }) => {
71 const options = meta?.loadSubsetOptions ?? {}
72 const rows = applyPredicates(remote, options).map((row) => ({
73 ...row,
74 }))
75 requests.push({
76 options,
77 ids: rows.map(({ id }) => id),
78 phase: providerPhase,
79 })
80 return rows
81 },
82 onUpdate: async ({ collection }) => {
83 await persistence.promise
84 const moved = remote.find(({ id }) => id === 3)!
85 moved.folder = `archive`
86 providerPhase = `handler-refetch`
87 await collection.utils.refetch()
88 return { refetch: false }
89 },
90 }),
91 )
92 source.createIndex((row) => row.at, { indexType: BTreeIndex })
93 let reports = 0
94 let requestCountAtReport = 0
95 source.on(`loadedSubsets:invalidated`, () => {
96 reports++
97 requestCountAtReport = requests.length
98 })
99 const live = createLiveQueryCollection({
100 query: (q) =>
101 q
102 .from({ row: source })
103 .where(({ row }) => eq(row.folder, `inbox`))
104 .orderBy(({ row }) => row.at, `desc`)
105 .limit(2),
106 })
107 const publicIds = () => live.toArray.map(({ id }) => id)
108 const publications: Array<Array<number>> = []
109 let unsubscribe: (() => void) | undefined
110 try {
111 await live.preload()
112 expect(publicIds()).toEqual(expectedPublicWindow(remote))
113 expect(source.toArray.map(({ id }) => id).sort()).toEqual([2, 3])
114 const subscription = live.subscribeChanges(
115 () => publications.push(publicIds()),
116 { includeInitialState: true },
117 )
118 unsubscribe = () => subscription.unsubscribe()
119 publications.length = 0
120
121 const initialRequests = requests.length
122 providerPhase = `optimistic`
123 const transaction = source.update(3, (draft) => {
124 draft.folder = `archive`
125 })
126 expect(publicIds()).toEqual([2])
127 expect(publications).toEqual([[2]])
128
129 await vi.waitFor(() => {
130 expect(requests.length).toBeGreaterThan(initialRequests)
131 expect(
132 requests
133 .slice(initialRequests)
134 .some(
135 ({ options, ids }) =>
136 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
137 options.limit !== undefined &&
138 options.limit <= 4 &&
139 ids.includes(1),
140 ),
141 ).toBe(true)
142 })
143 for (const { options, ids } of requests.filter(
144 ({ phase }) => phase === `optimistic`,
145 )) {
146 const orderedPage =
147 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
148 options.limit !== undefined &&
149 options.limit <= 4
150 const rankTieProbe = isNarrowRankTieProbe(options, remote)
151 expect(orderedPage || rankTieProbe).toBe(true)
152 expect(ids).not.toContain(4)
153 }
154 expect(publicIds()).toEqual([2])
155 expect(
156 publications.every(
157 (snapshot) => snapshot.length === 1 && snapshot[0] === 2,
158 ),
159 ).toBe(true)
160
161 if (reportDuringHold) {
162 remote.push({ id: 5, folder: `inbox`, at: 5 })
163 providerPhase = `held-invalidation`
164 await queryClient.invalidateQueries({
165 queryKey: [`optimistic-query-refetch`],
166 })
167 await vi.waitFor(() => expect(reports).toBe(1))
168 await vi.waitFor(() =>
169 expect(
170 requests
171 .slice(requestCountAtReport)
172 .some(
173 ({ options, ids, phase }) =>
174 phase === `held-invalidation` &&
175 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
176 options.limit !== undefined &&
177 options.limit <= 4 &&
178 ids.includes(5),
179 ),
180 ).toBe(true),
181 )
182 expect(publicIds()).toEqual([2])
183 expect(publications).toEqual([[2]])
184 }
185
186 persistence.resolve()
187 await transaction.isPersisted.promise
188 if (!reportDuringHold) {
189 expect(
190 requests.some(
191 ({ phase, ids }) =>
192 phase === `handler-refetch` && ids.includes(1) && !ids.includes(3),
193 ),
194 ).toBe(true)
195 }
196 await vi.waitFor(() =>
197 expect(publicIds()).toEqual(expectedPublicWindow(remote)),
198 )
199 expect(publicIds()).toEqual(reportDuringHold ? [5, 2] : [2, 1])
200 expect(publications.at(-1)).toEqual(publicIds())
201 } finally {
202 persistence.resolve()
203 unsubscribe?.()
204 await live.cleanup()
205 await source.cleanup()
206 queryClient.clear()
207 }
208}
209
210/**
211 * The public window of the live query `inbox` order `at desc` limit 2, computed
212 * from the plain remote row ledger. This is the model that the check compares
213 * the live rows against at each checkpoint.
214 */
215function expectedPublicWindow(remote: ReadonlyArray<Row>): Array<number> {
216 return remote
217 .filter(({ folder }) => folder === `inbox`)
218 .sort((left, right) => right.at - left.at)
219 .slice(0, 2)
220 .map(({ id }) => id)
221}
222
223declareOracle({
224 check: [checkOptimisticOrderedRefetch],
225 model: [expectedPublicWindow],
226})
227
228it(`publishes a short optimistic window during a mutation-handler refetch`, () =>
229 checkOptimisticOrderedRefetch(false))
230
231it(`keeps the short optimistic window through a held refetch report`, () =>
232 checkOptimisticOrderedRefetch(true))