Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import {
3 BasicIndex,
4 createCollection,
5 createLiveQueryCollection,
6} from '@tanstack/db'
7import { describe, expect, it, vi } from 'vitest'
8import fc from 'fast-check'
9import { oraclePropertyOptions } from '../../db/tests/oracle-config.js'
10import { createDeferred } from '../../db/src/deferred.js'
11import { createLiveQueryWindowController } from '../../db/src/live-query-window-controller.js'
12import { createCursorPager, queryCollectionOptions } from '../src/index.js'
13import { createBackend } from './cursor-pagination/backend.js'
14import { expectedWindow } from './cursor-pagination/model.js'
15import type { Row, Scope } from './cursor-pagination/model.js'
16
17/**
18 * # Does opaque pagination refine a real live-query window?
19 *
20 * This is the end-to-end path: QueryClient -> QueryCollection -> query graph ->
21 * shared window controller. The visible window and `hasNextPage` must match the
22 * independent full-relation model through growth, offset, ties, filtering,
23 * cancellation, replacement, and cache reuse.
24 *
25 * The fixture endpoint supports prefix and rank-equality tie requests. Other
26 * predicates and cursor expressions reject rather than silently dropping IR.
27 * Each tie filter has its own opaque backend sequence, just like the prefix.
28 */
29function createFixture(
30 rows: Array<Row>,
31 scope: Scope,
32 backendSize: number,
33 holdFirst = false,
34) {
35 const backend = { calls: [] as Array<string | undefined> }
36 const gate = createDeferred<void>()
37 let received = 0
38 const client = new QueryClient({
39 defaultOptions: {
40 queries: { retry: false, staleTime: Infinity, gcTime: Infinity },
41 },
42 })
43 const makePager = (rank?: number) => {
44 const makeBackend = () =>
45 createBackend(
46 rank === undefined ? rows : rows.filter((row) => row.rank === rank),
47 scope,
48 backendSize,
49 )
50 let transport = makeBackend()
51 return createCursorPager({
52 queryClient: client,
53 queryKey: [`cursor-experiment`, scope, `opaque-pages`, rank ?? null],
54 fetchPage: async (cursor, signal) => {
55 if (cursor === undefined) transport = makeBackend()
56 if (rank === undefined) backend.calls.push(cursor)
57 const page = await transport.fetchPage(cursor, signal)
58 if (++received === 1 && holdFirst) await gate.promise
59 return page
60 },
61 })
62 }
63 const pager = makePager()
64 const ties = new Map<number, ReturnType<typeof makePager>>()
65 const requests: Array<{ offset: number; limit: number | undefined }> = []
66 const direction = scope.descending ? `desc` : `asc`
67 const source = createCollection(
68 queryCollectionOptions<Row>({
69 queryClient: client,
70 queryKey: [`cursor-experiment`, scope, `rows`],
71 syncMode: `on-demand`,
72 autoIndex: `eager`,
73 defaultIndexType: BasicIndex,
74 getKey: (row) => row.id,
75 queryFn: async (ctx) => {
76 const options = ctx.meta?.loadSubsetOptions
77 let reader = pager
78 const where = options?.where
79 if (where !== undefined) {
80 if (
81 where.type !== `func` ||
82 where.name !== `eq` ||
83 where.args.length !== 2 ||
84 where.args[0]?.type !== `ref` ||
85 where.args[0].path.length !== 1 ||
86 where.args[0].path[0] !== `rank` ||
87 where.args[1]?.type !== `val` ||
88 typeof where.args[1].value !== `number`
89 ) {
90 throw new Error(`Unsupported fixture predicate`)
91 }
92 const rank = where.args[1].value
93 let tie = ties.get(rank)
94 if (!tie) {
95 tie = makePager(rank)
96 ties.set(rank, tie)
97 }
98 reader = tie
99 }
100 expect(
101 options?.cursor,
102 `fixture uses offset requests, not IR cursors`,
103 ).toBeUndefined()
104 if (options?.orderBy) {
105 expect(options.orderBy).toMatchObject([
106 { expression: { path: [`rank`] }, compareOptions: { direction } },
107 { expression: { path: [`id`] }, compareOptions: { direction } },
108 ])
109 }
110 const window = { offset: options?.offset ?? 0, limit: options?.limit }
111 requests.push(window)
112 return reader.read(window, ctx.signal)
113 },
114 }),
115 )
116 const live = createLiveQueryCollection((q) =>
117 q
118 .from({ row: source })
119 .orderBy(({ row }) => row.rank, direction)
120 .orderBy(({ row }) => row.id, direction)
121 .limit(1),
122 )
123 return {
124 backend,
125 gate,
126 requests,
127 live,
128 source,
129 refresh: () =>
130 client.invalidateQueries(
131 { queryKey: [`cursor-experiment`, scope] },
132 { throwOnError: true },
133 ),
134 received: () => received,
135 async cleanup() {
136 gate.resolve()
137 await live.cleanup()
138 await source.cleanup()
139 client.clear()
140 },
141 }
142}
143
144const matrix = [0, 1, 9, 20].flatMap((count) =>
145 [2, 5].flatMap((backendSize) =>
146 [3, 7].flatMap((pageSize) =>
147 [false, true].map((descending) => ({
148 count,
149 backendSize,
150 pageSize,
151 descending,
152 })),
153 ),
154 ),
155)
156
157// This oracle checks all user row fields and their order. Virtual Collection
158// fields ($key/$origin/etc.) are outside the cursor adapter's responsibility.
159const observeRows = (rows: ReadonlyArray<Row>) =>
160 rows.map(({ id, rank, group }) => ({ id, rank, group }))
161
162describe(`cursor adapter through production pagination`, () => {
163 it.each([
164 { wrapped: false, nested: false },
165 { wrapped: false, nested: true },
166 { wrapped: true, nested: false },
167 ])(
168 `manual writes preserve cache shapes: $wrapped/$nested`,
169 async ({ wrapped, nested }) => {
170 await fc.assert(
171 fc.asyncProperty(
172 fc.array(
173 fc.record({
174 kind: fc.constantFrom(`insert`, `update`, `delete`),
175 position: fc.nat({ max: 10 }),
176 }),
177 { minLength: 1, maxLength: 8 },
178 ),
179 fc.integer({ min: 2, max: 6 }),
180 async (operations, count) => {
181 const client = new QueryClient({
182 defaultOptions: {
183 queries: {
184 retry: false,
185 staleTime: Infinity,
186 gcTime: Infinity,
187 },
188 },
189 })
190 const rows = Array.from({ length: count }, (_, id) => ({
191 id,
192 rank: id,
193 group: 0,
194 }))
195 const pageKey = [`manual`, `pages`]
196 const rowKey = nested ? [`manual`] : [`manual`, `rows`]
197 const pager = createCursorPager({
198 queryClient: client,
199 queryKey: pageKey,
200 fetchPage: () => Promise.resolve({ rows, nextCursor: null }),
201 })
202 const common = {
203 queryClient: client,
204 queryKey: rowKey,
205 getKey: (row: Row) => row.id,
206 }
207 const source = createCollection(
208 wrapped
209 ? queryCollectionOptions({
210 ...common,
211 queryFn: async () => ({
212 items: await pager.read({}),
213 label: `keep`,
214 }),
215 select: (response) => response.items,
216 })
217 : queryCollectionOptions({
218 ...common,
219 queryFn: () => pager.read({}),
220 }),
221 )
222 try {
223 await source.preload()
224 // Raw row caches with no data must still be seeded by manual writes.
225 const emptyKey = [...rowKey, `unloaded`]
226 if (!wrapped)
227 client.getQueryCache().build(client, { queryKey: emptyKey })
228 const expected = rows.map((row) => ({ ...row }))
229 let nextId = count
230 for (const [step, operation] of operations.entries()) {
231 await client.invalidateQueries({
232 queryKey: pageKey,
233 exact: true,
234 refetchType: `none`,
235 })
236 const previous = client.getQueryState(pageKey)
237 const position =
238 operation.position % Math.max(1, expected.length)
239 if (operation.kind === `insert` || !expected.length) {
240 const row = { id: nextId, rank: nextId++, group: 0 }
241 source.utils.writeInsert({ ...row })
242 expected.push(row)
243 } else if (operation.kind === `update`) {
244 source.utils.writeUpdate({
245 id: expected[position]!.id,
246 group: step + 1,
247 })
248 expected[position]!.group = step + 1
249 } else {
250 source.utils.writeDelete(expected[position]!.id)
251 expected.splice(position, 1)
252 }
253 expect(observeRows([...source.values()])).toEqual(expected)
254 expect(client.getQueryData(rowKey)).toEqual(
255 wrapped ? { items: expected, label: `keep` } : expected,
256 )
257 if (!wrapped)
258 expect(client.getQueryData(emptyKey)).toEqual(expected)
259 // Preserving the object alone is insufficient: a no-op setQueryData
260 // also clears invalidation and marks an unrelated sequence fresh.
261 expect(
262 client.getQueryState(pageKey),
263 `manual writes must not touch page state`,
264 ).toBe(previous)
265 expect(await pager.read({})).toEqual(rows)
266 }
267 } finally {
268 await source.cleanup()
269 client.clear()
270 }
271 },
272 ),
273 oraclePropertyOptions(50, `cursor-pagination.manual-write`),
274 )
275 },
276 )
277 it.each(
278 [false, true].flatMap((descending) =>
279 [2, 5].map((backendSize) => ({ descending, backendSize })),
280 ),
281 )(
282 `refreshes changed backend rows before growing the window $descending/$backendSize`,
283 async ({ descending, backendSize }) => {
284 const rows = Array.from({ length: 3 }, (_, id) => ({
285 id,
286 rank: 0,
287 group: 0,
288 }))
289 const scope = { group: undefined, descending }
290 const fixture = createFixture(rows, scope, backendSize)
291 const controller = createLiveQueryWindowController(fixture.live, {
292 pageSize: 3,
293 })
294 const stop = controller.subscribe(() => {})
295 try {
296 await controller.preload()
297 expect(observeRows(controller.getSnapshot().data)).toEqual(
298 expectedWindow(rows, scope, 3).rows,
299 )
300 expect(controller.getSnapshot().hasNextPage).toBe(false)
301 for (const count of [9, 2, 0, 7]) {
302 const previous = observeRows(controller.getSnapshot().data)
303 const calls = fixture.backend.calls.length
304 rows.splice(
305 0,
306 rows.length,
307 ...Array.from({ length: count }, (_, id) => ({
308 id,
309 rank: Math.floor(id / 6),
310 group: count,
311 })),
312 )
313 // Refreshing only the outer row query still allows its fresh page
314 // cache. Prefix invalidation is the explicit two-cache refresh path.
315 await fixture.source.utils.refetch({ throwOnError: true })
316 expect(observeRows(controller.getSnapshot().data)).toEqual(previous)
317 expect(fixture.backend.calls).toHaveLength(calls)
318 await fixture.refresh()
319 const expected = expectedWindow(rows, scope, 3)
320 await vi.waitFor(() => {
321 expect(observeRows(controller.getSnapshot().data)).toEqual(
322 expected.rows,
323 )
324 expect(controller.getSnapshot().hasNextPage).toBe(
325 expected.hasNextPage,
326 )
327 })
328 }
329 await controller.fetchNextPage()
330 expect(observeRows(controller.getSnapshot().data)).toEqual(
331 expectedWindow(rows, scope, 6).rows,
332 )
333 expect(controller.getSnapshot().hasNextPage).toBe(true)
334 } finally {
335 stop()
336 controller.dispose()
337 await fixture.cleanup()
338 }
339 },
340 )
341
342 it.each(matrix)(
343 `publishes exact pages and exhaustion $count/$backendSize/$pageSize/$descending`,
344 async ({ count, backendSize, pageSize, descending }) => {
345 const rows = Array.from({ length: count }, (_, id) => ({
346 id,
347 rank: Math.floor(id / 6),
348 group: id % 2,
349 }))
350 const scope = { group: undefined, descending }
351 const fixture = createFixture(rows, scope, backendSize)
352 const controller = createLiveQueryWindowController(fixture.live, {
353 pageSize,
354 })
355 const publications: Array<{
356 rows: Array<Row>
357 pages: number
358 more: boolean
359 ready: boolean
360 }> = []
361 const unsubscribe = controller.subscribe(() => {
362 const snapshot = controller.getSnapshot()
363 publications.push({
364 rows: observeRows(snapshot.data),
365 pages: snapshot.pageParams.length,
366 more: snapshot.hasNextPage,
367 ready: snapshot.isReady,
368 })
369 })
370 try {
371 await controller.preload()
372 for (let page = 1; page <= Math.ceil(count / pageSize) + 1; page++) {
373 const expected = expectedWindow(rows, scope, page * pageSize)
374 const snapshot = controller.getSnapshot()
375 expect(observeRows(snapshot.data)).toEqual(expected.rows)
376 expect(snapshot.hasNextPage).toBe(expected.hasNextPage)
377 expect(observeRows(snapshot.pages.flat())).toEqual(expected.rows)
378 if (!expected.hasNextPage) break
379 await controller.fetchNextPage()
380 }
381 expect(publications.length).toBeGreaterThan(0)
382 expect(publications.some((published) => published.ready)).toBe(true)
383 for (const published of publications) {
384 if (published.ready) {
385 const expected = expectedWindow(
386 rows,
387 scope,
388 published.pages * pageSize,
389 )
390 expect(published.rows).toEqual(expected.rows)
391 expect(published.more).toBe(expected.hasNextPage)
392 }
393 }
394 expect(fixture.requests.length).toBeGreaterThan(0)
395 expect(fixture.requests[0]?.limit).toBe(pageSize + 1)
396 expect(fixture.backend.calls).toHaveLength(
397 Math.max(1, Math.ceil(count / backendSize)),
398 )
399 } finally {
400 unsubscribe()
401 controller.dispose()
402 await fixture.cleanup()
403 }
404 },
405 )
406
407 it(`holds real response delivery and preserves a shallower peer after deep exhaustion`, async () => {
408 const rows = Array.from({ length: 9 }, (_, id) => ({
409 id,
410 rank: Math.floor(id / 6),
411 group: 0,
412 }))
413 const scope = { group: undefined, descending: false }
414 const fixture = createFixture(rows, scope, 2, true)
415 const shallow = createLiveQueryWindowController(fixture.live, {
416 pageSize: 3,
417 })
418 const deep = createLiveQueryWindowController(fixture.live, { pageSize: 10 })
419 const publications: Array<Array<number>> = []
420 const stopShallow = shallow.subscribe(() =>
421 publications.push(shallow.getSnapshot().data.map((row) => row.id)),
422 )
423 const stopDeep = deep.subscribe(() => {})
424 let settled = 0
425 const pending = Promise.allSettled(
426 [shallow.preload(), deep.preload()].map((promise) =>
427 promise.then(() => {
428 settled++
429 }),
430 ),
431 )
432 try {
433 await vi.waitFor(() => expect(fixture.received()).toBe(1))
434 expect(settled).toBe(0)
435 expect(shallow.getSnapshot().data).toEqual([])
436 expect(publications.every((batch) => batch.length === 0)).toBe(true)
437 fixture.gate.resolve()
438 expect((await pending).map((result) => result.status)).toEqual([
439 `fulfilled`,
440 `fulfilled`,
441 ])
442 expect(shallow.getSnapshot().hasNextPage).toBe(true)
443 expect(deep.getSnapshot().hasNextPage).toBe(false)
444 stopDeep()
445 deep.dispose()
446 await shallow.preload()
447 expect(observeRows(shallow.getSnapshot().data)).toEqual(rows.slice(0, 3))
448 expect(shallow.getSnapshot().hasNextPage).toBe(true)
449 await shallow.fetchNextPage()
450 expect(observeRows(shallow.getSnapshot().data)).toEqual(rows.slice(0, 6))
451 expect(fixture.backend.calls).toHaveLength(5)
452 } finally {
453 fixture.gate.resolve()
454 await pending
455 stopShallow()
456 stopDeep()
457 shallow.dispose()
458 deep.dispose()
459 await fixture.cleanup()
460 }
461 })
462})