The user wants a design for a "Paginated API Correctness Checker." This is a system or tool that verifies if a paginated API behaves correctly, handling edge cases, cursor management, and ordering guarantees.
1. Deconstruct the Request:
- Core Task: Design a checker/validator for paginated APIs.
- Key Components:
- Edge cases (empty sets, single page, deletion during pagination).
- Cursors (offset vs. token-based/cursor-based).
- Ordering guarantees (consistency, missing data, duplicates).
- Goal: Provide a robust design, likely including architecture, test cases, and algorithms.
2. Initial Brainstorming & Categorization:
- Why is this hard? Pagination isn't just "get page 1, get page 2." It's about state. The underlying data can change while you are paginating. New items added, items deleted, sorting changing. This leads to the "missing item" or "duplicate item" problem.
- Types of Pagination:
- Offset/Limit: Simple but flawed with changing data.
- Cursor/Token: Better, requires specific logic (e.g.,
WHERE id > last_seen_id).
- Page Number: Generally discouraged for large datasets but common in UIs.
- The Checker's Role: It acts like a client but with assertions. It needs to be configurable to understand the specific API's schema and pagination style.
3. Structuring the Design:
A good technical design should cover:
- Architecture: How does the checker fit into the ecosystem?
- Core Logic/Algorithm: How do we actually check correctness? (The "Diff" strategy).
- Key Properties to Verify: What specifically are we testing?
- Edge Case Matrix: Specific scenarios.
- Implementation Details: Pseudo-code or flow.
4. Developing the Core Algorithm (The "Golden Master" approach):
- Idea: To check if paginated results are correct, we need to know what "correct" is.
- Approach: Fetch the entire dataset (or a controlled subset) via a non-paginated or differently paginated method (e.g., a "count" check or a massive limit if allowed) and compare it against the aggregated paginated results.
- Problem: What if the dataset is too huge?
- Solution: The checker needs to either work on a "hermetic" test environment where data is static and known, or it needs to use a statistical approach (sampling) or a "shadow traffic" approach.
- Refined Approach: Let's assume the context is a testing/staging environment.
- Seed Data: Generate a known dataset.
- The Walk: Paginate through the API.
- The Aggregate: Collect all items.
- The Comparison: Compare
Aggregated Items vs Seed Data (or a reference non-paginated call).
5. Deep Dive: Specific Problems to Check:
-
Ordering Guarantees:
- Are items strictly sorted?
- Are ties broken deterministically? (Crucial for cursor pagination). If two items have the same timestamp, which comes first? If the API sorts by
(timestamp, id), the cursor must capture both.
-
Cursors:
- Opacity: Is the cursor tamper-proof or valid?
- Staleness: What happens if a cursor from yesterday is used today?
- Invalidation: What happens if the filter changes mid-pagination?
-
Edge Cases:
- The "Shifting Window" (Offset-based): Item 0 is deleted while looking at page 1. Item 1 shifts to index 0. When fetching page 2 (start at 10), we missed Item 1. The checker must detect missing items.
- The "New Item" injection: A new item appears at the top. Everything shifts down. Duplicates appear.
- Empty/Nulls: Handling null fields in sorting.
6. Drafting the Design Document Structure:
- Title: Paginated API Correctness Checker Design.
- 1. High-Level Architecture:
- Inputs (Swagger/OpenAPI, Auth).
- Engine (The walker).
- Validator (The logic).
- 2. The "Diff" Algorithm (The heart of the solution):
- Strategy: Parallel verification. One "slow" full fetch (or known state) vs. the "fast" paginated fetch.
- Determinism check: Run twice, expect same result.
- 3. Verification Properties (The "What"):
- Integrity (No duplicates, no missing).
- Stability (Ordering).
- Boundary (Termination).
- 4. Handling Cursor Types:
- 5. Edge Case Scenarios (The "Test Suite"):
- Write-heavy simulation (Modifying data during pagination).
- 6. Implementation Pseudo-code.
7. Refining the Content (Self-Correction during drafting):
- Critique: Just saying "check for duplicates" isn't enough. How?
- Correction: Use a Hash Set. Add IDs. If
set.contains(id), fail.
- Critique: How do you check for missing items without knowing the full set?
- Correction: You can't effectively without a "Total Count" or a pre-known list. I must emphasize that this tool works best in a Test Environment with Known Data. Checking a live production API for correctness is extremely hard without a shadow copy. I will assume the target is a CI/CD environment.
- Refining the "Mutation" aspect: To test the "Live Modification" edge case, the checker needs to be an active participant. It shouldn't just read; it should occasionally insert/delete while paginating.
8. Final Polish:
- Use clear headings.
- Use diagrams (represented in text/mermaid).
- Write a sample test case definition.
(Self-Correction on "Ordering Guarantees"):
Most bugs in pagination come from non-deterministic sorting.
- Test: Sort by
createdAt.
- Scenario: Two items have identical
createdAt.
- Bug: Page 1 ends with Item A. Page 2 starts with Item A (again) or skips Item B because the DB sorted them differently on the second query.
- Checker Logic: Verify strict monotonicity of the cursor values. If the cursor value is the same as the previous item, the secondary sort key (ID) must be different.
9. Producing Output: (Proceeding to generate the detailed response following this structure.)
Designing a correctness checker for a paginated API requires moving beyond simple "happy path" testing. You need a stateful validator that can prove mathematical properties about the data stream (completeness, uniqueness, ordering) while simulating real-world race conditions.
Here is the design for Paginatrix, a specification-driven correctness checker.
1. High-Level Architecture
The system acts as a "Man-in-the-Middle" or a standalone test runner.
- Specifier: Defines the API schema (what fields act as the cursor, sort order, page size).
- Walker: Executes the pagination loop (fetch page → extract cursor → fetch next).
- Verifier: Applies assertions to the stream of data.
- Mutator (Chaos Engine): Modifies the underlying dataset during the walk to test consistency guarantees.
2. The Verification Model (The "Three Invariants")
To verify correctness, we must aggregate the stream and check three strict invariants:
A. The Uniqueness Invariant (No Duplicates)
Every item ID appearing in the paginated stream must be unique.
- Implementation: Use a Bloom Filter or a Hash Set.
- Check:
assert(item.id not in seen_items)
B. The Completeness Invariant (No Missing Items)
The total count of items received must match the total count available.
- Challenge: The "available" count changes in live environments.
- Solution: The checker runs against a frozen database snapshot or ensures the "Total-Count" header (if provided) matches the aggregated count.
C. The Monotonicity Invariant (Ordering Guarantees)
If sorting by created_at, then Itemn.timestamp≥Itemn−.
- Strictness: If the sort is non-unique (e.g., multiple items with the same timestamp), the API might "flip" their order between pages.
- Requirement: The checker enforces that the sort key is strictly non-decreasing.
3. Core Component Design
A. Cursor Strategy Parser
The checker needs to understand how the API creates the "bookmark" for the next page.
- Offset-Based (
offset=0, limit=10):
- Risk: If items are inserted at the top, the window shifts, causing duplicates. If items are deleted, the window shifts, causing skips.
- Checker Behavior: Expect "Eventual Consistency" failures. The checker allows the user to define a "tolerance" for duplicates/skips.
- Keyset/Cursor-Based (
last_seen_id=abc):
- Guarantee: Generally immune to insertion/deletion skew.
- Checker Behavior: Enforces Strict Consistency. No duplicates or skips are allowed.
- Encrypted/Opaque Cursor:
- Strategy: The checker treats this as a black box. It verifies that the cursor string changes with every request and that the returned data matches the opaque state.
B. The Walker Engine
The engine handles the request loop.
class PaginationWalker:
def walk(self, api_endpoint, strategy):
all_items = []
cursor = None
while True:
response = api.call(cursor)
items = response.items
# VERIFY: Empty Page Check
if not items and response.hasMore:
raise Error("Empty page but hasMore=True")
all_items.extend(items)
# VERIFY: Max Page Size
if len(items) > strategy.limit:
raise Error("Page size overflow")
if not response.hasMore:
break
cursor = response.nextCursor
# VERIFY: Cursor Progress
if cursor == previous_cursor:
raise Error("Cursor loop detected (same cursor returned)")
return all_items
4. Edge Case & Chaos Testing Matrix
This is where the checker provides the most value. It actively tries to break the API.
Case 1: The "Shifting Window" (Offset Pagination)
- Scenario: The walker requests Page 1. Before requesting Page 2, the Mutator inserts a new record at the top of the list.
- Expected Result (Offset): The walker will receive the last item of Page 1 again as the first item of Page 2 (Duplicate).
- Verdict: If using Offset, this is a Known Limitation. The checker logs it as a warning.
- Verdict: If using Cursor-based pagination, this is a FAIL.
Case 2: The "Deleted Page" (Gap in Sequence)
- Scenario: The walker fetches Page 1. The Mutator deletes the item that would be the first item of Page 2 (based on sort order).
- Offset Result: One item is skipped entirely (the item at the end of the new Page 2 shifts off the page).
- Cursor Result: The cursor points to a specific ID. If that ID is deleted, the API should handle it gracefully (usually by starting at the next available ID).
- Checker Logic: Ensure the API doesn't 404 or return an empty list prematurely.
Case 3: Non-Deterministic Sorting (The Tie-Breaker)
- Scenario: Sort by
status (e.g., "Pending"). There are 500 "Pending" items.
- Problem: Databases do not guarantee return order for identical values unless a secondary unique key (like
id) is used.
- Checker Logic:
- Request Page 1.
- Request Page 1 again.
- Assert: The order of items must be identical.
- Assert: If
status is the same for Item A and Item B, verify the API sorts by id (or another unique key) to break the tie.
Case 4: The "Last Page" Fencepost
- Scenario: Total items = 105. Page size = 10.
- Check:
- Page 10 returns 5 items.
hasMore or nextCursor must be null/false.
- Requesting Page 11 (or the final cursor) should return empty list and 200 OK (not 404).
5. Protocol Specification (YAML Example)
To make this reusable, we define a spec file that drives the checker.
pagination_spec:
type: cursor # or 'offset'
cursor_strategy:
input_param: "starting_after"
output_field: "data.next_cursor"
data_path: "data.items"
sorting:
default: "created_at"
direction: "desc"
unique_key: "id" # Required for strict monotonicity checks
correctness_contracts:
- no_duplicates: strict
- ordering: strict
- stability: yes # Re-running same query yields same order
chaos_tests:
- name: "Insert during pagination"
enabled: true
action: "INSERT"
position: "TOP"
6. Reporting Logic
The checker outputs a report classifying failures:
- Protocol Error:
hasMore=True but empty list; invalid cursor format.
- Data Integrity Error: Duplicate IDs found (ID
xyz appeared on Page 2 and Page 4).
- Ordering Violation: Item 10 has timestamp
10:00, Item 11 has timestamp 09:55.
- Stability Violation: Re-running the query resulted in a different sort order for items with identical sort keys.
Summary Checklist for Developers
If you are building this checker, ensure you implement these three functions:
- Validator:
check_monotonicity(stream)
- Validator:
check_uniqueness(stream)
- Chaos Monkey:
insert_data_during_walk() and delete_data_during_walk()