~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zlay

atproto relay in zig · mirror of https://tangled.org/zat.dev/zlay

0
0
111 lines · 6.4 KB Raw History
# seq rewind on unclean restart — relay_seq goes backwards

**Punchline:** zlay's event log is a Zig port of indigo's `diskpersist.go`, but it broke
indigo's one load-bearing invariant: **an event is broadcast to consumers only after it is
durably on disk.** zlay moved the broadcast out of the flush and into the persist callers, so
it broadcast `relay_seq` up to one flush interval *before* writing it. An unclean kill (OOM /
crashloop) then lost the unflushed tail, and on restart the seq counter resumed *below* seq
values already broadcast — consumers saw `seq` go backwards. **Fixed** in two parts, both
below: (1) a committed-seq watermark so a frame is never emitted before it's durable, and
(2) a validating recovery scan so a torn tail can't mis-recover the seq counter.

## evidence (downstream consumer, 00:51:22–23Z 2026-05-31)

`prev` = consumer's last-seen seq, `seq` = incoming. `prev` pinned at the pre-crash
high-water (~…8994xx) while incoming climbs monotonically from ~2,953 behind:

```
prev 7161747611348899444   seq 7161747611348896501
...
prev 7161747611348899454   seq 7161747611348899032
```

One-time rewind then monotonic climb (a counter rewind, not an ordering race), surfaced on a
cursor reconnect after one of several overnight restarts. The ~2,953-frame gap is ~7× the
400-event flush threshold — see "why the gap exceeded the flush bound" below.

## root cause: a divergence from indigo

Indigo broadcasts from inside the flush, after the durable write, and nowhere else
(`cmd/relay/stream/persist/diskpersist/diskpersist.go:371`):

```go
func (dp *DiskPersistence) flushLog(ctx) error {
    io.Copy(dp.logfi, dp.outbuf)        // 1. write batch to disk
    for _, ej := range dp.evtbuf {
        dp.broadcast(ej.Evt)            // 2. THEN broadcast
    }
}
```

`broadcast` is wired once via `SetEventBroadcaster` (event_manager.go:36). So broadcast
high-water ≤ durable boundary, always; on restart `resumeLog` sets `curSeq = lastDurable+1 =
lastBroadcast+1`, and a rewind is structurally impossible.

zlay had relocated the broadcast into the persist callers (`frame_worker`, `subscriber`,
`host_ops`): each called `persist()`, got the seq, resequenced, and pushed to the broadcast
queue *before* `flushLocked` wrote to disk. `flushLocked` did not broadcast at all. That single
relocation is the entire defect.

## the fix (implemented) — a committed-seq watermark

First attempt broadcast directly from `flushLocked` after the write. It was correct but
**regressed throughput**: the resequence (a frame-proportional CBOR decode+re-encode) ran under
`dp.mutex`, so every flush held the persist mutex for ~400 frame-resequences and serialized all
~2,670 producers behind it. In prod that dropped fr_out ~25%, backed the resolver queue up to
1280, ballooned live heap ~3.6× (queued backlog, not fragmentation), and OOMed. Rolled back.

The shipped fix keeps e77cb89's proven-fast hot path and gates *emission* on durability:

- producers resequence and `push` to the broadcast queue **in parallel, off `dp.mutex`** (exactly
  as e77cb89 did — no throughput change). `persist_order` still serializes the push so queue
  order == seq order.
- `flushLocked` does one cheap thing after the durable write: advance an atomic
  `committed_seq` to the highest seq just written. No copy, no CBOR, negligible lock time.
- the broadcaster fiber **holds back any queued frame whose seq > `committed_seq`**, emitting it
  only once a flush makes it durable (`peekSeq` + watermark compare in `runBroadcastLoop`).

So a frame still can't reach consumers before it's on disk (last broadcast seq ≤ committed_seq ≤
last durable seq), but the expensive resequence stays parallel and off the hot lock. Queued
frames now sit in the broadcast queue for up to one flush interval (≤100 ms), so steady-state
`relay_broadcast_queue_depth` rises to ~tens–hundreds — expected, not backpressure.

Regression test: `event_log.zig` "committed_seq advances only on durable flush" — persists
below the flush threshold, asserts `committed_seq` stays 0 (frames held), flushes, asserts it
jumps to the highest durable seq. (Also fixed the DB test harness to give each test an isolated
database — the suite's runner executes tests concurrently against one server, so they were
contaminating each other through the shared relay tables.)

## recovery hardening — why the gap exceeded the flush bound (fixed)

The 2,953-frame gap was larger than the 400-event/100 ms flush window should allow, because of
a *second*, recovery-side weakness in the same subsystem: `scanForLastSeq` advanced `pos +=
header_size + hdr.len` trusting `hdr.len` with no validation, and on a short read just `break`ed
and returned whatever seq it reached. A torn record (what an interrupted flush leaves) desynced
the walk and truncated — or over-counted — the recovered tail by an arbitrary amount,
compounding across crashloops.

Now fixed alongside the broadcast change:

- `scanForLastSeq` **validates every record** (known `kind`, `len <= max_record_len`, body
  fully present before EOF) and stops at the first record it can't trust — so a torn tail is
  bounded to the torn record itself, never an arbitrary rewind.
- `resumeLog` **truncates the file to the last valid record** (`File.setLength`) and appends
  from there, so the torn tail can't poison future appends or scans, and logs the heal loudly.
- Regression test: `event_log.zig` "scanForLastSeq stops at a torn tail" (no DB) — writes two
  complete records plus a record whose header claims 999 payload bytes with only 2 present, and
  asserts the scan recovers seq 2 and the offset at the end of record 2.

Remaining, and genuinely a different failure mode (not this incident): there is no `fsync` on
flush — recovery relies on the page cache, which survives a **process** OOM/kill (what happened
here) but not a **node**/power loss. Adding `fsync` + flush/rotation ordering would extend
durability to node loss; it is not required to close the seq-rewind, which was process-kill.

## status

Committed and the suite is green (236/239, 3 platform skips), incl. DB tests against an isolated
postgres and the torn-tail recovery test. Both halves of the bug are closed: broadcast never
outruns the durable seq (committed-seq watermark), and recovery never mis-reads a torn tail
(validated scan + truncate). The downstream consumer (tap) is on
`relay1.us-east.bsky.network`; redeploying zlay is not urgent, but it is now trustworthy enough
to take traffic again.