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 { afterAll, describe, 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 { createOracleReach } from '../../db/tests/oracle-reach'
14import { withOracleCleanup } from '../../db/tests/utils'
15import { atMutationCheckpoint } from '../../db/tests/mutation-confirmation-support'
16import { isNarrowRankTieProbe } from './optimistic-ordered-refetch-probe.js'
17import type { QueryCollectionConfig } from '../src/query'
18import type { LoadSubsetOptions } from '@tanstack/db'
19import type { Row } from './optimistic-ordered-refetch-probe.js'
20
21type ProviderPhase =
22 `initial` | `optimistic` | `held-invalidation` | `handler-refetch`
23
24/**
25 * # Does a Query DB refetch preserve an optimistic ordered departure?
26 *
27 * The public window is the first two inbox rows by descending `at`. An
28 * optimistic move from inbox to archive removes its row synchronously, even
29 * when only the old two-row prefix is installed. A missing replacement may
30 * arrive through a bounded provider request, but its Collection write cannot
31 * become public before it applies behind the pending mutation. After the
32 * authoritative write and refill, the window matches the backend.
33 * A prewrite rejection restores the earlier row; a post-confirmation rejection
34 * preserves the server edit. Insertions keep their optimistic head while held.
35 * The mutation handler calls `utils.refetch()` after changing the provider,
36 * matching the receiving path reported in #2169. A second history adds a new
37 * provider head and invalidates the Query while persistence is held. Query DB
38 * reports shifted loaded subsets, but the resulting repair must not retract
39 * the immediate optimistic publication. Its final window follows the backend
40 * edit and the handler's source confirmation.
41 * CRUD, fulfilled void/legacy returns and rejection before/after confirmation
42 * use the same window model. Source publication may need ordered repair after
43 * handler settlement; the final cut waits for that fixed point.
44 *
45 * The reference is the plain remote row ledger and filter/sort/slice below.
46 * The real QueryClient and queryCollectionOptions adapter receive each request
47 * through their public API. The backend applies LoadSubsetOptions, while the
48 * assertions compare public live-query rows and callback snapshots at the
49 * immediate, held-refetch, and settled checkpoints. The backend evaluator is
50 * only driver wiring: it never computes the expected window.
51 */
52type OrderedMutationHistory = {
53 operation: `insert` | `update` | `delete`
54 ending:
55 | `fulfilled-void`
56 | `fulfilled-legacy`
57 | `reject-before-write`
58 | `reject-after-write`
59 reportDuringHold: boolean
60}
61const orderedMutationHistories: Array<OrderedMutationHistory> = (
62 [`insert`, `update`, `delete`] as const
63).flatMap((operation) =>
64 (
65 [
66 `fulfilled-void`,
67 `fulfilled-legacy`,
68 `reject-before-write`,
69 `reject-after-write`,
70 ] as const
71 ).flatMap((ending) =>
72 [false, true].map((reportDuringHold) => ({
73 operation,
74 ending,
75 reportDuringHold,
76 })),
77 ),
78)
79const orderedReach = createOracleReach(
80 `query.ordered-mutation-outcome`,
81 orderedMutationHistories.map(
82 (h) => `${h.operation}/${h.ending}/${h.reportDuringHold}`,
83 ),
84)
85
86async function checkOptimisticOrderedRefetch(
87 history: OrderedMutationHistory,
88): Promise<void> {
89 const { operation, ending, reportDuringHold } = history
90 orderedReach.beginHistory()
91 const reach = createOracleReach(`ordered-mutation-cuts`, [
92 `optimistic`,
93 `settled-fixed-point`,
94 ...(operation === `insert` ? [] : [`bounded-refill`]),
95 ...(reportDuringHold ? [`held-report`] : []),
96 ...(ending === `reject-before-write` ? [] : [`handler-confirmation`]),
97 ])
98 reach.beginHistory()
99 const failure = new Error(`ordered handler failure`)
100 let handlerConfirmed = false
101 const queryClient = new QueryClient({
102 defaultOptions: {
103 queries: { retry: false, staleTime: Infinity, gcTime: Infinity },
104 },
105 })
106 const remote: Array<Row> = [-1, 0, 1, 2, 3, 4].map((id) => ({
107 id,
108 folder: id === 4 ? `archive` : `inbox`,
109 at: id,
110 }))
111 // Recompute the visible installed prefix under local intent. A departure
112 // may be short while its replacement's accepted sync rows remain held.
113 const installed = remote
114 .filter((row) => expectedPublicWindow(remote).includes(row.id))
115 .map((row) => ({ ...row }))
116 const optimisticRows =
117 operation === `insert`
118 ? [...installed, { id: 5, folder: `inbox` as const, at: 7 }]
119 : operation === `delete`
120 ? installed.filter(({ id }) => id !== 3)
121 : installed.map((row) =>
122 row.id === 3 ? { ...row, folder: `archive` as const } : row,
123 )
124 const immediateWindow = expectedPublicWindow(optimisticRows)
125 const persistence = createDeferred<void>()
126 let providerPhase: ProviderPhase = `initial`
127 const requests: Array<{
128 options: LoadSubsetOptions
129 ids: Array<number>
130 phase: ProviderPhase
131 }> = []
132 const handler = async ({
133 collection,
134 }: Pick<
135 Parameters<NonNullable<QueryCollectionConfig<Row>[`onUpdate`]>>[0],
136 `collection`
137 >) => {
138 await persistence.promise
139 if (ending === `reject-before-write`) throw failure
140 if (operation === `insert`) remote.push({ id: 5, folder: `inbox`, at: 5 })
141 else if (operation === `delete`)
142 remote.splice(
143 remote.findIndex(({ id }) => id === 3),
144 1,
145 )
146 else remote.find(({ id }) => id === 3)!.folder = `archive`
147 providerPhase = `handler-refetch`
148 await collection.utils.refetch()
149 handlerConfirmed = true
150 if (ending === `reject-after-write`) throw failure
151 return ending === `fulfilled-legacy` ? { refetch: false } : undefined
152 }
153 const runtimeHandler = handler as unknown as (
154 params: Parameters<typeof handler>[0],
155 ) => Promise<void>
156 let unsubscribe: (() => void) | undefined
157 let verdict: Promise<unknown> | undefined
158 let cleanupSource: (() => Promise<void>) | undefined
159 let cleanupLive: (() => Promise<void>) | undefined
160 await withOracleCleanup(async () => {
161 const source = createCollection(
162 queryCollectionOptions<Row>({
163 id: `optimistic-query-refetch`,
164 queryKey: [`optimistic-query-refetch`],
165 queryClient,
166 getKey: (row) => row.id,
167 syncMode: `on-demand`,
168 startSync: true,
169 queryFn: ({ meta }) => {
170 const options = meta?.loadSubsetOptions ?? {}
171 const rows = applyPredicates(remote, options).map((row) => ({
172 ...row,
173 }))
174 requests.push({
175 options,
176 ids: rows.map(({ id }) => id),
177 phase: providerPhase,
178 })
179 return rows
180 },
181 // JavaScript legacy results remain runtime inputs; TypeScript admission
182 // is judged separately by the generated handler type owner.
183 onInsert: runtimeHandler,
184 onUpdate: runtimeHandler,
185 onDelete: runtimeHandler,
186 }),
187 )
188 cleanupSource = () => source.cleanup()
189 source.createIndex((row) => row.at, { indexType: BTreeIndex })
190 let reports = 0
191 let requestCountAtReport = 0
192 source.on(`loadedSubsets:invalidated`, () => {
193 reports++
194 requestCountAtReport = requests.length
195 })
196 const live = createLiveQueryCollection({
197 query: (q) =>
198 q
199 .from({ row: source })
200 .where(({ row }) => eq(row.folder, `inbox`))
201 .orderBy(({ row }) => row.at, `desc`)
202 .limit(2),
203 })
204 cleanupLive = () => live.cleanup()
205 const publicIds = () => live.toArray.map(({ id }) => id)
206 const publications: Array<Array<number>> = []
207 await live.preload()
208 expect(publicIds()).toEqual(expectedPublicWindow(remote))
209 expect(source.toArray.map(({ id }) => id).sort()).toEqual([2, 3])
210 const subscription = live.subscribeChanges(
211 () => publications.push(publicIds()),
212 { includeInitialState: true },
213 )
214 unsubscribe = () => subscription.unsubscribe()
215 publications.length = 0
216
217 const initialRequests = requests.length
218 providerPhase = `optimistic`
219 const transaction =
220 operation === `insert`
221 ? source.insert({ id: 5, folder: `inbox`, at: 7 })
222 : operation === `delete`
223 ? source.delete(3)
224 : source.update(3, (draft) => {
225 draft.folder = `archive`
226 })
227 verdict = transaction.when(`settled`).then(
228 () => undefined,
229 (error: unknown) => error,
230 )
231 expect(publicIds()).toEqual(immediateWindow)
232 expect(publications).toEqual([immediateWindow])
233 reach.reach(`optimistic`)
234
235 if (operation !== `insert`) {
236 await vi.waitFor(() => {
237 expect(requests.length).toBeGreaterThan(initialRequests)
238 expect(
239 requests
240 .slice(initialRequests)
241 .some(
242 ({ options, ids }) =>
243 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
244 options.limit !== undefined &&
245 options.limit <= 4 &&
246 ids.includes(1),
247 ),
248 ).toBe(true)
249 })
250 reach.reach(`bounded-refill`)
251 }
252 for (const { options, ids } of requests.filter(
253 ({ phase }) => phase === `optimistic`,
254 )) {
255 const orderedPage =
256 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
257 options.limit !== undefined &&
258 options.limit <= 4
259 const rankTieProbe = isNarrowRankTieProbe(options, remote)
260 expect(orderedPage || rankTieProbe).toBe(true)
261 expect(ids).not.toContain(4)
262 }
263 expect(publicIds()).toEqual(immediateWindow)
264 expect(
265 publications.every(
266 (snapshot) =>
267 JSON.stringify(snapshot) === JSON.stringify(immediateWindow),
268 ),
269 ).toBe(true)
270
271 if (reportDuringHold) {
272 const head = operation === `insert` ? 6 : 5
273 remote.push({ id: head, folder: `inbox`, at: head })
274 providerPhase = `held-invalidation`
275 await queryClient.invalidateQueries({
276 queryKey: [`optimistic-query-refetch`],
277 })
278 await vi.waitFor(() => expect(reports).toBe(1))
279 await vi.waitFor(() =>
280 expect(
281 requests
282 .slice(requestCountAtReport)
283 .some(
284 ({ options, ids, phase }) =>
285 phase === `held-invalidation` &&
286 options.orderBy?.[0]?.compareOptions.direction === `desc` &&
287 options.limit !== undefined &&
288 options.limit <= 4 &&
289 ids.includes(head),
290 ),
291 ).toBe(true),
292 )
293 expect(publicIds()).toEqual(immediateWindow)
294 expect(publications).toEqual([immediateWindow])
295 reach.reach(`held-report`)
296 }
297
298 persistence.resolve()
299 const actualError = await atMutationCheckpoint(
300 verdict,
301 `ordered handler settlement`,
302 )
303 expect(actualError).toBe(ending.startsWith(`reject`) ? failure : undefined)
304 expect(transaction.state).toBe(
305 ending.startsWith(`reject`) ? `failed` : `completed`,
306 )
307 if (ending !== `reject-before-write`) {
308 expect(handlerConfirmed).toBe(true)
309 reach.reach(`handler-confirmation`)
310 }
311 if (
312 !reportDuringHold &&
313 operation !== `insert` &&
314 ending !== `reject-before-write`
315 ) {
316 expect(
317 requests.some(
318 ({ phase, ids }) =>
319 phase === `handler-refetch` && ids.includes(1) && !ids.includes(3),
320 ),
321 ).toBe(true)
322 }
323 await vi.waitFor(() =>
324 checkOrderedMutationObservation(
325 remote,
326 history.ending,
327 {
328 ids: publicIds(),
329 error: actualError,
330 state: transaction.state,
331 },
332 failure,
333 ),
334 )
335 expect(publications.at(-1)).toEqual(publicIds())
336 reach.reach(`settled-fixed-point`)
337 reach.assertReached()
338 orderedReach.reach(`${operation}/${ending}/${reportDuringHold}`)
339 }, [
340 () => persistence.resolve(),
341 () =>
342 verdict && atMutationCheckpoint(verdict, `ordered cleanup settlement`),
343 () => unsubscribe?.(),
344 () => cleanupLive?.(),
345 () => cleanupSource?.(),
346 () => queryClient.clear(),
347 ])
348}
349
350/**
351 * The public window of the live query `inbox` order `at desc` limit 2, computed
352 * from the plain remote row ledger. This is the model that the check compares
353 * the live rows against at each checkpoint.
354 */
355function expectedPublicWindow(remote: ReadonlyArray<Row>): Array<number> {
356 return remote
357 .filter(({ folder }) => folder === `inbox`)
358 .sort((left, right) => right.at - left.at)
359 .slice(0, 2)
360 .map(({ id }) => id)
361}
362
363// Ordering derives from the backend ledger, while outcome derives from the
364// handler's Promise. Rejecting after confirmation changes only the latter.
365function checkOrderedMutationObservation(
366 remote: ReadonlyArray<Row>,
367 ending: OrderedMutationHistory[`ending`],
368 observed: { ids: Array<number>; error: unknown; state: string },
369 failure: Error,
370): void {
371 expect(observed.ids).toEqual(expectedPublicWindow(remote))
372 expect(observed.error).toBe(ending.startsWith(`reject`) ? failure : undefined)
373 expect(observed.state).toBe(
374 ending.startsWith(`reject`) ? `failed` : `completed`,
375 )
376}
377
378declareOracle({
379 check: [checkOptimisticOrderedRefetch, checkOrderedMutationObservation],
380 model: [expectedPublicWindow],
381 grammar: [orderedMutationHistories],
382})
383
384// The original two update/success histories remain rows of this finite
385// grammar, alongside neighboring wrapper, error and discarded-value histories.
386describe(`ordered mutation histories`, () => {
387 afterAll(() => {
388 orderedReach.assertReached()
389 console.info(
390 `query.ordered-mutation-outcome reach`,
391 Object.fromEntries(orderedReach.counts()),
392 )
393 })
394 it.each(orderedMutationHistories)(
395 `preserves ordered mutation outcomes: %j`,
396 checkOptimisticOrderedRefetch,
397 )
398})
399
400// These controls challenge the same public-window/outcome comparison. They
401// establish sensitivity without changing any production code.
402it.each([
403 `rollback-confirmed-row`,
404 `discarded-value-failure`,
405 `reversed-order`,
406] as const)(`rejects ordered wrong observation: %s`, (fault) => {
407 const remote: Array<Row> = [
408 { id: 1, folder: `inbox`, at: 1 },
409 { id: 2, folder: `inbox`, at: 2 },
410 ]
411 const ending =
412 fault === `rollback-confirmed-row`
413 ? `reject-after-write`
414 : `fulfilled-legacy`
415 const failure = new Error(`handler failure`)
416 const actual = {
417 ids: expectedPublicWindow(remote),
418 error:
419 ending === `reject-after-write`
420 ? (failure as unknown)
421 : (undefined as unknown),
422 state: ending === `reject-after-write` ? `failed` : `completed`,
423 }
424 checkOrderedMutationObservation(remote, ending, actual, failure)
425 if (fault === `rollback-confirmed-row`) actual.ids = [3, 2]
426 if (fault === `discarded-value-failure`) {
427 actual.error = new Error(`legacy value`)
428 actual.state = `failed`
429 }
430 if (fault === `reversed-order`) actual.ids.reverse()
431 expect(() =>
432 checkOrderedMutationObservation(remote, ending, actual, failure),
433 ).toThrow()
434})