Product case study · November 23, 2026

Ask Claude Code to fix SQLite pagination that skips tied rows

Reproduce a SQLite cursor bug with tied timestamps, ask Claude Code for a bounded repair, and verify every row appears exactly once in a fixed dataset.

Reading time
7 min
Checked
Nov 23, 2026
Paper cards pass through a divider into two trays, with paired blue and ochre markers preserving their sequence.
Carry both sort values across the page boundary.
Bottom line

A page cursor must remember the unique tie-breaker as well as the timestamp.

Your activity feed shows two events, then jumps to the next timestamp. A third event has vanished from the feed even though it is still in the database. The first page looks correct; the bug lives in the instruction for where page two starts.

This lab asks Claude Code to repair that boundary. You will give it a fixed dataset with tied timestamps and tests that check the entire traversal, rather than accepting a plausible first page.

You need Bash on Linux, macOS or WSL, Python 3 with SQLite 3.15.0 or newer, and an installed, signed-in Claude Code. The Python baseline and reference repair were tested locally; the agent prompt is an authored exercise, not a recorded Claude run. Official sources were checked November 23, 2026.

Build a feed that drops one event

Create an empty practice directory:

pagination_lab=$(mktemp -d /tmp/claude-pagination.XXXXXX)
cd "$pagination_lab"
python3 -c 'import sys, sqlite3; print(sys.version); print(sqlite3.sqlite_version)'

Save this as feed.py:

def page(con, after=None, size=2):
    if size < 1:
        raise ValueError("size must be positive")
    if after is None:
        return con.execute(
            "SELECT created_at, id FROM events "
            "ORDER BY created_at, id LIMIT ?", (size,)
        ).fetchall()
    return con.execute(
        "SELECT created_at, id FROM events WHERE created_at > ? "
        "ORDER BY created_at, id LIMIT ?", (after[0], size)
    ).fetchall()

The cursor is the last returned pair, (created_at, id). The first query sorts by both values, but the next-page query uses only the timestamp. It discards every remaining row with that same timestamp.

Save this as test_feed.py:

import sqlite3
import unittest
from feed import page


class PaginationTests(unittest.TestCase):
    def setUp(self):
        self.con = sqlite3.connect(":memory:")
        self.addCleanup(self.con.close)
        self.con.execute(
            "CREATE TABLE events(id INTEGER PRIMARY KEY, "
            "created_at INTEGER NOT NULL)"
        )
        # Synthetic integer times; IDs deliberately differ from time order.
        self.con.executemany(
            "INSERT INTO events(id, created_at) VALUES (?, ?)",
            [(9, 100), (2, 100), (7, 100), (1, 101), (8, 102)],
        )
        self.expected = [(100, 2), (100, 7), (100, 9), (101, 1), (102, 8)]

    def test_first_page(self):
        self.assertEqual(page(self.con), self.expected[:2])

    def test_resume_inside_tie(self):
        self.assertEqual(
            page(self.con, after=(100, 7)), [(100, 9), (101, 1)]
        )

    def test_complete_traversal(self):
        for size in (1, 2, 3, 4, 8):
            with self.subTest(size=size):
                seen, after = [], None
                # Bound the loop so a repeated cursor cannot hang the test.
                for _ in range(len(self.expected) + 1):
                    batch = page(self.con, after=after, size=size)
                    if not batch:
                        break
                    self.assertLessEqual(len(batch), size)
                    seen.extend(batch)
                    after = batch[-1]
                else:
                    self.fail("pagination never reached an empty page")
                self.assertEqual(seen, self.expected)

    def test_empty_end_and_invalid_size(self):
        self.assertEqual(page(self.con, after=self.expected[-1]), [])
        for size in (0, -1):
            with self.assertRaises(ValueError):
                page(self.con, size=size)

Run:

python3 -m unittest -v test_feed

The local baseline failed the resume test and the traversal subtests for sizes 1 and 2. The other cases passed. At size 3, all three tied rows happen to fit on the first page, concealing the defect. A test that checks only that page would give the agent the wrong definition of success.

Ask Claude Code to repair the boundary

Start claude in this directory. If needed, follow the first project session lesson for setup and permission review.

Paste this brief:

Read feed.py and test_feed.py. Run python3 -m unittest -v test_feed
and report which cases fail before changing anything.
Repair only page() in feed.py. Keep ascending (created_at, id) order,
the two-value cursor format, positive-size validation and SQL placeholders.
Return at most size rows per query. Resume strictly after both cursor values.
Do not change tests, the fixture, schema, or function signature. Do not
fetch the entire table and slice it in Python or replace this with OFFSET.
Use only the standard library. Do not install packages, access other
folders or databases, commit files, or delegate.
Rerun the unchanged tests and explain why a timestamp-only cursor loses rows.

Anthropic’s best-practices guide recommends giving Claude a check it can run. Here the check includes the inconvenient input: several rows at the same time, split by a page boundary. Review proposed tool actions; the brief itself does not enforce a filesystem sandbox.

Review the two-value comparison

A reference repair for feed.py is:

def page(con, after=None, size=2):
    if size < 1:
        raise ValueError("size must be positive")
    if after is None:
        return con.execute(
            "SELECT created_at, id FROM events "
            "ORDER BY created_at, id LIMIT ?", (size,)
        ).fetchall()
    return con.execute(
        "SELECT created_at, id FROM events "
        "WHERE (created_at, id) > (?, ?) "
        "ORDER BY created_at, id LIMIT ?",
        (after[0], after[1], size),
    ).fetchall()

SQLite’s row-value documentation describes left-to-right comparison and its use for scrolling queries. After (100, 7), the pair (100, 9) belongs on the next page because its timestamp ties and its ID is larger. (101, 1) also follows because its timestamp is larger, even though its ID is smaller.

Keep id in ORDER BY too. SQLite’s SELECT reference says rows tied on every ordering expression have an undefined relative order. The unique primary key removes that ambiguity in this fixture. Keep values in placeholders, as documented in Python’s sqlite3 guide.

Run the same test command yourself. The reference repair passed all four test methods locally, including every page-size subtest. At size 2 the repaired pages are:

[(100, 2), (100, 7)]
[(100, 9), (101, 1)]
[(102, 8)]
[]

Compare the agent’s diff with the contract before accepting it. An exact sequence comparison catches omissions, duplicates and wrong ordering. Checking only the total row count would miss some combinations of those errors.

Recover from misleading fixes

Proposed fix or symptomWhat to check
Change > to >= for the timestampThis includes earlier tied rows again; the traversal test catches repeats or a loop.
Filter only by id > ?IDs do not follow time order here. Event 1 comes after event 9.
Add the ID to the cursor but leave it out of the queryBoth cursor fields must participate in the boundary.
Make the page largerSize 3 already hides this fixture’s defect. Keep the size 1 and 2 checks.
Syntax error near the tuple comparisonCheck the linked SQLite version printed at setup; row values require 3.15.0 or newer.

This exercise assumes a fixed dataset, non-null integer times, unique IDs and ascending order. It does not prove a consistent snapshot while another connection inserts, deletes or changes sort values. For a live export, define snapshot and update behavior separately before asking the agent to extend this query. Descending or mixed-direction sorts also need their own boundary tests.

On a larger database, evaluate a composite index matching the sort columns and inspect the query plan. This five-row correctness lab makes no speed claim and does not benchmark an index. Its deliverable is narrower: every expected row appears exactly once in the correct order while the dataset stays fixed.

Sources and verification

Checked November 23, 2026:

Local testing covers the published Python fixture and reference repair. It does not measure a Claude model’s reliability or validate production concurrency behavior.

Put this to work

How a composite cursor keeps the WHERE boundary aligned with the ORDER BY clause.

Try

Build a disposable five-row SQLite event feed using Python's standard library.

Prove it worked

Run four unchanged tests before and after the repair; compare exact row sequences.

Keep in view

  • Reproduce missing records when several events share a timestamp.
  • Give Claude Code unchanged tests and a narrow query repair boundary.
  • Verify complete traversal at several page sizes, including ties across pages.
Learn the workflow: Start a scoped Claude Code project session