Skip to content

fix: refuse page tokens that aren't strings - #829

Merged
uniqueg merged 5 commits into
devfrom
fix/page-token-checks
Nov 25, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/page-token-checks

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up of #828 from the pre-release review of 0.23.0 (before the helpers ship):

  • PageKey.after() (and so find_page()) refuses page tokens that aren't strings (e.g., 123 from a JSON body) as invalid-format (400); before, TypeError (500).
  • PageKey refuses fields that aren't a tuple of strings: PageKey(("name")) (a string) sorted by the characters of the name and failed on every list with a next page; PageKey((1,)) raised TypeError; a list broke hashing.
  • docs/utilities.md ("Page tokens"): when find_page() raises ValueError (only for a page with a next page), how items without a sort field sort (first when ascending, skipped when descending), why to sort by values the app sets rather than values users write, how to accept empty tokens of generated clients (None if pageToken == "" else pageToken), TokenPage, and the ValueErrors of the helpers' own arguments. Reflowed the PageKey bullet.

Closes #830

Verification

  • Tests first: test_tokens_of_other_types and test_fields_not_tuple_of_strings failed before the fixes, pass after.
  • pytest tests/utils/test_pagination_tokens.py tests/utils/test_pagination.py: 146 passed; coverage report --include=foca/utils/pagination.py: 100%.
  • ruff check ., ruff format --check ., mypy (192 files), ast-grep scan --error, semgrep scan --config .semgrep --error: pass.
  • mkdocs build --strict: pass.
  • Not run locally: the MongoDB test jobs and integration tests (no mongod here); CI runs them.

Review

Two rounds of the adversarial-reviewer and quality-reviewer subagents; no high findings. Fixed: the medium of round 1 (docs reflow and claims checked against the code) and the lows that affect behaviour (non-string tokens, string/list/non-string fields, docs precision on ValueErrors and null ordering; the collation note was dropped as not supported by the code path).

Declined review findings

  • get_page_size(maximum=50) without default raises ValueError (unlike get_page(), which clamps): kept as a programmer error, documented ("with a maximum below 100, pass a default too").
  • Empty tokens stay invalid: documented, with the one-line opt-in for APIs that accept them.
  • find_page() keeps raising ValueError for items without a valid token instead of a problem: the cause is the app's data or key, which a client can't fix; documented, with the advice to sort by values the app sets.
  • Doctest of PageKey not run in CI and shared integer parsing with _get_integer: out of scope for a release fix.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5

Summary by Sourcery

Harden pagination token and page-key validation while documenting pagination edge cases and helper errors.

Bug Fixes:

  • Reject non-string page tokens as invalid requests instead of allowing them to cause server errors.
  • Validate that pagination fields are a tuple of distinct, valid strings, preventing malformed keys from breaking pagination.

Enhancements:

  • Clarify pagination token behavior, sorting edge cases, helper argument errors, and TokenPage usage in the utilities documentation.

Documentation:

  • Expand page-token documentation to cover empty tokens, non-string tokens, invalid sort values, and expected ValueError behavior.

Tests:

  • Add coverage for non-string tokens and invalid pagination field definitions.

uniqueg and others added 3 commits November 25, 2026 15:10
PageKey.after() raised TypeError, so a 500, for tokens of other types,
e.g., from JSON bodies; they are now invalid-format, as other
malformed tokens. Document what the pre-release review of 0.23.0
found missing: the ValueError of find_page() for items without a
valid token and why to sort by values the app sets, skipped items
without sort fields, collations, empty tokens of generated clients,
TokenPage, and the ValueErrors of the helpers' own arguments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
PageKey("name") sorted by the characters of the name, so lists with
more than one page failed. Follow the review: wrap the docs, say when
find_page() raises and how items without sort fields sort in either
order, drop the collation note, accept only empty tokens as the first
page, and assert that other types of tokens aren't quoted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
PageKey((1,)) raised TypeError and PageKey(["a"]) broke hashing;
both are now ValueErrors, as the docs say.

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

API

Make PageKey reject non-tuple or non-string fields and make after() report non-string page tokens as invalid-format.

  • foca/utils/pagination.py L384-386, L400-403, L454-460

Documentation

Explain page-token handling, pagination edge cases, and helper argument errors, and clarify PageKey and TokenPage behavior.

  • docs/utilities.md L104-117, L151-169

Tests

Cover invalid page-key field shapes and ensure non-string tokens produce the expected invalid-format field error without echoing the token.

  • tests/utils/test_pagination_tokens.py L114-115, L122-127, L251-259

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 (4baaf89) to head (992ec71).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #829   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           76        76           
  Lines        10831     10831           
=========================================
  Hits         10831     10831           
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 15:08

@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 3 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="403-404" />
<code_context>
+            # A string, e.g., `("name")`, would sort by its characters
+            not isinstance(self.fields, tuple)
+            or not self.fields
+            or not all(isinstance(field, str) for field in self.fields)
             or len(set(self.fields)) != len(self.fields)
             or not all(_FIELD.fullmatch(field) for field in self.fields)
         ):
</code_context>
<issue_to_address>
**Unhashable fields raise TypeError**

When a tuple contains a `str` subclass with `__hash__ = None`, `isinstance(field, str)` accepts it, then `len(set(self.fields))` raises `TypeError` instead of the documented `ValueError`.

Reject unhashable fields before deduplicating them, and raise the documented `ValueError`.

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

### Comment 2
<location path="docs/utilities.md" line_range="153-155" />
<code_context>
-the same order, keeps pages fast.
+`find_page()` raises a `ValueError` (so the app answers `500`) for a page
+that has a next page and whose last item has no valid token. Items without
+a sort field sort as `null`: first in ascending order (a `500` once they
+fill a page), and last in descending order, where the filter of each next
+page leaves them out, so they are skipped once a page ends before them. So sort by values that the app
+sets itself (e.g., times of creation and identifiers), not by values that
+users write (e.g., names), unless the app checks their type and length when
</code_context>
<issue_to_address>
**Missing fields aren't always skipped**

When a `PageKey` has multiple fields and an item lacks a later sort field, `PageKey.after()` builds a lexicographic `$or` filter, so a document missing a later sort field can still match an earlier-field comparison and appear on a subsequent descending page, contrary to the blanket claim that such items are left out and skipped.

Describe missing values as null in the affected sort-field component, and qualify the ordering and skipping behavior for compound keys.
</issue_to_address>

### Comment 3
<location path="docs/utilities.md" line_range="163-166" />
<code_context>
+to find the items after a token.
+
+Errors of the app's own calls raise `ValueError` (see the [API
+reference](reference.md) for each): e.g., page keys without fields, with a
+string or list instead of a tuple of fields, with fields named twice, or
+with names that have empty parts or parts starting with `$`; a `default` of
+`get_page_size()` larger than its `maximum` (with a `maximum` below 100,
+pass a `default` too).

</code_context>
<issue_to_address>
**Pagination API reference is missing**

When a reader follows the new API-reference direction for a pagination helper, the sentence directs readers to the API reference for each helper, but `docs/reference.md` has no pagination entries, so readers cannot find the promised per-helper reference there.

Add the pagination helpers to `docs/reference.md`, or change the direction to point to a reference that documents them.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/utils/pagination.py:404, docs/utilities.md:155


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

Comment thread foca/utils/pagination.py Resolved
Comment thread docs/utilities.md Resolved
Comment thread docs/utilities.md Resolved
With several sort fields, items without a later one are compared by
the earlier ones first, so they are skipped only among items with the
same earlier values. Rewrap the paragraph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
uniqueg added a commit that referenced this pull request Nov 25, 2026
#826 is deferred out of 0.23.0: say in the migration guide that the
endpoints for managing roles and the permissions API still accept bare
users, which apply to nobody once an issuer namespaces its subjects.
Add #829 (#830) to the release notes.

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

Linked issues

Checked at commit 992ec71

#830 fix: refuse page tokens that aren't strings · 5 of 5 met

# Requirement Status Notes
1 Reject page tokens that are not strings as invalid-format ✅ Met PageKey.after() checks the token type and routes non-strings through the invalid-format error; the docs also say non-string tokens are invalid.
2 Refuse a string as the fields argument to PageKey ✅ Met PageKey validates that fields is a tuple of strings and raises ValueError otherwise; its API documentation describes this.
3 Document when find_page() raises ValueError ✅ Met The utilities docs explain the next-page case where the last item has no valid token, and refer readers to the API reference for errors caused by invalid helper arguments.
4 Document how items without sort fields sort ✅ Met The docs describe their null ordering for ascending and descending sorts and the resulting error or skipped items.
5 Document how to accept empty tokens from generated clients ✅ Met The docs give the suggested conversion: None if pageToken == "" else pageToken.

@uniqueg
uniqueg merged commit fc425f8 into dev Nov 25, 2026
58 checks passed
@uniqueg
uniqueg deleted the fix/page-token-checks branch November 25, 2026 16:32
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.

fix: refuse page tokens that aren't strings

1 participant