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