Linora

0705. Tail counters: signed deltas, compare-and-swap saves, quiet reconcile

Status: Accepted (2026-11-28). Amends the “Tail counters” part of 0703. Wave-3 review item (PLAN follow-up “review the compactor’s write to realtime-owned columns”).

Context

pages.tail_ops/tail_bytes decide when a page is compacted. Realtime adds +ops/+bytes per committed batch, but lazily: deltas are buffered for up to about 1 s (more while its flush retries) and lost if the process crashes. The compactor subtracted what it folded, greatest(0, tail - folded), and ADR 0703 claimed the two writers commute. The review found two flaws:

  1. The clamp does not commute. When a compaction folds batches whose deltas are still in realtime’s buffer, tail - folded goes below 0 and is clamped. The late flush then adds them back, so the counter overcounts by folded - tail, permanently. That happens on every busy page; the property test reproduces it.
  2. Overlapping jobs double-subtract. A job whose lease expired (stall, GC pause, slow DB) can still save after another job has compacted the same range from the same base snapshot. The insert succeeds (a different seq), and the counters are decremented twice.

Decision

Proof sketch

Each writer issues a single UPDATE pages SET c = c + d WHERE id = ... (realtime: d = +ops of a batch; compactor: d = -ops folded). Postgres takes the row lock and, under READ COMMITTED, re-evaluates the expression on the latest committed version, so no update is lost. Integer addition is commutative and associative, so after any interleaving c = Σ(realtime deltas delivered) − Σ(folded ops). The CAS makes the folded sets a partition of the batches at or below snapshot_seq. With all deltas delivered, c = Σ ops of batches above snapshot_seq: the exact tail. The only non-additive writes (zeroing) happen when the tail is provably empty and no delta can be pending, so they agree with that sum. A lost delta (crash) leaves a constant offset until the next quiet reconcile.

Alternatives

Consequences