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-oracle.js'
10import { createCursorPager } from './cursor-pagination/pager.js'
11import type { Row, Scope, Window } from './cursor-pagination/model-oracle.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.each([1, 2, 5, 50])(
206 `fulfills windows across backend pages of %i`,
207 async (pageSize) => {
208 const backend = createBackend(fixtureRows, allAscending, pageSize)
209 const pager = createCursorPager(backend.fetchPage)
210 for (const window of [
211 { offset: 0, limit: 0 },
212 { offset: 0, limit: 3 },
213 { offset: 2, limit: 6 },
214 { offset: 0, limit: undefined },
215 { offset: 30, limit: 2 },
216 ]) {
217 await checkRead(fixtureRows, allAscending, window, pager.read)
218 }
219 expect(backend.calls).toHaveLength(
220 Math.ceil(fixtureRows.length / pageSize),
221 )
222 },
223 )
224
225 it(`matches whole-relation slices across random window histories`, async () => {
226 await assertCursorProperty(
227 fc.asyncProperty(
228 rowsArbitrary,
229 scopeArbitrary,
230 fc.integer({ min: 1, max: 8 }),
231 fc.array(windowArbitrary, { minLength: 1, maxLength: 20 }),
232 async (rows, scope, pageSize, windows) => {
233 const backend = createBackend(rows, scope, pageSize)
234 const pager = createCursorPager(backend.fetchPage)
235 for (const window of windows)
236 await checkRead(rows, scope, window, pager.read)
237 const calls = backend.calls.length
238 for (const window of [...windows].reverse())
239 await checkRead(rows, scope, window, pager.read)
240 expect(backend.calls).toHaveLength(calls)
241 },
242 ),
243 100,
244 `cursor-pagination.history`,
245 )
246 })
247
248 it(`keeps answers invariant under backend page repartition`, async () => {
249 await assertCursorProperty(
250 fc.asyncProperty(
251 rowsArbitrary,
252 scopeArbitrary,
253 windowArbitrary,
254 async (rows, scope, window) => {
255 for (const size of [1, 4, 50]) {
256 const backend = createBackend(rows, scope, size, true)
257 await checkRead(
258 rows,
259 scope,
260 window,
261 createCursorPager(backend.fetchPage).read,
262 )
263 }
264 },
265 ),
266 100,
267 `cursor-pagination.partition`,
268 )
269 })
270
271 it.each([`abort`, `reject`, `reset`] as const)(
272 `keeps a healthy peer usable after held response %s`,
273 async (action) => {
274 const backend = createBackend(fixtureRows, allAscending, 2)
275 const gate = createDeferred<void>()
276 const abort = new AbortController()
277 const failure = new Error(`backend failed`)
278 let calls = 0
279 const pager = createCursorPager(async (cursor, signal) => {
280 const page = await backend.fetchPage(cursor, signal)
281 if (++calls === 1) await gate.promise
282 return page
283 })
284 const outcomes: Array<string> = []
285 const first = pager.read({ offset: 0, limit: 2 }, abort.signal).then(
286 () => {
287 outcomes.push(`first-success`)
288 return undefined
289 },
290 (error: unknown) => {
291 outcomes.push(`first-error`)
292 return error
293 },
294 )
295 await vi.waitFor(() => expect(calls).toBe(1))
296 expect(outcomes).toEqual([])
297 if (action === `abort`) abort.abort()
298 if (action === `reset`) pager.reset()
299 const peer = pager.read({ offset: 0, limit: 6 })
300 const peerObserved = peer.then((rows) => {
301 outcomes.push(`peer-success`)
302 return rows
303 })
304 if (action === `reject`) gate.reject(failure)
305 else gate.resolve()
306 const error = await first
307 if (action === `reject`) expect(error).toBe(failure)
308 else expect(error).toMatchObject({ name: `AbortError` })
309 await expect(peerObserved).resolves.toEqual(
310 expectedRows(fixtureRows, allAscending, { offset: 0, limit: 6 }),
311 )
312 expect(outcomes).toEqual([`first-error`, `peer-success`])
313 // Cancelling a reader leaves the shared Query fetch active. A successful
314 // page remains reusable; failed or reset Query fetches start again.
315 if (action === `abort`) {
316 expect(backend.calls[1]).toEqual(expect.any(String))
317 expect(backend.calls).toHaveLength(3)
318 } else {
319 expect(backend.calls.slice(0, 2)).toEqual([undefined, undefined])
320 }
321 },
322 )
323
324 it(`serializes unequal peer windows without refetching cached pages`, async () => {
325 const backend = createBackend(fixtureRows, allAscending, 2)
326 const pager = createCursorPager(backend.fetchPage)
327 const windows = [
328 { offset: 0, limit: 3 },
329 { offset: 2, limit: 6 },
330 { offset: 0, limit: 2 },
331 ]
332 const results = await Promise.all(
333 windows.map((window) => pager.read(window)),
334 )
335 expect(results).toEqual(
336 windows.map((window) => expectedRows(fixtureRows, allAscending, window)),
337 )
338 expect(backend.calls).toHaveLength(4)
339 await checkRead(fixtureRows, allAscending, windows[0]!, pager.read)
340 expect(backend.calls).toHaveLength(4)
341 })
342
343 it(`resets source generations and isolates filter/order scopes`, async () => {
344 await assertCursorProperty(
345 fc.asyncProperty(
346 rowsArbitrary,
347 scopeArbitrary,
348 scopeArbitrary,
349 async (rows, firstScope, secondScope) => {
350 let backend = createBackend(rows, firstScope, 3)
351 const pager = createCursorPager((cursor, signal) =>
352 backend.fetchPage(cursor, signal),
353 )
354 const all = { offset: 0, limit: undefined }
355 await checkRead(rows, firstScope, all, pager.read)
356 const changed = rows.map((row) => ({
357 ...row,
358 rank: -row.rank,
359 id: row.id + 100,
360 }))
361 backend = createBackend(changed, secondScope, 2)
362 pager.reset()
363 await checkRead(changed, secondScope, all, pager.read)
364 const independent = createCursorPager(
365 createBackend(rows, firstScope, 4).fetchPage,
366 )
367 await checkRead(rows, firstScope, all, independent.read)
368 await checkRead(changed, secondScope, all, pager.read)
369 },
370 ),
371 50,
372 `cursor-pagination.reset`,
373 )
374 })
375
376 it(`recovers after faults at generated intermediate page boundaries`, async () => {
377 await assertCursorProperty(
378 fc.asyncProperty(
379 fc.array(fc.integer({ min: -2, max: 2 }), {
380 minLength: 12,
381 maxLength: 24,
382 }),
383 fc.integer({ min: 1, max: 4 }),
384 fc.integer({ min: 0, max: 2 }),
385 fc.boolean(),
386 fc.constantFrom(`reject`, `abort`),
387 async (ranks, size, faultPage, descending, fault) => {
388 const rows = ranks.map((rank, id) => ({ id, rank, group: id % 2 }))
389 const scope = { group: undefined, descending }
390 const backend = createBackend(rows, scope, size)
391 const abort = new AbortController()
392 const error = new Error(`page failure`)
393 let calls = 0
394 const pager = createCursorPager(async (cursor, signal) => {
395 const page = await backend.fetchPage(cursor, signal)
396 if (calls++ === faultPage) {
397 if (fault === `reject`) throw error
398 abort.abort(error)
399 }
400 return page
401 })
402 const all = { offset: 0, limit: undefined }
403 const failed = pager.read(all, abort.signal)
404 // Attach observers before the healthy peer can expose a failure.
405 const outcomes = Promise.allSettled([failed, pager.read(all)])
406 const [first, peer] = await outcomes
407 expect(first).toEqual({ status: `rejected`, reason: error })
408 expect(peer).toEqual({
409 status: `fulfilled`,
410 value: expectedRows(rows, scope, all),
411 })
412 expect(backend.calls).toHaveLength(
413 // Query marks failed fetches stale and rebuilds their prefix.
414 Math.ceil(rows.length / size) +
415 (fault === `reject` ? faultPage + 1 : 0),
416 )
417 const before = backend.calls.length
418 await checkRead(rows, scope, { offset: 1, limit: 3 }, pager.read)
419 expect(backend.calls).toHaveLength(before)
420 },
421 ),
422 100,
423 `cursor-pagination.failure`,
424 )
425 })
426})