Skip to content

Keep an empty-string keyset pagination cursor - #2968

Open
feiiiiii5 wants to merge 7 commits into
simonw:mainfrom
feiiiiii5:fix/next-token-empty-pk
Open

feiiiiii5 wants to merge 7 commits into
simonw:mainfrom
feiiiiii5:fix/next-token-empty-pk

Conversation

@feiiiiii5

Copy link
Copy Markdown
Contributor

Closes #2967, which has the longer write-up.

The defect in one place

path_from_row_pks() returns "" for a row whose only primary key value is the empty string, and "" is a legitimate _next= cursor. Both the site that emits the token and the site that reads it back test it for truthiness instead of identity:

# emit
"next": next_value and str(next_value) or None,        # "" and "" or None  ->  None

# read back
_next = _next or request.args.get("_next")
if _next:                                              # "" is falsy -> cursor ignored

None is the no-cursor sentinel — initialised to None at table.py:2508, and nothing ever assigns "" to it deliberately.

The result

CREATE TABLE t (id TEXT PRIMARY KEY);
INSERT INTO t (id) VALUES ('a'), (''), ('c'), ('d'), ('e');
/d/t.json?_size=1  ->  rows ['']   next=None   next_url=/d/t.json?_size=1&_next=
following that     ->  rows ['']   next=None   next_url=/d/t.json?_size=1&_next=
following that     ->  rows ['']   ...        never reaches 'a'

A client that follows next_url loops on the first page. With the fix it walks '', a, c, d, e once each and the last page has both keys null.

Two things made this a contract violation rather than a curiosity:

  • docs/json_api.rst:99 says "next" and "next_url" are both null on the final page. Here next is null while next_url is not.
  • tests/test_table_api.py:333 already asserts the two agree — urlencode({"_next": response.json()["next"]}) in path — and fails with assert '_next=None' in '...&_next='. It passes today only because every stock fixture has non-empty primary keys.

The same function already asks this question correctly at table.py:2536 (if prefix is None: prefix = "$null"), and row_label_from_label_column at table.py:287 uses if value is None or value == "".

Behaviour change worth naming

A bare ?_next= with no value now means "rows after the empty primary key" instead of being ignored and returning page 1. That is the only coherent reading of an empty cursor, but it is a change. _next=a and _next=zzz behave exactly as before.

Testing

tests/test_table_api.py::test_paginate_table_with_empty_string_primary_key walks the pages via next_url, checks next_url and next agree on every non-final page, asserts all five rows come back exactly once, and asserts the final page has both keys null. It fails on cec5e6b2 with the _next=None / _next= assertion above.

  • pytest -n auto -m "not serial" — 2782 passed, 54 skipped, 6 xfailed, 15 xpassed, 143 subtests
  • pytest -m serial — 40 passed
  • black --check ., ruff check datasette tests, cog --check docs/*.rst, codespell — clean

The judgement call I left to you

This needs a table whose single text primary key holds ''. Legal SQLite, and nothing in Datasette rejects it, but I could not find a path there that does not involve importing a CSV with an empty key — so it may be rare enough that you would rather not carry the change. What convinced me it is a bug is the contradiction with the documented JSON contract, which holds whatever the input.

No documentation change: json_api.rst already describes the fixed behaviour, the code was the thing that disagreed.

path_from_row_pks() returns "" for a row whose only primary key value is
the empty string, and "" is a legitimate _next= cursor. Both the site
that emits the token and the site that reads it back tested it for
truthiness, so the token was discarded.

Emitting:

    "next": next_value and str(next_value) or None

turns "" into None, while next_url is still built a few lines earlier
and stays non-null. docs/json_api.rst:99 says both are null on the final
page, so the response contradicted its own documentation. Reading back,
"if _next:" then ignored the cursor and the query returned page 1
again, so a client following next_url looped on the first row forever.

    CREATE TABLE t (id TEXT PRIMARY KEY);
    INSERT INTO t (id) VALUES ('a'), (''), ('c'), ('d'), 'e');

    /d/t.json?_size=1   rows ['']   next=None   next_url=...&_next=
    following it       rows ['']   next=None   next_url=...&_next=

None is the no-cursor sentinel: it is initialised to None at
table.py:2508 and nothing assigns "" to it deliberately. The same
function already asks this correctly at table.py:2536
("if prefix is None: prefix = '\'").

A bare ?_next= with no value now means "rows after the empty primary
key" rather than being ignored, which is the only coherent reading of
an empty cursor. _next=a and _next=zzz are unchanged.

No docs change: json_api.rst already describes the fixed behaviour.

Test: tests/test_table_api.py::test_paginate_table_with_empty_string_primary_key
walks the pages and fails on cec5e6b with

    assert '_next=None' in '...?_size=1&_next='

pytest -n auto -m 'not serial' 2782 passed, pytest -m serial 40 passed.
black, ruff, cog --check and codespell clean.
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Hi @simonw — #2968 has been open since 28 September with the docs build green and no feedback yet, so this is the one nudge I planned.

Recap: path_from_row_pks() returns "" for a row whose only primary-key value is the empty string, but both the site that emits _next (next_value and str(next_value) or None) and the site that reads it back (if _next:) test it for truthiness, so a client following next_url loops on the first page forever. The fix keeps "" as a real cursor, which also makes next and next_url agree on the final page as docs/json_api.rst:99 requires (and tests/test_table_api.py:333 already asserts).

One thing I checked rather than assumed: table.py:2536 already distinguishes None from "" for the $null prefix, so None remains the only no-cursor sentinel in the emit path — no other keyset caller depends on "" meaning "absent".

Is there anything you'd like changed before this can go in?

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Hi @simonw — two small pagination fixes for Datasette have been green and conflict-free for a few weeks:

Both have regression tests, and the checks pass. Could you take a look when you have a moment? Happy to adjust anything.

@Muguett-DBY Muguett-DBY left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could the empty-cursor handling distinguish views from tables? Views use _next as an integer offset, so the new if _next is not None also sends an empty string into int(_next). With a view v AS SELECT id FROM items, GET /check/v.json?_size=1&_next= returns the first page on the base, but returns 500 (ValueError: invalid literal for int() with base 10: '') on this head. The same empty cursor on the table advances past the empty primary key as intended.

Perhaps a view could continue treating an empty offset as the first page, with a regression test for that route. I checked actual HTTP responses using the exact base and PR table_view_data functions, with the remaining Datasette code from b4c280c on Windows/Python 3.12; I have not built or run the full suite at this PR head.

The empty-string cursor change made `if _next is not None` apply to
views as well. Views paginate by integer offset, and their first page
arrives as `?_next=`, so `int("")` raised ValueError and returned 500.
An empty cursor now stays "no cursor" for views, while a table still
reads it as a real cursor for an empty primary key.

Refs simonw#2967, simonw#2968

Test: tests/test_table_api.py::test_view_ignores_an_empty_next_cursor
returns 500 before this change and passes after it. The same test
passes against origin/main's table.py, so this restores base behaviour.
tests/test_table_api.py: 129 passed, 8 xpassed; tests/test_html.py -k
view: 6 passed; black and ruff check clean.
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Good catch — confirmed on the branch. GET /view_db/v.json?_size=1&_next= reaches int("") at table.py:2150 and returns 500, while a8e13cc4 (actual base) serves the first page.

Fixed in f7c7dac9: an empty _next stays "no cursor" when the object is a view, while a table still reads it as a real cursor for an empty primary key.

tests/test_table_api.py::test_view_ignores_an_empty_next_cursor covers ?_next= (first page) and ?_next=1 (second page). It fails with the ValueError before the change, passes after, and passes against origin/main's table.py, so the PR no longer changes view behaviour.

Validation: tests/test_table_api.py 129 passed, 8 xpassed; tests/test_html.py -k view 6 passed; black --check and ruff check clean.

@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 0.00%. Comparing base (ea03655) to head (3133904).

Files with missing lines Patch % Lines
datasette/views/table.py 0.00% 6 Missing ⚠️
Additional details and impacted files
@@          Coverage Diff          @@
##            main   #2968   +/-   ##
=====================================
  Coverage   0.00%   0.00%           
=====================================
  Files         79      79           
  Lines      13978   13980    +2     
=====================================
- Misses     13978   13980    +2     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
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.

next token dropped when a row's only primary key value is the empty string

2 participants