Skip to main content
coreydaley.dev

Why my progress bar went backwards: atomic counters aren't ordered delivery

A test called “Parallel-ZIP coalesced progress: monotonic and lands at total” failed about one run in five. It checked that while Purrchiver compresses a ZIP across several cores, the byte count reported to the progress bar never goes down and ends at the total. Sometimes the count went down. A real progress bar would have ticked back a little, then carried on.

The counter itself was correct the whole time. That’s what made it worth writing up.

The setup

Purrchiver makes ZIPs in parallel by splitting the input files into groups (“shards”), compressing each shard as its own archive at the same time, and stitching the results together. Every shard reports bytes as it goes, and they all report into one shared progress sink:

final class ProgressSink: Sendable {
    private let state = OSAllocatedUnfairLock(initialState: State())
    private let emit: @Sendable (Progress) -> Void

    func addBytes(_ n: Int64) {
        let snapshot = state.withLock { s in
            s.bytesProcessed += n
            return Progress(bytesProcessed: s.bytesProcessed)
        }
        emit(snapshot)   // outside the lock
    }
}

The increment is under a lock, so no update is lost and every snapshot is a true count at the moment it was taken. Calling emit outside the lock is deliberate. You don’t want to hold a lock across a callback you don’t control.

What actually happens

Two shards call addBytes at almost the same time:

  1. Shard A takes the lock, bumps the count to 100 MB, builds a snapshot of 100, and releases the lock.
  2. Shard B takes the lock, bumps it to 108 MB, builds a snapshot of 108, and releases.
  3. Shard B calls emit(108).
  4. Shard A, which was descheduled for a moment after leaving the lock, calls emit(100).

Both snapshots were correct when they were taken. They were delivered in the wrong order. The lock makes the count atomic. It says nothing about the order in which the threads holding those results get to the next line of code.

How it surfaced

A few days earlier I’d made the hot path cheaper. Each shard’s writer reports roughly every megabyte, and with several shards all contending for the sink’s lock, that lock was busy. So each shard got its own private counter and only flushed to the shared sink every 8 MiB, plus whatever was left at the end. That cut contended lock acquisitions about eightfold.

The monotonic test came in with that change, to prove the batching didn’t corrupt the byte count. It didn’t. The emit-outside-the-lock ordering was already there, and the new test was the first thing that looked for it. Bigger, less frequent flushes probably made each reordering easier to see, since two shards flushing at once now produce snapshots megabytes apart.

The fix: a separate gate for delivery

The fix serializes delivery, not counting. There’s a second lock that holds only the last value delivered. A snapshot that’s older than what already went out gets dropped:

private let emitGate = OSAllocatedUnfairLock(initialState: Int64(0))

private func deliver(_ snapshot: Progress) {
    emitGate.withLock { last in
        guard snapshot.bytesProcessed >= last else { return }  // stale frame
        last = snapshot.bytesProcessed
        emit(snapshot)
    }
}

Three details matter:

  • It’s a different lock from the counter’s. The per-chunk accounting path stays as uncontended as the coalescing made it. The gate is only taken on the already-infrequent flushes.
  • Dropping is safe here. A dropped frame is always older than one that was already shown, so the bar loses nothing. The largest snapshot always gets through, because when it reaches the gate nothing larger has been delivered. The final “finished” frame snaps the count to the total, so the bar always ends at exactly 100%.
  • >=, not >. A frame that marks a new entry without adding bytes still passes, so the current filename keeps updating.

The cost is that emit now runs while holding a lock. That’s acceptable because emits are infrequent after coalescing, and the callback must never call back into the sink. If your callback can re-enter or block, this pattern will deadlock or stall, and you want a queue instead.

Make the flaky test deterministic

The end-to-end test failed about 20% of the time because it depended on two shards happening to race. That’s a poor regression test: remove the fix and it still passes four times out of five.

So the fix came with a test that goes after the sink directly. Sixteen tasks each call addBytes(1) 250 times, all at once. That’s 4,000 concurrent emits, which makes an out-of-order delivery close to certain without the gate. The test asserts two things: the delivered sequence never decreases, and the last value delivered is exactly 4,000.

await withTaskGroup(of: Void.self) { group in
    for _ in 0..<16 {
        group.addTask { for _ in 0..<250 { sink.addBytes(1) } }
    }
}
let bytes = collector.values
#expect(zip(bytes, bytes.dropFirst()).allSatisfy { $0 <= $1 })
#expect(bytes.last == 4_000)

The second assertion matters as much as the first. A gate that drops too much would pass the monotonic check and leave the bar short of the total.

What to take away

  • Atomic isn’t ordered. A lock guarantees that each result is correct. Once the work leaves the lock, it says nothing about the order the results arrive in.
  • Every concurrent producer of a “latest value” needs a rule for stale values. For a progress bar, the rule is “never go backwards.” Write it down in code rather than hoping the scheduler is kind.
  • Optimizations change timing. The coalescing change didn’t introduce this bug, but it came with the test that found it.
  • When a concurrency test flakes, write a second one that forces the race. Hammer the shared component directly instead of waiting for the full pipeline to line up badly.

Related posts