Ordering and pagination in a cached list: why equal values need a tie-breaker
A deterministic order cannot align pages from different generations: immutable DTOs in MySQL 8.4, scope, and an explicit restart after expiry.
A list contains two articles with the same publication time. Adding a unique ID to the sort makes the order deterministic. Yet a reader still encounters the same card on page two. The cache may explain why: page one came from an old collection, while page two was built after an insertion. Both SQL queries have a correct ORDER BY, but answer questions about different sets.
This article continues the subject of correct reading. The earlier pagination discussion already explains tie-breakers, OFFSET, keyset, insertions, and mutable keys. Here the promise is different: a reader should traverse an unchanged selected set even when new readers already begin with an updated collection. Cached pages need a generation identity and a defined availability boundary for that generation.
Deterministic order has a boundary
The teaching dataset uses this order:
SELECT id, published_at, title, revision
FROM article
ORDER BY published_at DESC, id DESC;
A timestamp is not a unique position. The second key breaks ties in the first; the schema makes ID unique and both keys non-null. Under those conditions, each row has an unambiguous place in a particular set. When all sorting expressions are equal, MySQL does not guarantee the relative order of those rows, including when selecting a page with LIMIT. The MySQL documentation on LIMIT and row order explains this behavior.
An unambiguous position does not make the set immutable. A new article can appear before those already read; editing a timestamp can move an existing article. Keyset defines continuation from a key but does not itself retain the entire previous state. That may suit a current feed. A frozen traversal requires a separate explicit decision.
Freeze a small counterexample
Use six synthetic rows. The first column is ID, the second is logical time; the page size is two. These are fixture values, not calendar dates or performance measurements.
| ID | Time |
|---|---|
| 91 | 500 |
| 90 | 500 |
| 80 | 400 |
| 70 | 300 |
| 60 | 200 |
| 50 | 100 |
Generation G1 has order 91,90,80,70,60,50. Its cached first page contains 91,90. Now insert row 100,600. The current G2 order is 100,91,90,80,70,60,50. If page two is obtained with OFFSET 2 from this new set, it contains 90,80.
Combining the old first page with the new second page repeats 90. The tie-breaker worked correctly: the failure crosses generations. In the executed experiment, this is a deliberate negative control. Removing the duplicate only in the interface would hide the symptom without restoring the promised sequence or missing records.
What a generation means here
A generation is the immutable result of one selection, rather than just the time of the last cache purge. Capture stores ordered DTOs: ID, time, selected title, and revision. G1 pages are then sliced only from those data. A new capture creates G2; it neither overwrites G1 nor changes an existing reader's reference.
Identity includes site, locale, filter, sort version, page size, and DTO version. A hash covers these dimensions and the selected rows. A page key adds the generation name and page number. The number page=2 alone, without that context, does not identify the cards the reader expects.
This is no requirement to freeze every list. A current feed may deliberately show a current title for an old ID or remove unavailable cards. That is a useful contract, but it needs a name. The exercise chooses a different result for comparison: immutable selected bytes during a bounded traversal.
A list of IDs does not retain a representation
Suppose G1 retained only identities. After capture, article 80's title changes. Loading current data by ID for page two would make G1 show the new text. Collection membership stayed old while its representation became mixed. That is insufficient for an immutable DTO agreement.
The editing case must therefore check both revision and selected title. G1 retains Card 80 and revision 1 for article 80. A new G2 contains Changed card and revision 2. Different hashes establish that the prepared sets differ; this is data identity, not a digital signature or evidence of authorization.
Retaining all HTML is not necessarily required either. Define the scope of the promise first. DTOs are stable in this example. A template, external image, or style can change separately. If the product promises an exact reproduction of the whole presentation, the contract must include the relevant versions and resource lifecycle.
An old version has a lifetime and permission to exist
The fixture retains a generation for 120 logical seconds after capture. It is available at 119 and returns restart_required at 120. A cached page cannot bypass that check. When G1 is missing, expired, or invalidated, the code does not silently substitute G2. The client must explicitly start a new traversal.
Reading a page again does not extend the generation's lifetime. Otherwise, an active reader could retain an outdated set indefinitely. Evicting a cached page does not require a new capture either: while the generation is available, the page can be sliced from the same snapshot again. These are distinct storage units with distinct meanings.
Access withdrawal is a separate boundary. A snapshot gives no right to continue displaying an article that must be hidden. In the teaching model, withdraw removes the source row and invalidates all generations that selected it. Current permission and availability are checked even before returning a cached page. This is a trusted decision fixture, not a complete authentication system.
An application snapshot and a database transaction
The independent teaching dataset is stored in MySQL 8.4 using InnoDB tables and native PDO MySQL. One SELECT obtains DTOs, after which the code stores immutable selected JSON bytes and the generation header in the database. Pages reread those bytes; the local page cache lives only within the process. No long transaction remains open between reader actions. The stored JSON bytes are an application snapshot, not an open InnoDB transaction. The InnoDB consistent-read documentation describes data visibility when reading within a transaction—a different guarantee.
An application snapshot used over several steps is not evidence of distributed snapshot isolation. If a real collection is assembled with multiple queries or services, a consistent capture point must be defined separately. One caller and sequential insertion do not test concurrent writers, replication, or atomicity between database and cache.
A page's context is part of its meaning
All source rows in the exercise already belong to one public site; locale demonstrates identity separation rather than a SQL translation join. In a real implementation, these conditions must apply during selection, rather than merely appearing in a key name. Otherwise, correctly partitioned storage will retain incorrectly selected data. Current permission must also come from the access owner, rather than an arbitrary client parameter.
Page size is deliberately included in scope. Changing it changes page-number boundaries even though the complete snapshot stays the same. The selected model rejects that continuation and asks for a new start. Another product could permit size changes using a position within the snapshot, but that would require a different navigation format. Do not silently combine these two promises in one page parameter.
For a bounded teaching set, retaining all DTOs is simple and transparent. The code allows at most one hundred rows and twenty items per page. A large collection requires assessment of capacity, retention, capture cost, and behavior when storage is lost. There are no measurements here that justify scaling this method. An available generation is a condition of a response; losing its data means an explicit restart, even if the source can still build a similar new collection.
What to check in one Demo
The additive code develops the same article_demo without creating another skeleton. A command demonstrates G1, insertion, the mixed second page, a DTO edit, G2, and refusal after expiry. Running it requires dependencies from the existing lock, the PDO MySQL extension, and MySQL 8.4. Run this teaching module's database-dependent commands through the guarded wrapper bash fixtures/mysql_labs/run.sh. The shared App\Infrastructure\MysqlLab prepares a disposable schema with a separate migrator before business transactions; the runtime connection performs DML only and has no CREATE, ALTER, or DROP privileges. MySQL DDL can implicitly commit, so this preparation is neither an atomic schema upgrade nor an automatic data migration from the old SQLite store. A separate check opens a new native connection to the same schema and reads the stored G1 DTOs; this does not test crash resilience or concurrent capture.
For the native MySQL 8.4 implementation, check the same vectors: G1 91,90 / 80,70 / 60,50 and G2 100,91 / 90,80 / 70,60 / 50. Each ID must occur once in its complete traversal. The mixed negative control produces 91,90,90,80: duplicate 90 is a deliberate cross-generation contract violation, not a tie-breaker failure. Also compare the exact selected JSON bytes and SHA-256 for both generations with a separate oracle: correct IDs are insufficient if a stored title or revision has changed. These checks concern data correctness, not performance.
Reading again through a new native connection to the same MySQL schema checks that G1 DTO bytes/hash/revision survive source changes; a new reader instance starts with an empty local page cache. Other checks cover a repeated-read cache hit and restart_required for a different scope, a missing generation, access denial, persisted withdrawal, and expiry at 120; the generation remains available at 119. Withdrawal is checked before expiry, while expiry uses its own independent 0/119/120 timeline. Reversing insertion order must not change the selected order, and overwriting an existing generation must be rejected. This scenario is bounded to one caller, up to 100 rows and 20 items/page; reconnecting does not establish crash resilience, concurrent capture, or distributed isolation.
The report needs exact page IDs, each ID's multiplicity, DTO hashes, revisions, the context key, and whether a page came from cache or snapshot. Comparing only card counts is insufficient: different sets can have the same size. Likewise, a successful HTTP status without membership checks does not establish correct traversal.
An empty final page must also belong to the requested generation. It ends that particular set rather than automatically switching to new publications. To see new content, the client starts another traversal. Navigation then keeps the same meaning throughout reading. Retain this case in the report too: empty items in an available generation differ from restart_required. The first response finishes the reader’s path; the second says that the previous promise of continuation can no longer be fulfilled.
Before capture, the exact scope keys, types, allowed values, and integer page_size from 1 to 20 are validated; the same validation applies when loading a stored generation. An invalid scope writes no generation. Withdrawal deletes the source row and invalidates affected generations in one InnoDB transaction owned by the operation. An active caller transaction is rejected before mutation: the example does not commit or roll it back. To test failure, the fixture migrator installs a MySQL trigger using SIGNAL SQLSTATE '45000' beforehand; the runtime operation performs DML only. The error propagates after rollback of the owned transaction, and assertions require the row and valid generation to remain unchanged. Do not assume that every MySQL error automatically rolls back the whole transaction: the outcome depends on the error, as the InnoDB error-handling documentation explains. This verifies a sequential scenario, not a crash or concurrency guarantee.
The practical decision begins with the promise to the reader. A live feed may accept a changing set and explain continuation. Stable browsing needs immutable data, a defined context, and explicit expiry. A tie-breaker establishes order within a set; a generation explains which set each cached page belongs to.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
Check the current example against an owned disposable MySQL schema:
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/ListGeneration