feat(page): add typed keyset pagination for Bob (#15)
Documentation / docs (push) Successful in 29s
ci / check (push) Successful in 41s
ci / postgres (push) Successful in 45s

Add transport-neutral keyset pagination through native Bob query mods.
Preserve supported cursor value types in a compact versioned format, with
bidirectional pages, explicit row keys, and a separate opt-in count.
Include SQLite tests, PostgreSQL service CI, and the cursor-format ADR.

Closes #6
This commit was merged in pull request #15.
This commit is contained in:
end committed 2026-10-27 20:21:58 -07:00
1 parent e5298cff37
commit c45e8abe08
11 files changed
+1225 -1

No files matched your search

@@ -0,0 +1,91 @@
---
title: Preserve supported value types in versioned page cursors
date: 2026-10-27
status: accepted
implementation: implemented
summary: Pair a plain sort with a typed row key function and preserve supported concrete values with tagged cursors.
tags:
- pagination
- cursors
supersedes: []
superseded_by: []
related:
- /docs/adr/20261025T214616275Z-version-light-core-packages-in-the-root-module-and-nest-heavy-dependency-modules.md
tracking:
- https://gitea.auvem.com/corestack/go/issues/6
implemented_by:
- https://gitea.auvem.com/corestack/go/pulls/15
---
# Preserve supported value types in versioned page cursors
## Context and Problem Statement
[Issue 6](https://gitea.auvem.com/corestack/go/issues/6) requires transport-neutral, non-null keyset pagination through Bob query mods. Cursors may be retained by callers, so their format is a compatibility contract. The owner requires two plain query inputs: a Sort and a typed `func(T) []any` returning column values in sort order. No reflection, struct tags, field lookup or per-column getters may connect rows to columns. Future code generation may produce both values; v0 must work with handwritten values.
Type preservation here means retaining each supported concrete value across encoding/decoding and passing that value to Bob's argument binder. It does not mean statically proving the agreement between independent Sort and key values. JSON decoded into untagged `any` would lose integer precision and concrete types.
## Considered Options
* Plain Sort/key values with explicit tagged scalar encoding: meets the requested API and preserves a documented finite set without reflection.
* Untagged JSON decoded into `[]any`: smaller, but numbers become float64 and concrete type information disappears.
* Per-column generic extractors or caller-defined generic cursor tuples: can tie values to columns more strongly, but do not match the owner's chosen two-value API.
* Reflection, codec registration or arbitrary serialized Go objects: broadens the supported set at the cost of machinery and compatibility obligations not needed for v0.
## Decision Outcome
Use plain Sort/key inputs with tagged JSON, wrapped in unpadded base64url (`base64.RawURLEncoding`). The owner accepted this reviewed design on 2026-10-27, including the two-input API and continuation flags. [PR 15](https://gitea.auvem.com/corestack/go/pulls/15) delivers the implementation, SQLite/PostgreSQL outcome tests and package example. Local build, vet, race tests with real PostgreSQL, pinned lint, TODO and documentation checks passed; independent Standard review's Minor fixture finding was fixed, and fresh High review of `927594b` found no Blocking, Major or Minor findings. Published-head CI remains a merge-readiness gate reported in the PR; this implementation state does not assert CI success, merge or release.
Sort contains a stable caller-owned ID and an ordered list of columns, each with a Bob expression, direction and unique marker. Reject empty sorts, a missing or invalid UTF-8 Sort ID, nil expressions, invalid directions and a missing unique marker on the final column. Columns have no redundant ID field. The marker asserts that column alone is unique in the selected relation under database collation/comparison semantics, including joins. The library cannot prove schema truth. Composite-only uniqueness is outside the issue's final unique-column contract. Expressions and IDs come from trusted application declarations, never cursor-controlled SQL. The sort ID identifies the full immutable interpretation: ordered expressions, directions, key types, uniqueness and comparison semantics. Changing any of these requires a new ID. The backend selects the expected trusted Sort for the query; a decoded token ID must equal its ID. There is no global registry, descriptor fallback or hash subsystem. Local column metadata remains available for validation and query generation; it is not repeated on the wire.
A typed key function returns values in exactly that order. Check `len(key(row)) == len(sort.Columns)` for every returned row used to assemble a page, including the fetched extra row. A mismatch returns a clear programmer-error `KeyError` with expected/actual lengths; never truncate, zip a prefix or emit a bad cursor. Reject nil key functions. Column/value correspondence remains an explicit caller contract; no field discovery or hidden mapping is introduced.
Cursor v1 contains only version, sort ID and ordered typed values. Each value is exactly a two-element `[typeTag,payloadString]` array. Example decoded JSON:
```json
{"v":1,"sort":"orders/recent/v1","values":[["time","2026-10-27T12:00:00Z"],["int64","9007199254740993"]]}
```
For this exact example, compact JSON is 105 bytes and its unpadded base64url token is 140 bytes; the prior descriptor/object format was 242 and 323 bytes respectively. All tags and payloads are strings. Fixed type tags distinguish `int`, `int8`, `int16`, `int32`, `int64`, `string`, `time` and `uuid`. A type switch encodes exactly these concrete Go types; a fixed switch reconstructs them using range-checked integer parsing, valid UTF-8 strings, `time.Time` via RFC3339Nano, and standard-library `uuid.UUID` via canonical lowercase dashed text. Integer decimal text is canonical and never passes through float64. `int` must fit the consuming platform. Normalize timestamps to UTC before RFC3339Nano encoding, preserving the instant and nanoseconds, not monotonic metadata or named timezone identity; reject years unrepresentable in RFC3339 with a typed `ValueError`. Reject invalid UTF-8 rather than silently replacing bytes.
UUID support specifically means Go 1.27.1's standard `uuid.UUID`: its Parse/String methods support this representation and database/sql's default converter converts it to a string for drivers. Third-party UUID types require explicit caller conversion to this type. Named user-defined scalar types, unsigned integers, floats, booleans, pointers, nullable wrappers, byte slices and arbitrary custom types return a typed `ValueError`; no reflection, implicit coercion, custom binder or registry is proposed. A true Go type alias retains its underlying supported identity. Additional types require an explicit format/support decision. V0 sort columns must be non-null and ordered consistently by WHERE and ORDER BY; callers extract actual stored/scanned values, including timestamp precision.
Apply the same maximum of 16 KiB (16,384 bytes) to both emitted and received tokens, measured after final unpadded base64url encoding, including the full envelope. Check received token bytes before decoding, and decode before constructing a mod. Encoding a key or envelope that cannot fit returns a typed `CursorError` and no partial Page. Reject bad base64/JSON, unknown/duplicate/missing envelope fields (only `v`, `sort` and `values` are allowed, so `columns` is rejected), trailing data, version mismatch, a sort ID unequal to the expected Sort ID, wrong value count, nulls, non-array value entries, pairs of any arity other than two, non-string tags/payloads, unknown tags and invalid/range-overflowing payloads. The outer `values` array must contain exactly `len(sort.Columns)` pairs; the former type/value objects are rejected. An exported `CursorError`, inspectable with `errors.As`, distinguishes malformed, version, sort and unsupported-value failures. Encoding unsupported key values returns `ValueError` identifying the position and type, without leaking values. Keys and token shape are validated before producing a Page; errors return no partial page. Cursors are not authenticated: a well-formed edit to a supported value or tag remains a seek request, not a tamper-detection failure. Without expected type metadata in Sort, the library cannot prove an edited supported tag matches a SQL column; driver/database errors propagate normally. Authorization stays in the query.
Prepared pagination exposes one generic Bob `Mod[Q]` targeting native `AppendWhere(...any)`, `AppendOrder(bob.Expression)` and `SetLimit(any)` methods shared by PostgreSQL, SQLite and MySQL SelectQuery. Use Bob expressions and `clause.OrderDef`, fixed operators/directions, and an integer limit. Prepare validates requests/cursors first because ordinary Bob Apply has no error return. Cursor values only enter `expr.Arg(value)`; Bob's existing `any` boundary retains their concrete dynamic type. No custom SQL renderer is needed. Apply once to a query without ORDER BY, LIMIT, OFFSET or FETCH; callers may append their dynamic/authorization filters but must not override pagination/order.
For `(created DESC, id ASC)`, after means `created < c OR (created = c AND id > i)`, grouped as one WHERE condition. Before reverses each comparison. Backward also reverses each ORDER BY direction, fetches limit+1, trims overflow, then reverses retained rows into canonical order. Page[T] holds Items, StartCursor, EndCursor, HasNext and HasPrevious; cursors describe the canonical first/last returned items, or are empty when no items exist. Deleted anchors remain value boundaries. Writes or changed filters between requests may skip/repeat items; no snapshot is promised.
Forward maps first/after and Backward maps last/before to a transport-neutral Direction, Size and Cursor request. Request rules: zero direction is Forward, zero/absent size uses configured default, negative sizes and invalid directions fail, oversized sizes clamp to maximum; require `1 <= default <= maximum` and overflow-safe limit+1. Empty cursor means no anchor. The owner selected continuation semantics: forward HasNext=overflow and HasPrevious=nonempty after; backward HasPrevious=overflow and HasNext=nonempty before. This applies even to empty/stale results. An anchor-derived opposite flag does not prove rows exist; no extra existence probes are required.
Bob v0.50.0 distinguishes generated column references from generated typed WHERE helpers. Generated references such as `models.Orders.Columns.CreatedAt` (schematic; this repository has no generated models) satisfy `bob.Expression` and can replace handwritten `expr.Quote` identifiers in Sort. Their generated per-table column type embeds the dialect Expression and has no Go value-type parameter: neither reference nor `expr.Quote` statically links that expression to a `time.Time` key. In contrast, generated `models.SelectWhere.Orders.CreatedAt` uses `WhereMod[Q, time.Time]`; its `EQ`/`LT`/`GT` arguments must be assignable to `time.Time`, and Q must satisfy Bob's Filterable constraint. These helpers produce WHERE mods, not sortable column expressions, and expose no public expression accessor. They cannot be substituted directly for Sort expressions or consume a heterogeneous `[]any` element without recovering the expected concrete type. The chosen API preserves the concrete dynamic values through the codec/binder and checks lengths at runtime; it promises no compile-time column/key type or order agreement. The owner deferred stronger compile-time field correspondence to [code generation issue 11](https://gitea.auvem.com/corestack/go/issues/11); no code generation or stronger typed abstraction is implemented here.
A concrete call shape using schematic Bob-generated references is (this repository has no generated models):
```go
sort := page.Sort{ID: "orders/recent/v1", Columns: []page.Column{
{Expression: models.Orders.Columns.CreatedAt, Direction: page.Desc},
{Expression: models.Orders.Columns.ID, Direction: page.Asc, Unique: true},
}}
key := func(o Order) []any { return []any{o.CreatedAt, o.ID} } // time.Time, int64
prepared, err := page.Prepare(sort, key, page.Request{
Direction: page.Forward, Size: 25, Cursor: after,
}, page.Limits{Default: 25, Maximum: 100})
// Handle err before applying the mod to a normal Bob PostgreSQL SELECT q.
q.Apply(page.Mod[*pgdialect.SelectQuery](prepared))
q.Apply(sm.Where(psql.Quote("orders", "tenant_id").EQ(psql.Arg(tenantID))))
// Execute q with Bob's normal Order mapper, obtaining up to 26 []Order rows.
result, err := prepared.Page(rows)
```
Backward changes Direction and supplies the before cursor. `pgdialect`/`sm` are Bob's PostgreSQL dialect/select-mod packages; corresponding SQLite/MySQL select types use the same mod. `Page` retains the typed `Order` key function; `o.ID` is restored as int64, including above 2^53. A separate opt-in `Count(ctx, executor, callerBuiltCountQuery)` executes an explicitly counting, authorized unpaginated Bob query. It never guesses how to strip pagination or count grouped/distinct caller relations.
Bob v0.50.0 is source-feasible for all three dialects, with two reported limitations: generic `mods.OrderBy` expects a different AppendOrder signature from actual selects (native ModFunc matches); MySQL's select writer discards LIMIT expression arguments (use the normal native integer LIMIT API, while cursor WHERE values remain bound). SQLite runs in-process in the normal test suite. PostgreSQL uses the same pagination outcome suite and a required CI service container. MySQL has compile-time native mod composition coverage; runtime behavior remains unverified. Bob belongs in the root module under the accepted module-boundary ADR; no UUID dependency is needed. No persistence, writers, migrations, secrets, workers or timers are introduced.
### Consequences
* The owner-chosen Sort/key separation is simple and code-generation-ready, with runtime length errors instead of compile-time column/value agreement. Tests and package examples must demonstrate correct pairing and disagreement failures.
* Explicit tags retain supported concrete types without reflection, precision loss or a registry. Unsupported custom/third-party types require explicit caller conversion or a later support decision.
* Version and sort IDs become compatibility commitments; changes may deliberately reject retained cursors. No legacy decoder is needed before another version exists.
* Cursors expose values and permit valid edits; queries, counts and every request must preserve authorization. Concurrent writes have no snapshot guarantee. Nothing runs when unused.
* Implementation tests must cover tagged round trips (including large integers, time with an unusual second-offset timezone, and UUID), unrepresentable timestamp years, encoded-token boundaries at and above 16 KiB for both emission and receipt, oversized-string rejection with a typed error and no partial Page, unsupported/malformed/tampered/mismatched cursors (including removed `columns` fields, object-shaped values, incorrect pair arity and non-string entries), Sort/key disagreement, mixed-direction ties, both directions, boundaries and size clamping, plus a package Example of the key function. Execute our pagination and compliant binding/composition tests on in-process SQLite and PostgreSQL CI; do not assert Bob SQL formatting/rendering guarantees. MySQL remains source-feasible until runtime coverage exists.