This post is about a race that I think hides in a lot of apps that load a long list in pages, which I ran into while trying to make a small change cheaper. The app is a reading app I'm building in SwiftUI with The Composable Architecture (TCA), with the library stored in Core Data. The idea itself applies to any reducer or store that receives a list in chunks, with one requirement about cancelling old loads that I'll get to below.
The change that started it
When a book joined or left a bundle (a group of books shown together), the library reloaded everything, which meant every page of books, the bundles and the suggestions, just so one row could show its new bundle in a context menu. The obvious improvement is to refresh only the touched rows, and the app already had a narrow refetch for that, which fetches a few rows by id and patches them into the list.
Before switching to it, I checked whether a page of a full load that is already in flight can overwrite a row the narrow refetch just patched. It can, and the reason is in how the reducer handled pages:
case let .pageLoaded(page, isFirstPage): if isFirstPage { state.rows = page } else { state.rows.append(contentsOf: page) } A page is read from the store, travels through an effect, and lands in the reducer some time later. If the first page was read before the patch and lands after it, state.rows = page puts the old row back. If a later page carries the patched row, append adds a stale copy beside the fresh one, and the patch code, which keeps one index per id, only ever updates one of the two copies. Nothing heals it until the next full load.
It wasn't one writer
At first I treated it as a race in the narrow refetch, but listing everything that writes to that row list turned up six writers. They are the narrow refetch, a delete, a metadata edit, a single-book refresh, a reading progress refresh and a privacy re-stamp that marks rows as hidden (books can be protected, and a protected book must never show in the list without unlocking). All six had the same exposure, and the narrow refetch was just the one I was about to rely on more. The privacy one is the bad one, since an old page landing after a re-stamp could show a row that had just been hidden.
So the fix had to be about the load, not about any single writer.
There are a few other ways to get there, and each fits some apps better. If every row carried a version or a modified-at stamp from the store, we could keep whichever copy is newer when a page lands, but here only the reading progress has a timestamp, protection is computed rather than stored, and a delete would need tombstones to win a comparison. Cancelling and restarting the load on every write is simpler, but progress refreshes happen often enough that a long load might never finish. Remembering the ids written during the load and refetching them once it completes works too, at the cost of the stale row being visible until the load ends, which for the protected rows is exactly what we don't want.
A write log that lives only while a load runs
What I ended up with is a log of row writes, which exists only while a full load is in flight. The load starts it empty, and every writer appends to it while it exists. Each page, when it lands, is applied first, and then the whole log is replayed over it. When the load completes or fails the log is dropped. The code below is simplified from the app's, with the names made generic.
enum RowWrite: Equatable, Sendable { case replace(BookRow) // a narrow refetch or a single-book refresh case remove(Set<UUID>) // a delete, or a refetch that found the row gone case progress(bookId: UUID, progress: Double, updatedAt: Date?) case protection(protectedIds: Set<UUID>) } // in State var writesDuringLoad: [RowWrite]? // nil while no load is in flight Each writer keeps doing what it did, and we add a line that logs what it changed:
case let .progressRefreshed(bookId, progress, updatedAt): // ...update state.rows as before... state.writesDuringLoad?.append( .progress(bookId: bookId, progress: progress, updatedAt: updatedAt) ) The optional chaining does the "only while a load runs" part for free, since with no load the log is nil and the append does nothing. If a writer needs a row from the list for its log entry, copy it into a local first, because state.writesDuringLoad?.append(.replace(state.rows[index])) didn't compile for me. With TCA's @ObservableState the fields are computed properties, so each access counts as an access to the whole state, and the ?. opens the append's write access before state.rows[index] is read, which overlaps the two (on a plain struct with stored properties the same line compiles fine).
The writers in the app log after the store write has committed, which matters here. The load resets the log when it starts, so anything written before that has to already be in the store for the pages to carry it. If you have an optimistic writer that patches the list before its store write lands, it needs its own pending set.
The page handling changes in two ways. A later page is upserted by id instead of appended, so a row that a write already put in place isn't listed twice, and both branches replay the log after applying the page:
case let .pageLoaded(page, isFirstPage): if isFirstPage { state.rows = page } else { upsertById(&state.rows, page) // replace the row with the same id, or append } RowWrite.replay(state.writesDuringLoad ?? [], over: &state.rows) We want upsertById to look rows up through an id index (or use TCA's IdentifiedArray), since a linear search per row over a growing list adds up to a lot of comparisons on the main thread for a big library.
We also can't consume the log after a page. A progress or protection write for a book whose page hasn't landed yet finds no row and does nothing, and it only takes effect when the replay runs again after that book's page arrives, so the whole log is replayed every time.
Replaying, and why protection only goes up
Let's look at the replay, also simplified:
static func replay(_ writes: [RowWrite], over rows: inout [BookRow]) { var indexById = Dictionary(uniqueKeysWithValues: rows.enumerated().map { ($1.id, $0) }) for write in writes { switch write { case let .replace(written): if let index = indexById[written.id] { var merged = written merged.isProtected = rows[index].isProtected || written.isProtected rows[index] = merged } else { indexById[written.id] = rows.count rows.append(written) } case let .remove(ids): rows.removeAll { ids.contains($0.id) } indexById = Dictionary(uniqueKeysWithValues: rows.enumerated().map { ($1.id, $0) }) case let .progress(bookId, progress, updatedAt): guard let index = indexById[bookId] else { continue } rows[index].progress = progress rows[index].updatedAt = updatedAt case let .protection(protectedIds): for index in rows.indices where protectedIds.contains(rows[index].id) { rows[index].isProtected = true } } } } The index has to be kept up to date inside the loop, since an append that isn't added to it turns two writes for the same book into two rows, and a remove shifts every index after it.
Replaying in order is right for every page read before a write, because the write is newer than those pages. The log is per load though, not per page, so a write made after the load started but before a later page was read is older than that page, and gets replayed over it anyway. Most of the time that's the same data, but a progress write can roll back newer progress the page brought in from somewhere else, until the next write to that row or the next full load. To make it exact, each page would need to carry the time it was read, compared against when each writer read its own data, and per load was good enough for this app.
That ordering gap is also why protection is only ever raised on replay. A replayed write can carry a protected bit that's older than the page's, and replaying an old "this row is not protected" over a newer page could show a row that should be hidden. So a replace keeps the page's protected bit if either side has it, and the protection write only sets rows to protected. That leans towards hiding a row that should be visible, which is the safe direction, and to settle those rows, a load that replayed any writes asks for one protection re-resolve over the finished list when it completes. A load with an empty log skips it.
Cancelling the old load
All of this assumes that when a new load starts, nothing from the old one reaches the reducer anymore. Say load A is running and a write is logged, then load B starts and resets the log to empty. If one of A's pages lands now, it's applied with nothing to replay, and the write is lost. If A's completion lands, it drops B's log, and writes during the rest of B aren't logged at all. In TCA the load effect is .cancellable(id:cancelInFlight: true), and a cancelled effect's sends are dropped, so A goes away cleanly. In a store without that, you'd tag each page and completion with a load id and ignore the ones that don't match the current load. We also have to drop the log when a load is cancelled without a new one starting, otherwise it stays open and keeps growing with no load to read it.
Each writer has to log only what it wrote
A review of the change found a bug in what one writer logged. The metadata edit logged a whole row with .replace, but an edit only changes the book's details and keeps whatever progress the row had. For a book whose row wasn't loaded yet, the edit built a placeholder row with zero progress, and for a loaded row it carried the progress it saw at the time of the edit. Replayed over a page that brought the real, newer progress, either one wiped it. Before the log, that placeholder was dropped by a first page or left beside the real row by a later one, so the log turned a duplicate into lost progress. The right write for an edit carries only the book (.book(Book)) and keeps the page's progress, date and protection, adding the placeholder only when the row is missing.
The same thing applies to any other list that gets "collect all pages, then swap once" to avoid flicker. Every page in that single swap is older than any write made during the read, so writes to that list need the same log and replay, or the swap will undo them.
Summary
If a list loads in pages and anything else writes single rows into it, the pages are always older than they look by the time they land, and "refresh just the row" loses to whatever full load is running. A log of row writes kept only for the duration of the load, replayed over every page, fixes it, as long as later pages are merged by id instead of appended and an old load can't deliver anything after a new one starts. Privacy-related state should only ever tighten on replay, with one re-check at the end. What goes into the log is the easiest thing to get wrong, since each writer has to log exactly the fields it changed, and a writer that logs a whole row it partly made up will overwrite the fresh data the page brought.