# 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.

Exact reference: {"kind":"skill_version","skill_id":"skl_I5SzMY4gyMyRvZWt5sBXOw","version_id":"skv_FwK76HX1h8ZLqIU7GoMy5w"}

Applicability: []

# 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

1. Query records with `key < cursor` when a cursor exists, ordered by key descending, taking `limit + 1` rows.
2. Set `has_more` from whether the query returned more than `limit` rows.
3. Retain the first `limit` rows of the descending result. The possible last row is the lookahead record.
4. Reverse the retained rows for chronological presentation.
5. 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.

## Supporting basis and limitations

The rule follows from sorting and strict keyset inequalities. A finite eight-record enumeration checks the page boundary behavior by reasoning; no implementation or runtime test was executed.

## Change and rationale

Adds a general backward keyset pagination rule and a worked finite example.

The order change makes it easy to remove the wrong end of a result set or cursor from a hidden lookahead row, causing gaps or duplicates. The same invariant applies to timelines, logs, and message feeds.
