Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

cursor-pagination.oracle.test.ts

402 lines14.2 KB

1import fc from 'fast-check'
2import { describe, expect, it, vi } from 'vitest'
3import { createDeferred } from '../../db/src/deferred.js'
4import { oraclePropertyOptions } from '../../db/tests/oracle-config.js'
5import { createBackend } from './cursor-pagination/backend.js'
6import { expectedRows } from './cursor-pagination/model.js'
7import { createCursorPager } from './cursor-pagination/pager.js'
8import type { Row, Scope, Window } from './cursor-pagination/model.js'
9​
10/**
11 * # Can opaque pages reconstruct any requested ordered slice?
12 *
13 * The backend owns unreadable continuation tokens and one stable filtered,
14 * totally ordered sequence. The pager may fetch and cache pages, but `read()`
15 * must equal the independent full-relation model for any offset and limit. It
16 * must reject invalid windows, foreign tokens, missing continuation, duplicate
17 * rows, wrong order, and protocol cycles instead of guessing.
18 *
19 * Generated sources vary IDs, ties, groups, direction, backend page size, and
20 * requested windows. The model never sees tokens. The driver observes returned
21 * rows, fetch order, cancellation, and bounded page traversal. This separation
22 * prevents a pager and its oracle from sharing the same cursor arithmetic.
23 */
24​
25const rowsArbitrary = fc.uniqueArray(
26 fc.record({
27 id: fc.integer({ min: 0, max: 60 }),
28 rank: fc.integer({ min: -3, max: 3 }),
29 group: fc.integer({ min: 0, max: 2 }),
30 }),
31 { selector: (row) => row.id, maxLength: 30 },
33const scopeArbitrary = fc.record({
34 group: fc.option(fc.integer({ min: 0, max: 2 }), { nil: undefined }),
35 descending: fc.boolean(),
36})
37const windowArbitrary = fc.record({
38 offset: fc.integer({ min: 0, max: 35 }),
39 limit: fc.option(fc.integer({ min: 0, max: 35 }), { nil: undefined }),
40})
41const fixtureRows: Array<Row> = Array.from({ length: 9 }, (_, id) => ({
42 id,
43 rank: Math.floor(id / 6),
44 group: id % 2,
45}))
46const allAscending: Scope = { group: undefined, descending: false }
47​
48it(`backend sequences reject foreign tokens while retaining their own continuations`, async () => {
49 await fc.assert(
50 fc.asyncProperty(
51 fc.integer({ min: 1, max: 5 }),
52 fc.boolean(),
53 async (size, descending) => {
54 const scope = { group: undefined, descending }
55 const rows = Array.from({ length: size * 3 }, (_, id) => ({
56 id,
57 rank: id,
58 group: 0,
59 }))
60 const a = createBackend(rows, scope, size)
61 const b = createBackend(rows, scope, size)
62 const firstA = await a.fetchPage(undefined),
63 firstB = await b.fetchPage(undefined)
64 expect(firstA.nextCursor).not.toBe(firstB.nextCursor)
65 await expect(
66 Promise.resolve().then(() => b.fetchPage(firstA.nextCursor!)),
67 ).rejects.toThrow(`Foreign`)
68 const own = await b.fetchPage(firstB.nextCursor!)
69 expect(own.rows).toEqual(
70 expectedRows(rows, scope, { offset: size, limit: size }),
71 )
72 },
73 ),
74 oraclePropertyOptions(50, `cursor-pagination.backend-ownership`),
75 )
76})
77​
78async function checkRead(
79 source: Array<Row>,
80 scope: Scope,
81 window: Window,
82 read: (window: Window) => Promise<Array<Row>>,
83) {
84 const expected = expectedRows(source, scope, window)
85 expect(await read(window), `ordered slice ${JSON.stringify(window)}`).toEqual(
86 expected,
87 )
89​
90describe(`cursor pagination reference`, () => {
91 it(`preserves ties, filtering and reverse total order`, () => {
92 expect(
93 expectedRows(
94 fixtureRows,
95 { group: 1, descending: true },
96 { offset: 1, limit: 3 },
97 ).map((row) => row.id),
98 ).toEqual([5, 3, 1])
99 expect(
100 expectedRows(fixtureRows, allAscending, { offset: 0, limit: 0 }),
101 ).toEqual([])
102 })
103​
104 it(`rejects capped-page, wrong-order and duplicate-row answers`, async () => {
105 const window = { offset: 0, limit: 8 }
106 const expected = expectedRows(fixtureRows, allAscending, window)
107 for (const wrong of [
108 expected.slice(0, 2),
109 [...expected].reverse(),
110 [...expected.slice(0, 7), expected[0]!],
111 ]) {
112 await expect(
113 checkRead(fixtureRows, allAscending, window, () =>
114 Promise.resolve(wrong),
115 ),
116 ).rejects.toThrow(`ordered slice`)
117 }
118 await checkRead(fixtureRows, allAscending, window, () =>
119 Promise.resolve(expected),
120 )
121 })
122})
123​
124describe(`opaque cursor adapter`, () => {
125 it.each([
126 { offset: -1, limit: 1 },
127 { offset: 0.5, limit: 1 },
128 { offset: Infinity, limit: 1 },
129 { offset: NaN, limit: 1 },
130 { offset: 0, limit: -1 },
131 { offset: 0, limit: 0.5 },
132 { offset: 0, limit: Infinity },
133 { offset: 0, limit: NaN },
134 { offset: Number.MAX_SAFE_INTEGER, limit: 1 },
135 ])(
136 `rejects invalid windows before transport: $offset/$limit`,
137 async (window) => {
138 const backend = createBackend(fixtureRows, allAscending, 2)
139 const pager = createCursorPager(backend.fetchPage)
140 await expect(pager.read(window)).rejects.toThrow(RangeError)
141 expect(backend.calls).toEqual([])
142 await checkRead(
143 fixtureRows,
144 allAscending,
145 { offset: 0, limit: 2 },
146 pager.read,
147 )
148 },
149 )
150​
151 it(`captures each requested window before queued work starts`, async () => {
152 const backend = createBackend(fixtureRows, allAscending, 2)
153 const pager = createCursorPager(backend.fetchPage)
154 const window = { offset: 1, limit: 3 }
155 const expected = expectedRows(fixtureRows, allAscending, window)
156 const pending = pager.read(window)
157 window.offset = 7
158 window.limit = 1
159 expect(await pending).toEqual(expected)
160 })
161​
162 it(`accepts large backend pages without spreading rows into arguments`, async () => {
163 const rows = Array.from({ length: 150_000 }, (_, id) => id)
164 const pager = createCursorPager(() =>
165 Promise.resolve({ rows, nextCursor: null }),
166 )
167 expect(await pager.read({ offset: 149_997, limit: undefined })).toEqual(
168 rows.slice(149_997),
169 )
170 expect(await pager.read({ offset: 0, limit: 2 })).toEqual(rows.slice(0, 2))
171 })
172​
173 it.each([1, 2, 5, 50])(
174 `fulfills windows across backend pages of %i`,
175 async (pageSize) => {
176 const backend = createBackend(fixtureRows, allAscending, pageSize)
177 const pager = createCursorPager(backend.fetchPage)
178 for (const window of [
179 { offset: 0, limit: 0 },
180 { offset: 0, limit: 3 },
181 { offset: 2, limit: 6 },
182 { offset: 0, limit: undefined },
183 { offset: 30, limit: 2 },
184 ]) {
185 await checkRead(fixtureRows, allAscending, window, pager.read)
186 }
187 expect(backend.calls).toHaveLength(
188 Math.ceil(fixtureRows.length / pageSize),
189 )
190 },
191 )
192​
193 it(`matches whole-relation slices across random window histories`, async () => {
194 await fc.assert(
195 fc.asyncProperty(
196 rowsArbitrary,
197 scopeArbitrary,
198 fc.integer({ min: 1, max: 8 }),
199 fc.array(windowArbitrary, { minLength: 1, maxLength: 20 }),
200 async (rows, scope, pageSize, windows) => {
201 const backend = createBackend(rows, scope, pageSize)
202 const pager = createCursorPager(backend.fetchPage)
203 for (const window of windows)
204 await checkRead(rows, scope, window, pager.read)
205 const calls = backend.calls.length
206 for (const window of [...windows].reverse())
207 await checkRead(rows, scope, window, pager.read)
208 expect(backend.calls).toHaveLength(calls)
209 },
210 ),
211 oraclePropertyOptions(100, `cursor-pagination.history`),
212 )
213 })
214​
215 it(`keeps answers invariant under backend page repartition`, async () => {
216 await fc.assert(
217 fc.asyncProperty(
218 rowsArbitrary,
219 scopeArbitrary,
220 windowArbitrary,
221 async (rows, scope, window) => {
222 for (const size of [1, 4, 50]) {
223 const backend = createBackend(rows, scope, size, true)
224 await checkRead(
225 rows,
226 scope,
227 window,
228 createCursorPager(backend.fetchPage).read,
229 )
230 }
231 },
232 ),
233 oraclePropertyOptions(100, `cursor-pagination.partition`),
234 )
235 })
236​
237 it.each([`abort`, `reject`, `reset`] as const)(
238 `keeps a healthy peer usable after held response %s`,
239 async (action) => {
240 const backend = createBackend(fixtureRows, allAscending, 2)
241 const gate = createDeferred<void>()
242 const abort = new AbortController()
243 const failure = new Error(`backend failed`)
244 let calls = 0
245 const pager = createCursorPager(async (cursor, signal) => {
246 const page = await backend.fetchPage(cursor, signal)
247 if (++calls === 1) await gate.promise
248 return page
249 })
250 const outcomes: Array<string> = []
251 const first = pager.read({ offset: 0, limit: 2 }, abort.signal).then(
252 () => {
253 outcomes.push(`first-success`)
254 return undefined
255 },
256 (error: unknown) => {
257 outcomes.push(`first-error`)
258 return error
259 },
260 )
261 await vi.waitFor(() => expect(calls).toBe(1))
262 expect(outcomes).toEqual([])
263 if (action === `abort`) abort.abort()
264 if (action === `reset`) pager.reset()
265 const peer = pager.read({ offset: 0, limit: 6 })
266 const peerObserved = peer.then((rows) => {
267 outcomes.push(`peer-success`)
268 return rows
269 })
270 if (action === `reject`) gate.reject(failure)
271 else gate.resolve()
272 const error = await first
273 if (action === `reject`) expect(error).toBe(failure)
274 else expect(error).toMatchObject({ name: `AbortError` })
275 await expect(peerObserved).resolves.toEqual(
276 expectedRows(fixtureRows, allAscending, { offset: 0, limit: 6 }),
277 )
278 expect(outcomes).toEqual([`first-error`, `peer-success`])
279 // Cancelling a reader does not cancel Query's shared acquisition. A
280 // successful page remains reusable; failed/reset acquisitions restart.
281 if (action === `abort`) {
282 expect(backend.calls[1]).toEqual(expect.any(String))
283 expect(backend.calls).toHaveLength(3)
284 } else {
285 expect(backend.calls.slice(0, 2)).toEqual([undefined, undefined])
286 }
287 },
288 )
289​
290 it(`serializes unequal peer windows without refetching cached pages`, async () => {
291 const backend = createBackend(fixtureRows, allAscending, 2)
292 const pager = createCursorPager(backend.fetchPage)
293 const windows = [
294 { offset: 0, limit: 3 },
295 { offset: 2, limit: 6 },
296 { offset: 0, limit: 2 },
297 ]
298 const results = await Promise.all(
299 windows.map((window) => pager.read(window)),
300 )
301 expect(results).toEqual(
302 windows.map((window) => expectedRows(fixtureRows, allAscending, window)),
303 )
304 expect(backend.calls).toHaveLength(4)
305 await checkRead(fixtureRows, allAscending, windows[0]!, pager.read)
306 expect(backend.calls).toHaveLength(4)
307 })
308​
309 it(`resets source generations and isolates filter/order scopes`, async () => {
310 await fc.assert(
311 fc.asyncProperty(
312 rowsArbitrary,
313 scopeArbitrary,
314 scopeArbitrary,
315 async (rows, firstScope, secondScope) => {
316 let backend = createBackend(rows, firstScope, 3)
317 const pager = createCursorPager((cursor, signal) =>
318 backend.fetchPage(cursor, signal),
319 )
320 const all = { offset: 0, limit: undefined }
321 await checkRead(rows, firstScope, all, pager.read)
322 const changed = rows.map((row) => ({
323 ...row,
324 rank: -row.rank,
325 id: row.id + 100,
326 }))
327 backend = createBackend(changed, secondScope, 2)
328 pager.reset()
329 await checkRead(changed, secondScope, all, pager.read)
330 const independent = createCursorPager(
331 createBackend(rows, firstScope, 4).fetchPage,
332 )
333 await checkRead(rows, firstScope, all, independent.read)
334 await checkRead(changed, secondScope, all, pager.read)
335 },
336 ),
337 oraclePropertyOptions(50, `cursor-pagination.reset`),
338 )
339 })
340​
341 it(`rejects a repeated opaque cursor without looping`, async () => {
342 let calls = 0
343 const pager = createCursorPager(() => {
344 calls++
345 return Promise.resolve({ rows: [], nextCursor: `same` })
346 })
347 await expect(pager.read({ offset: 0, limit: 1 })).rejects.toThrow(
348 `repeated`,
349 )
350 expect(calls).toBe(2)
351 })
352​
353 it(`recovers after faults at generated intermediate page boundaries`, async () => {
354 await fc.assert(
355 fc.asyncProperty(
356 fc.array(fc.integer({ min: -2, max: 2 }), {
357 minLength: 12,
358 maxLength: 24,
359 }),
360 fc.integer({ min: 1, max: 4 }),
361 fc.integer({ min: 0, max: 2 }),
362 fc.boolean(),
363 fc.constantFrom(`reject`, `abort`),
364 async (ranks, size, faultPage, descending, fault) => {
365 const rows = ranks.map((rank, id) => ({ id, rank, group: id % 2 }))
366 const scope = { group: undefined, descending }
367 const backend = createBackend(rows, scope, size)
368 const abort = new AbortController()
369 const error = new Error(`page failure`)
370 let calls = 0
371 const pager = createCursorPager(async (cursor, signal) => {
372 const page = await backend.fetchPage(cursor, signal)
373 if (calls++ === faultPage) {
374 if (fault === `reject`) throw error
375 abort.abort(error)
376 }
377 return page
378 })
379 const all = { offset: 0, limit: undefined }
380 const failed = pager.read(all, abort.signal)
381 // Attach observers before the healthy peer can expose a failure.
382 const outcomes = Promise.allSettled([failed, pager.read(all)])
383 const [first, peer] = await outcomes
384 expect(first).toEqual({ status: `rejected`, reason: error })
385 expect(peer).toEqual({
386 status: `fulfilled`,
387 value: expectedRows(rows, scope, all),
388 })
389 expect(backend.calls).toHaveLength(
390 // Query marks failed acquisitions stale and rebuilds their prefix.
391 Math.ceil(rows.length / size) +
392 (fault === `reject` ? faultPage + 1 : 0),
393 )
394 const before = backend.calls.length
395 await checkRead(rows, scope, { offset: 1, limit: 3 }, pager.read)
396 expect(backend.calls).toHaveLength(before)
397 },
398 ),
399 oraclePropertyOptions(100, `cursor-pagination.failure`),
400 )
401 })
402})