Test iOS SQLite keyset pagination on a cloud Mac
A colleague in Asia-Pacific has just finished the first page when a batch of new records arrives from the other end. Suddenly, the next page contains duplicates—or skips a record. For iOS data-layer tests running long-term on a cloud Mac, repeatedly scrolling through a list and hoping to reproduce the issue is not a useful strategy. Fix the data order and the timing of changes so you can tell whether the query is wrong or the product simply has no defined consistency boundary.
Define the list’s ordering contract first
This article tests a local SQLite list, not network pagination. The contract is created_at DESC, id DESC, with three records per page. Timestamps are integers, IDs are unique and immutable, and neither field allows nulls. When timestamps tie, the ID determines the order; never rely on whatever order the database happens to return.
The cursor stores both fields from the last record on the previous page. For a descending list, the next page uses a strict less-than comparison—not less-than-or-equal, and not a timestamp-only comparison. Filtering only by timestamp would also skip records with that timestamp that have not yet been returned.
A cursor represents an ordering boundary, not “how many records have been read.” It does not automatically represent a database snapshot, either.
This approach suits record lists browsed in a stable creation order. If users can change the sorting weight at any time, define the refresh strategy before reusing the pagination code.
Run an executable fixture in a separate database
Once the command-line developer tools are installed on the cloud Mac, run xcrun --find swift and sqlite3 --version to record the environment. Run the entire script below in a terminal. The temporary database does not touch project data, and a failed assertion makes the command exit with a nonzero status.
set -eu
db="$(mktemp -t cursor-fixture)"
trap 'rm -f "$db"' EXIT
sqlite3 "$db" <<'SQL'
.bail on
CREATE TABLE entries (
id INTEGER PRIMARY KEY,
created_at INTEGER NOT NULL
);
CREATE INDEX entries_page
ON entries(created_at DESC, id DESC);
INSERT INTO entries VALUES
(101,10),(102,10),(103,20),
(104,20),(105,30),(106,30);
CREATE TEMP TABLE checks (
ok INTEGER NOT NULL CHECK(ok = 1)
);
INSERT INTO checks
SELECT (
SELECT group_concat(id, ',')
FROM (
SELECT id FROM entries
ORDER BY created_at DESC, id DESC
LIMIT 3
)
) = '106,105,104';
INSERT INTO entries VALUES (107,40);
INSERT INTO checks
SELECT (
SELECT group_concat(id, ',')
FROM (
SELECT id FROM entries
WHERE (created_at, id) < (20,104)
ORDER BY created_at DESC, id DESC
LIMIT 3
)
) = '103,102,101';
SELECT 'cursor checks passed';
SQL
The first page ends at (20,104). After a new record is inserted ahead of it, the second page should still return 103,102,101. The input to the aggregate is placed in an ordered subquery so that the assertion itself does not depend on an unspecified order.
The command-line test verifies the SQL contract. When integrating it into the app, run the same dataset in the iOS test target as well: the device’s SQLite runtime version and database wrapper may differ.
Replace hard-coded values with bound parameters
Keep two queries in the data layer: one without a cursor condition for the first page, and one with a composite boundary for subsequent pages. Do not implement the first page using an arbitrarily chosen “maximum timestamp,” because valid data could fall outside that boundary.
SELECT id, created_at
FROM entries
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT ?;
Bind the previous page’s timestamp, ID, and page size, in that order. Use integer binding APIs for the timestamp and ID. Validate the page size in the application layer first, ensuring it is positive and has an upper limit. Do not convert values to strings and concatenate them into SQL. Generate the cursor only from the last row actually returned, never from the time the request was initiated.
An empty page means there are no records beyond the current query boundary. If a page contains fewer records than requested, you can end the current loading cycle. The next explicit refresh should request the first page again, rather than modify the old cursor to keep searching for new records.
Test inserts, deletes, and updates separately
Start each case from the original six records, fetch the first page, and then apply one change. Do not chain all the operations together: a later operation could hide an earlier failure.
- Insert
(107,40)ahead of the cursor: the next page remains103,102,101. The new record appears when the first page is refreshed. - Delete the already-read record
105: the next page stays unchanged. Offset-based implementations are prone to skipping a record here. - Delete the unread record
103: the next page should be102,101. It must not return previously read rows just to fill a three-record page. - Delete the cursor row
104: the boundary values remain valid. There is no need to check whether that row still exists. - Change the timestamp of unread row
103to50: it moves ahead of the cursor and will not appear on subsequent pages in this loading cycle.
The last case does not mean the composite comparison has failed. It reflects a live list that allows sort fields to change. If the business requirement is to include the same set of records throughout a browsing session, fix the result IDs or complete the reads within a controlled read transaction. Do not keep a transaction open for pagination spanning multiple user actions; long-running read transactions can also delay database checkpoint progress.
Finish with an index check and a regression record
Run EXPLAIN QUERY PLAN on the pagination query and confirm that a composite index matching the sort fields has been created. Query-plan wording changes between SQLite versions, so do not turn the entire output into an exact-string assertion. Maintain behavioral assertions separately from query-plan reviews.
When submitting the regression record, save the table-creation statement, initial data, first-page result, cursor, mutation, second-page result, and runtime version. Add cases for an empty table, a single record, a full page of identical timestamps, and consecutive page requests through to the end. Check for duplicate returned IDs and verify that the full static dataset is returned without omissions.
When teammates in another region take over, have them run this small fixture before the application tests. The discussion then shifts from “I sometimes see duplicates here” to explicit rules for ordering, boundaries, and mutations. Live refreshes and consistent snapshots no longer get treated as the same promise.
Frequently asked questions
Can a cursor contain only the creation timestamp?
Not when timestamps can tie. Add a unique, stable ID to both the ordering and the cursor, and use a comparison direction that matches the sort order.
Does keyset pagination guarantee a consistent snapshot?
No. It avoids position shifts caused by inserts or deletes before the cursor, but changes to ordering fields can still move rows across it. Use a controlled read transaction or a materialized result set when snapshot consistency is required.
Get a dedicated Mac mini for your project
A whole machine, dedicated to one customer—ideal for remote development, automated builds, and always-on workloads. Rent by the day for short-term projects, then choose the term that works for you.