Repository navigation
feat: add page-token pagination helpers - #828
Conversation
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
Reviewer's GuideData structuresDefine the public
APIExpose page-size validation, the public
ImplementationAdd token dependencies, bounds and field-validation constants, shared request-error construction, and the encoding, decoding, and nested-field helpers used by the pagination API.
DocumentationDocument page-token pagination, its usage and constraints, validation errors, and token security; update the offset guidance to point to the new helpers.
TestsAdd coverage for page-size validation, token encoding and rejection, and MongoDB page retrieval across sort orders, projections, and collection changes.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 49f839d #799 feat: page-token pagination utilities · 6 of 6 met
|
There was a problem hiding this comment.
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
- 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
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
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 returns400with the parameter named and the value not quoted (invalid-type,too-small,too-large). Unlikeget_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):sortgives thepymongosort specification.token(item)issues the opaque token for the page after an item: URL-safe base64 of tagged JSON holdingObjectId,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 ($orof equality prefixes plus$gt/$lt). Malformed or fabricated tokens get400 invalid-format.find_page(collection, query, *, key, size, parameter, token=None, projection=None)readssize + 1items and returnsTokenPage(items, next_token). The last page has no token.pageTokenvspage_token).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 offoca/utils/pagination.py. New tests intests/utils/test_pagination_tokens.pycover:The same tests on Python 3.11.16. The deep-nesting regression test fails there without the
RecursionErrorfix.Full suite
pytest -m "not mongodb": 5488 passed. The tests markedmongodbneed 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 --strictand the docstring doctest ofPageKeyall pass.Reviews: adversarial and quality reviewer subagents, 2 rounds. Fixed:
RecursionError);find_pageerror test.Sourcery review: 7 findings, all addressed in 49f839d, threads answered and resolved:
get_page_size()refuses maximums thatfind_page()can't read;CI: all checks pass on 49f839d (30 pass, 3 skipped by design: image push/publish and Trivy on PRs).
Declined review findings
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.tests/utils/test_pagination.py: kept as a separate file because of their size; both test the same module.bson.encode. The repo'smongodb-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