Skip to content

feat: add page-token pagination helpers - #828

Merged
uniqueg merged 4 commits into
devfrom
feat/799-page-tokens
Nov 25, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/799-page-tokens

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds keyset ("page token") pagination to foca.utils.pagination, next to the offset helpers, so that cloud-registry, drs-filer and proWES can stop maintaining their own variants:

  • get_page_size(value, *, parameter, default=100, maximum=1000) checks a page size and returns 400 with the parameter named and the value not quoted (invalid-type, too-small, too-large). Unlike get_page(), sizes above the maximum are refused rather than clamped, because token pages have no links that would tell clients the size actually used.
  • PageKey(fields, descending=False) sets the sort fields (dot notation, ending with a unique tie-breaker such as _id):
    • sort gives the pymongo sort specification.
    • token(item) issues the opaque token for the page after an item: URL-safe base64 of tagged JSON holding ObjectId, datetime (microseconds, naive times treated as UTC), 8-byte integer or string values.
    • after(token, parameter=...) checks a token exactly (re.fullmatch, length limit, strict structure and type checks) and builds the keyset filter ($or of equality prefixes plus $gt/$lt). Malformed or fabricated tokens get 400 invalid-format.
  • find_page(collection, query, *, key, size, parameter, token=None, projection=None) reads size + 1 items and returns TokenPage(items, next_token). The last page has no token.
  • Parameter names stay with the app (pageToken vs page_token).
  • Docs: a new "Page tokens" section under "Paginating lists" (docs/utilities.md), with an example, the requirements on sort fields, the error codes and the security notes (tokens are opaque but not signed). The API reference is generated from the docstrings.

Release notes are not part of this PR: they are written at release prep (#823 for 0.23.0). Moving cloud-registry, drs-filer and proWES to the helpers is follow-up work in their own repos, as the issue says.

Closes #799

Verification

  • pytest tests/utils/: 687 passed, with 100 % line coverage of foca/utils/pagination.py. New tests in tests/utils/test_pagination_tokens.py cover:

    • first, middle and last pages, a full last page and an empty list;
    • items added or deleted between pages;
    • query and projection, ascending and descending order, and tie-breakers;
    • malformed tokens, and fabricated ones (wrong tags, types and ranges, lone surrogates, deep nesting);
    • size bounds;
    • round trips that are BSON-encodable.
  • The same tests on Python 3.11.16. The deep-nesting regression test fails there without the RecursionError fix.

  • Full suite pytest -m "not mongodb": 5488 passed. The tests marked mongodb need a server and did not run locally; CI runs them.

  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep scan --config .semgrep, mkdocs build --strict and the docstring doctest of PageKey all pass.

  • Reviews: adversarial and quality reviewer subagents, 2 rounds. Fixed:

    • fabricated tokens with lone surrogates gave a 500 at BSON encoding;
    • deeply nested JSON gave a 500 on Python 3.11 (RecursionError);
    • the docs overstated which tokens of other keys are refused;
    • new docs: sort-field values must have one type in all items;
    • new docs: an empty token is invalid;
    • a shared problem helper;
    • a stricter find_page error test.
  • Sourcery review: 7 findings, all addressed in 49f839d, threads answered and resolved:

    • get_page_size() refuses maximums that find_page() can't read;
    • sort paths through arrays are refused;
    • non-canonical tokens (with other unused bits) are refused;
    • docs on long sort values, inserts before the cursor and changing sort values;
    • two stronger tests.
  • CI: all checks pass on 49f839d (30 pass, 3 skipped by design: image push/publish and Trivy on PRs).

Declined review findings

  • Listing the new codes in docs/problems/invalid-request.md: open PR fix: refuse users without namespace in role APIs #827 changes that file. The codes are documented in the new section, which links to the problem docs. A cross-link can follow once fix: refuse users without namespace in role APIs #827 is merged.
  • Merging the new tests into tests/utils/test_pagination.py: kept as a separate file because of their size; both test the same module.
  • Integration tests against a real MongoDB: the unit tests use mongomock, and round trips are now checked with bson.encode. The repo's mongodb-marked tests exercise apps rather than utilities, so a server test of these helpers is left for the first app that adopts them.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5

uniqueg and others added 3 commits November 25, 2026 08:47
Add keyset pagination to foca.utils.pagination, next to the offset
helpers: get_page_size() checks page sizes against a default and a
maximum, PageKey issues opaque tokens for the page after an item and
turns them back into MongoDB filters (with exact checks and 400 for
malformed or fabricated tokens, naming the parameter without quoting
it), and find_page() gets a page of a collection with the next token.

Document them in "Paginating lists".

Closes #799

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Address review findings: refuse decoded strings that BSON can't
encode (400 instead of 500), share the problem helper, document that
empty tokens are invalid and which tokens of other keys pass, and
check the parameter of errors in find_page().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Python 3.11 raises RecursionError, not a ValueError, for deeply nested
JSON, so such fabricated tokens gave a 500. Refuse them with 400, and
document that sort fields need values of one type in all items.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the public TokenPage result structure that carries page items and the optional next token.

  • foca/utils/pagination.py L485-496

API

Expose page-size validation, the public PageKey interface for sort keys and tokens, and find_page() for fetching token-based pages.

  • foca/utils/pagination.py L219-267, L359-484, L497-549

Implementation

Add token dependencies, bounds and field-validation constants, shared request-error construction, and the encoding, decoding, and nested-field helpers used by the pagination API.

  • foca/utils/pagination.py L7-30, L183-218, L268-358

Documentation

Document page-token pagination, its usage and constraints, validation errors, and token security; update the offset guidance to point to the new helpers.

  • docs/utilities.md L84-166

Tests

Add coverage for page-size validation, token encoding and rejection, and MongoDB page retrieval across sort orders, projections, and collection changes.

  • tests/utils/test_pagination_tokens.py L1-404

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5f6c105) to head (49f839d).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #828    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           76        76            
  Lines        10708     10831   +123     
==========================================
+ Hits         10708     10831   +123     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 25, 2026 09:43
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 49f839d

#799 feat: page-token pagination utilities · 6 of 6 met

# Requirement Status Notes
1 Check page size against a configurable default and maximum, returning 400 with the parameter named and value not echoed. ✅ Met get_page_size() supports configurable bounds and reports invalid-type, too-small and too-large through the named parameter.
2 Encode and decode tokens for a stable sort key, with exact validation and 400 for malformed tokens. ✅ Met PageKey provides token encoding, exact token validation and the keyset continuation filter; malformed tokens produce invalid-format.
3 Build the MongoDB filter and sort for the next page, and the next token from the last item. ✅ Met find_page() applies the query and token filter, sorts by the key, reads one extra item, and returns a next token when another page exists.
4 Keep parameter names configurable for different API conventions. ✅ Met get_page_size(), PageKey.after() and find_page() accept the parameter name used in errors.
5 Document the helpers in “Paginating lists.” ✅ Met docs/utilities.md adds a “Page tokens” section under “Paginating lists,” including usage, constraints, errors and security notes.
6 Test first, middle and last pages; additions and deletions between requests; malformed and fabricated tokens; and size bounds. ✅ Met The new pagination-token tests cover these cases, including a full final page and an empty list.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/utils/pagination.py" line_range="248" />
<code_context>
+        ValueError: `default` or `maximum` is less than 1, or more than the
+            largest integer of 8 bytes, or `default` is more than `maximum`.
+    """
+    if not 1 <= default <= maximum <= _MAX_VALUE:
+        raise ValueError(
+            f"`default` and `maximum` must be from 1 to {_MAX_VALUE}, "
</code_context>
<issue_to_address>
**Valid page sizes fail**

When an app configures `maximum` or `default` as `_MAX_VALUE` and a request asks for that size, `get_page_size()` accepts and returns `_MAX_VALUE`, but `find_page()` rejects it because it needs room to fetch one extra item. The caller gets a `ValueError` for a size the helper accepted instead of a page or a client error.

Make `get_page_size()` reject sizes that `find_page()` cannot fetch, including `_MAX_VALUE`.

Also at `foca/utils/pagination.py:526`.
</issue_to_address>

### Comment 2
<location path="foca/utils/pagination.py" line_range="347" />
<code_context>
+    """
+    value: object = item
+    for name in field.split("."):
+        if not isinstance(value, Mapping) or name not in value:
+            raise ValueError(f"Item has no sort field '{field}'")
+        value = value[name]
</code_context>
<issue_to_address>
**Array paths fail pagination**

When a `PageKey` field uses dot notation through an array of embedded documents, `_get_field()` stops when a dotted sort path crosses an array of embedded documents and raises `ValueError`; MongoDB accepts such dotted paths for sorting, so `find_page()` fails instead of returning a page.

Either support array-path sort values with matching keyset semantics or explicitly reject and document array-traversing fields.
</issue_to_address>

### Comment 3
<location path="foca/utils/pagination.py" line_range="425" />
<code_context>
+        values = [_encode_value(_get_field(item, f), f) for f in self.fields]
+        raw = json.dumps(values, ensure_ascii=False, separators=(",", ":"))
+        token = base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
+        if len(token) > _MAX_TOKEN_LENGTH:
+            raise ValueError(
+                f"Values of the sort fields {self.fields} are too long for a page token"
</code_context>
<issue_to_address>
**Long sort values break page requests**

When the last item on a non-final page has a supported string sort value long enough to exceed the token limit, `PageKey.token()` raises `ValueError` when a string sort value makes the token exceed 4096 characters, and `find_page()` lets that exception escape while building `next_token`. A page containing an otherwise valid MongoDB string value can therefore fail as a server error instead of returning a page.

Either support tokens large enough for the documented string values or handle oversized sort values explicitly in `find_page()` and document the resulting API behavior.

Also at `foca/utils/pagination.py:537`.
</issue_to_address>

### Comment 4
<location path="foca/utils/pagination.py" line_range="451" />
<code_context>
+            if not _TOKEN.fullmatch(token):
+                raise ValueError("not a token")
+            padding = "=" * (-len(token) % 4)
+            entries = json.loads(base64.urlsafe_b64decode(token + padding))
+            if not isinstance(entries, list) or len(entries) != len(self.fields):
+                raise ValueError("not a token of this key")
</code_context>
<issue_to_address>
**Changed tokens pass validation**

When a client changes only unused trailing bits in a valid token’s final base64 character, `PageKey.after()` decodes the token without checking that its base64 encoding is canonical, so the changed token passes validation instead of returning the documented `invalid-format` error.

Re-encode the decoded payload and reject the token unless its encoding matches the original token.

Also at `docs/utilities.md:151`.
</issue_to_address>

### Comment 5
<location path="foca/utils/pagination.py" line_range="8" />
<code_context>
 pages from the public URL of the app (`server.public_url`), not from the
 request, whose `Host` header clients control.
+
+Page tokens (keyset pagination), which skip or repeat no items when items are
+added or deleted between requests: :py:func:`get_page_size` checks the page
+size of a request, :py:class:`PageKey` sorts by fields of the items and
</code_context>
<issue_to_address>
**Pages can miss or repeat items**

When an item is inserted before the saved cursor, or an existing item’s sort values change across the cursor between page requests, `PageKey.after()` continues strictly beyond the saved sort values, so an inserted item before the cursor is omitted from later pages, and a changed sort value can make an existing item be omitted or returned twice. The documentation promises no skipped or repeated items despite these cases.

Qualify the documentation’s no-skip/no-repeat claims to explain that inserts before the cursor and changes to sort values can cause items to be omitted or repeated.

Also at `foca/utils/pagination.py:464`, `foca/utils/pagination.py:472`, `docs/utilities.md:92-93`, `docs/utilities.md:134-137`.
</issue_to_address>

### Comment 6
<location path="tests/utils/test_pagination_tokens.py" line_range="339-342" />
<code_context>
+    def test_changes_between_pages(self, pets: Collection[dict[str, Any]]) -> None:
+        """Items added or deleted between pages are not skipped or repeated."""
+        first = self._page(pets, None)
+        pets.insert_one({"name": "new", "born": _TIME + timedelta(days=10)})
+        pets.delete_many({"name": {"$in": ["pet6", "pet5"]}})
+        rest = self._page(pets, first.next_token, size=10)
+        assert _names(rest) == ["pet4", "pet3", "pet2", "pet1", "pet0"]
+
+    def test_query_and_projection(self, pets: Collection[dict[str, Any]]) -> None:
</code_context>
<issue_to_address>
**Mutation test accepts offset pagination**

When the continuation uses the original page-size offset after these mutations, `test_changes_between_pages` passes with an offset-based continuation: inserting one item before the cursor and deleting two shifts the list by a net one item, so skipping the original page size of four still starts at `pet4` and matches the assertion. The test does not distinguish keyset continuation from offset pagination.

Use mutations that make an offset continuation produce a different result, and assert the expected keyset continuation.
</issue_to_address>

### Comment 7
<location path="tests/utils/test_pagination_tokens.py" line_range="326-329" />
<code_context>
+
+    def test_exactly_full_last_page(self, pets: Collection[dict[str, Any]]) -> None:
+        """A full last page has no next token."""
+        first = self._page(pets, None, size=5)
+        last = self._page(pets, first.next_token, size=5)
+        assert len(last.items) == 5
+        assert last.next_token is None
+
+    def test_empty_list(self) -> None:
</code_context>
<issue_to_address>
**Full-page test accepts repeated first page**

When a full first page incorrectly returns `next_token=None` for this page size, `test_exactly_full_last_page` never checks that `first.next_token` exists. If the first full page incorrectly has no token, `last` repeats that first page, and the length and missing-token assertions still pass instead of testing a full final page.

Assert that `first.next_token` is not `None` before fetching `last`, and verify the final page contains the remaining items.
</issue_to_address>

Sourcery assessment

Approval pending. 7 findings to address first.

Blocking findings: foca/utils/pagination.py:248, foca/utils/pagination.py:347, foca/utils/pagination.py:425, foca/utils/pagination.py:451, foca/utils/pagination.py:8, and 2 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread tests/utils/test_pagination_tokens.py Resolved
Comment thread tests/utils/test_pagination_tokens.py Resolved
- get_page_size() refuses maximums that find_page() can't read
- refuse sort paths through arrays, with a clear error
- refuse non-canonical tokens (other unused bits)
- document long sort values, inserts before the cursor and changed
  sort values
- tests that tell keyset from offset continuation, and a stricter
  full-last-page test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@uniqueg
uniqueg merged commit 382098f into dev Nov 25, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/799-page-tokens branch November 25, 2026 12:17
uniqueg added a commit that referenced this pull request Nov 25, 2026
The tag is due on 2026-11-25. #828 (page-token pagination) is part of
0.23.0: name it in the intro and the features of the release notes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: page-token pagination utilities

1 participant