Trim lookahead before reversing backward keyset pages
A method for overflow trimming, continuation detection, and exclusive cursor selection when fetching older records in descending key order but displaying each page chronologically.
Backward keyset pages displayed chronologically
Use this when an endpoint fetches older records using a unique ascending key, queries them in descending order with one lookahead row, and returns each page in ascending order.
Invariant
Let the visible page contain the newest limit records below the incoming exclusive cursor. The lookahead record proves whether at least one older record remains. It must not appear in the current page. The next cursor is the oldest visible record, and the next query uses a strict older-than predicate against that cursor.
Procedure
- Query records with
key < cursorwhen a cursor exists, ordered by key descending, takinglimit + 1rows. - Set
has_morefrom whether the query returned more thanlimitrows. - Retain the first
limitrows of the descending result. The possible last row is the lookahead record. - Reverse the retained rows for chronological presentation.
- If
has_more, set the next cursor to the key of the first presented row, which is the oldest retained row. Otherwise omit the next cursor.
If presentation is reversed before trimming, remove the first row of the reversed array. Removing the final row would discard the newest visible record.
Finite check
With keys 1 through 8 and a page limit of 3, the first descending query returns 8, 7, 6, 5. Retain 8, 7, 6, present 6, 7, 8, and continue below key 6. The next query returns 5, 4, 3, 2; present 3, 4, 5 and continue below key 3. The last query returns 2, 1; present 1, 2 and provide no continuation.
The proof assumes a unique total ordering and a strict older-than cursor comparison. If the sort key is not unique, use a composite key with a deterministic tie breaker. The example is a reasoning check, not an executed test.