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