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

zat.dev/zlay

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

0
0
532 lines · 26.5 KB Raw History

handoff 2026-08-04 — zlay on zio: seven fixes and a soak

STATUS: FINAL. Soak v3 passed: 95 minutes, 19/19 samples green, on the exact ship build. Details in the soak section.

Continues HANDOFF-2026-08-03-zio-backend.md. That handoff ended with: zlay runs on zio, holds ~47 connections, does not sustain. Since then, seven root-caused bugs were found and fixed across zio and zlay, and the current build connects the full ~1,900-host fleet with sub-second /metrics during ramp.

branches

zio — zzstoatzz.io/zio, branch fiber/mmap-guard-stacks (tip 6bf8eba):

6bf8eba  sched: park-shot window to 4KB
f4cc7c4  sched: park-shot detector reports and continues
bda454b  poller: per-direction one-shot arms on epoll          <- fix 6
2c1fe11  sched: membership invariants + rsp-bounds assert; collision test
d5b91f9  sched: park-shot scribble detector
6fdb246  sched: panic on double pushReady
b45b4fe  sched: checksum saved-register block across parks
6b9f83b  bench: storm churn mirrors zlay reconnect error path
cd8a7c9  bench: storm hung-connect cancellation
d64f0f0  backend: retire read/write-side nonblock flip
7d5e466  backend: SpillPool — owned worker threads              <- fix 5
7270453  backend: fiber-native Io.Group                         <- fix 4 (see caveat)
6842075  backend: nonblock belt while groups were Threaded
6e7fbc7  backend/sched: boundary invariant; drop broadcast wake
634a73a  backend: DNS spill on a detached thread (superseded by 7d5e466)
8037e06  backend: park fiber until DNS spill completes          <- fix 3
2a1853c  bench: adversarial fiber storm (new harness)
17bfbad  backend: force fibers' sockets non-blocking            <- fix 2
f27c7ff  backend: non-blocking ip6 connect on the fiber path    <- fix 1½

zlay — zat.dev/zlay, branch fix/subscriber-connect-domain (tip 97440d2):

97440d2  subscriber: sequential per-address connect             <- fix 7
91c9147..3e3109e  zio bumps, use_gpa retain_metadata, frame pool fix (fix 1),
                  connect re-revert, queue-full saturation

the seven fixes, shortest useful form

  1. frame pool synced through pool_io (zlay): fibers parked on a Threaded kernel futex, freezing the loop. Pool sync now uses the main io — zio's futex vtable is dual-domain.
  2. blocking fds reaching fiber read/write (zio): the fiber path parks on EAGAIN, which requires non-blocking fds; Threaded-created fds arrived blocking and seized the loop in read(2). Invariant now held at the boundaries. Diagnostic tell: all threads in futex/nanosleep wchan, none in epoll_wait.
    • 1½: ip6 connect fell through to a blocking inner connect — capped every early run at ~150 connections and starved the loop.
  3. DNS spill outlived its caller's frame (zio): the spilled getaddrinfo wrote results into a stack-resident queue after cancellation freed the frame — the source of the @errorName-garbage corruption class. The caller's fiber now parks until the spill completes; the spill runs on a SpillPool (plain threads zio owns) after a detached-thread version died in glibc TLS teardown and an inner-Threaded version corrupted per-thread state (Threaded await/futex are undefined on threads it doesn't manage).
  4. group.await from a fiber kernel-parked the loop thread (zio): Threaded's groupAwait blocked the loop for up to a TCP timeout per dead host during HostName.connect — THE cause of the persistent /metrics starvation across every earlier run. Groups are now fiber-native. Caveat: an unsolved corruption correlates with fiber-native groups under field churn — see "open bug" below.
  5. SpillPool as the designed home for blocking calls from fibers.
  6. epoll arm collision (zio): one registration per fd meant the second fiber to arm an fd stole the first's wake. Per-direction tokens now. Found by a deterministic test in an OrbStack x86_64 container.
  7. sequential per-address connect (zlay): HostName.connect races addresses via Io.Group + cancels losers — wrong tradeoff for a relay. The subscriber now resolves and tries addresses one at a time. This also removes fiber-native groups from the hot path entirely, sidestepping the open bug.
  8. poller left empty registrations as RDHUP-only (zio, fc6e0aa): once both direction tokens were consumed, the registration kept firing token-less hangup events for every dead socket (level-triggered), and a few hundred churned connections filled every epoll batch with noise — observed as the ws accept loop going deaf mid-run while metrics stayed healthy. Registrations are deleted when no direction is armed. This was caught because a consumer was finally attached — always attach one.

the open bug: parked-stack scribble under group churn

With fiber-native groups in the hot path (pre-fix-7), runs died in 2–45 minutes: a callee-saved register holding an error code arrived at @errorName as garbage. Evidence collected: a parked fiber's switch frame was overwritten by a coherent park frame from vtNetConnectIp→waitEvent (two logical fibers on one stack), yet exact list-membership invariants and an rsp-bounds assert never fired, and a 512B park snapshot saw nothing. The 4KB-window detector run was cut short by fix 7 making the question non-blocking. The no-groups build ran 72 minutes clean.

Post-certification investigation (2026-08-04 evening). Two real zio bugs were root-caused after the canary, plus one correction to earlier claims in this document.

Root cause of the group-era corruption: io.async was never overridden. zio's vtable replaced concurrent/await/cancel but not async, so every io.async call fell through to the inner Io.Threaded and returned a Threaded future object — which Future.await/cancel then handed back to zio's vtAwait/vtCancel, which cast it to *Task and read/wrote refs/state/result at offsets that mean something else entirely inside a Threaded future. HostName.connect is built on io.async (connectMany, and lookup inside it), so every reconnect minted a type-confused future. This explains the garbage error unions at @errorName and the 0xAA… (zig undefined-fill) values seen in task fields. Fixed in zio 41d3be1; async now spawns fibers exactly like concurrent, with the eager-inline fallback its contract permits.

A second, latent bug that fix exposed: lost fiber wake from a spilled DNS lookup. Threaded.netLookup writes results into the caller's queue and closes it through its own inner io, whose futexWake is kernel-only and readies no fibers. HostName.connectMany consumes that queue concurrently with the lookup, so its fiber parked in queue.getOne forever. Symptom: a relay that spawns 1,797 subscriber fibers and establishes zero connections, while /metrics and the accept path stay perfectly healthy — relay_seq pinned at 0. Latent before the async fix because connectMany then ran on a Threaded thread, where a kernel-only wake was the right domain. Fixed in zio 9c8d3cf (broadcast fiber wake on spill completion).

CORRECTION to an earlier revision of this document: it claimed the corruption was "confirmed as stack aliasing" based on a parked-stack snapshot detector. That detector had an address bug — it snapshotted at the stack pointer captured before the context switch (the fiber's previous park) and verified against the current one, so ordinary changes in park depth read as corruption. Every park-shot diff and GEOMETRY panic from it is unfounded, and no evidence of stack aliasing survives. The two bugs above were found by other means (error-value tripwires, relay_seq inspection, code reading) and are unaffected. Detector fixed in zio 1321be0; it is comptime-gated off in ship builds either way.

Still open: the prod deafness itself. Neither bug above explains it — the ship build uses sequential connect (no connectMany, no io.async) and had no async override. A consumer-churn harness now exists to attack it (see below); it has not yet reproduced prod's failure.

observability added for the next canary (this is the important part)

zio.ZioBackend.debugStats() (zio d0526f8) exposes scheduler internals cheaply and on demand — switches counter, live/ready/parked fiber counts, futex waiter count, timer heap depth, inject queue depth, free list, poller registration count, and DNS spill pool depth/workers/idle. Walk is O(fibers) and happens only when called.

Wire these into /metrics before the next canary so the operator's prometheus captures them through any onset (last time the scrape timeline was the only forensics that survived the pod). The discriminators they give you, which we lacked entirely during the incident:

  • switches flat across scrapes → the scheduler loop is wedged
  • parked climbing, ready ~0 → fibers piling up on a lost wake
  • poller_registrations collapsing → registration erosion
  • dns_queued climbing, dns_idle 0 → spill pool saturated/stuck
  • all healthy while serving is deaf → the failure is above the runtime

instrumentation that now exists (all in zio, cheap enough to keep)

  • saved-frame/park-shot scribble detector with per-write reports (sched.zig, park_shot_bytes)
  • exact in_ready/in_free membership panics; ctx.rsp bounds panic
  • the storm bench: error propagation across parks under lookup/cancel/socket churn + heap canaries + echo integrity
  • the arm-collision test (fails only in dirty-fd environments — run the full suite, not the test alone)
  • an OrbStack x86_64 container loop: docker run --platform=linux/amd64 zig016 … with -mcpu baseline (Rosetta misreports the CPU)

the machine

zlay-zio-0801 (fly, personal, ord, 8cpu/16GB, NO VOLUME — stop/start loses everything). The machine's init command exits after exactly 24 hours (observed twice: clean exit_code=0 at the 24h boundary) — a soak scheduled near the end of a lifecycle dies with the box; check fly machine status event logs before blaming the workload. /root/provision.sh (base64-shipped from the session) reprovisions from a bare rootfs: toolchain, postgres with scram auth on localhost, zlay build, cron event-log janitor (the 8GB disk fills in under an hour at full ingest), core pattern. Warm tree /root/zlay-work (keep it warm: untar over it, don't recreate). Postgres seeded. 8GB disk: the event log fills it in under an hour at full ingest — wipe /data/events/* per run. pkill -f with any pattern from your own command line kills your own ssh session.

soak evidence — TO FINALIZE with soak v3

Soak v1 (build 97440d2, fixes 1–7): 75+ minutes, ingest fully healthy (1,500–1,900 conns, metrics 0.03–0.6s, RSS 1.16–1.35GB no trend, queues clean), but its ws accept loop went deaf mid-run — that diagnosis became fix 8, so v1 certifies nothing beyond ingest.

Soak v2 (build c39adfc, all 8 fixes, consumer attached throughout): ~75 minutes, every gauge green at every sample — 1,477–1,858 conns, RSS 1.23–1.35GB oscillating with no growth, metrics 0.027–0.57s (1.4s once, during ramp), seq 154k→1.21M continuous, broadcast queue never full, db queue always 0, consumer delivered ~890k frames / 4.8GB at ~270 frames/s and successfully RECONNECTED at the hour mark (re-proving the fix-8 path under long-run conditions). The relay also sailed through two disk-100% episodes without dropping connections. The window ended at ~75 minutes because the fly machine's own 24-hour keepalive expired (clean exit_code=0 of the VM — see machine notes), not due to any relay behavior.

Soak v3 — PASSED (ship build c383540 = zio 6790455 with the detector gated off; reprovisioned machine; consumer attached throughout; 2026-08-04 07:40–09:15 UTC):

  • 95 minutes, 19/19 samples green, zero crashes, zero assert trips
  • connections 1,307–1,872 (normal fleet churn around ~1,831 seeded hosts)
  • RSS 900–1,057 MB oscillating, no growth trend — ~2.6x below prod's flat 2.6 GB, and ~300 MB lighter than the detector builds
  • /metrics 0.034–0.405 s across all samples (never over half a second)
  • relay_seq 0 → 1,221,943 continuous; db queue depth 0 at every sample
  • consumer: ~812k frames / ~4.2 GB across two sessions at ~215–270 frames/s, with a clean reconnect at the hourly session recycle
  • disk stable at 37–39% under the cron janitor
  • recommended next: operator canary (message drafted); the box keeps running as unattended burn-in until its 24h lifecycle ends

canary #2 candidate (2026-08-05)

Deploy target: zlay df312dd (branch canary/obs-2026-08-04) with zio 385c825 (branch canary/obs-2026-08-04).

what changed vs the build you already ran

Deliberately almost nothing. This is the certified code plus eyes:

  • added: zio runtime internals exported on /metrics (see below)
  • added: scripts/zlay-forensics.sh — run it in-pod before rollback
  • removed: dead code (the pre-fiber Engine prototype and its bench)
  • unchanged: every code path that serves traffic

Explicitly NOT included: the two zio bug fixes found after the canary (async override, DNS broadcast wake — see the section above). They are correct and on zio main, but they only affect HostName.connect / Io.Group paths that this build does not use, they have not been soaked, and the broadcast wake has an O(fibers) cost per DNS completion that wants measuring before it goes near prod. Minimal delta was the priority.

the new gauges and what each failure looks like

All are zio_*, computed only when scraped, on the loop thread, and compiled out entirely on the Threaded backend. Healthy values from the canary soak, for reference:

zio_sched_switches_total        14036060   climbing fast
zio_sched_fibers{state="live"}      1906
zio_sched_fibers{state="parked"}    1906   ~all parked on io = normal
zio_sched_fibers{state="ready"}        0
zio_sched_futex_waiters                1
zio_sched_timers                     ~120
zio_sched_inject_pending               0
zio_poller_registrations            1646   tracks established conns
zio_dns_spill{kind="queued"}           0
zio_dns_spill{kind="workers"}         32
zio_dns_spill{kind="idle"}            32

Read them like this when something goes wrong:

symptommeaning
switches_total flat between scrapesthe scheduler loop is wedged — a fiber is blocking it (syscall, lock)
parked climbing, ready ~0, switches still climbingfibers piling up on lost wakes
poller_registrations collapsing while conns holdregistration erosion (the fix-8 family)
dns_spill{queued} climbing, idle 0DNS spill pool saturated or stuck
all of the above healthy while serving is deafthe failure is above the runtime — look at the ws server/consumer layer

Also worth watching, and free: relay_seq must advance. A flat relay_seq with healthy everything else means ingest is dead and consumers have nothing to receive — which reads exactly like "serving is broken" if you only probe the serving side. That mistake cost us hours; check relay_seq first.

forensics before rollback

scripts/zlay-forensics.sh is read-only and takes ~10s:

kubectl exec -n <ns> <pod> -- sh -c 'cat > /tmp/f.sh' < scripts/zlay-forensics.sh
kubectl exec -n <ns> <pod> -- sh /tmp/f.sh > forensics-$(date +%s).txt

It captures both ports' responsiveness, ingest liveness across two samples, socket and listener state, epoll registration count, per-thread wait channels, and userspace stacks. Last time the pod died with its evidence and only the prometheus timeline survived; this plus the new gauges should make the next failure self-explaining.

KNOWN ISSUE found during this soak (by the new gauges, in 20 minutes): a fiber leak of ~1 per consumer connection. zio_sched_fibers{live} climbs monotonically while relay_workers_count stays flat at 1798 and conns merely oscillates — so it is not host discovery, and zio_sched_free_fibers sits at ~1, meaning fibers are not being recycled at all. The excess tracks consumer connection count 1:1.

Not a canary blocker: prod runs ~2 consumers with occasional reconnects, so the rate there is a few fibers per hour (each ~200 bytes of struct plus a lazily-populated stack), negligible over a canary window. It matters for long-running deployments and should be fixed before this backend is permanent.

Prime suspect: the websocket server spawns each connection into an Io.Group (server.zig:557), and zio's FiberGroup only frees member records at await/cancel teardown — which for a server group happens at shutdown. Whether the fibers additionally park forever (vs just their task records accumulating) is the open question; live climbing says the fibers themselves are not completing, so start there.

This is the argument for the instrumentation in one line: the certified 95-minute soak never saw this because it made ~3 consumer connections total; the churn harness plus the new gauges surfaced it in 20 minutes.

soak result for this candidate


2026-08-05 overnight: the prod failure REPRODUCED (root cause still open)

the headline

The prod failure now reproduces deterministically on the test box, with zero consumers, in minutes. A fresh relay at ~1,700 upstream connections starves its accept paths: /metrics on :3001 answers roughly 1 probe in 12 (3s timeout), :3000 likewise, while ingest stays healthy (relay_seq advancing, hosts still connecting) and the loop thread sits at only ~50% CPU. That is the 2026-08-04 prod signature — both ports mostly-deaf, process alive, ingest continuing, scrapes intermittent with the occasional lone success.

This is the thing we did not have before: a failure we can trigger on demand instead of waiting for prod.

ruled out, with evidence

  • epoll watch exhaustion — max_user_watches is 3,639,251. Off by three orders of magnitude.
  • arm failures — zio_poller_arm_failures_total stayed 0 throughout. Nothing fails to register.
  • CPU saturation — loop thread ~36–50%, not pegged.
  • consumer fan-out — reproduced with ZERO consumers attached.
  • the fiber leak — real (see below) but not causal; reproduction happens with the leak fixed.

two real bugs found and fixed on the way

  1. fibers stranded on closed fds (zio, 71a66ba + regression test 41a83f1). zio never overrode netClose; the kernel drops closed fds from the epoll set without an event, so any fiber parked on one waited forever — one leaked fiber per connection under churn, identified by the new zio_fiber_starts histogram as the websocket server's per-connection handler. The test fails (hangs) without the fix and passes with it.
  2. ready-queue starving the poller (zio, d6d77b7). step() drained the ready queue to empty and skipped poller.wait() whenever anything was runnable, so a busy fiber population could stop io delivery entirely. Real bug, and it matches the symptom shape — but measured A/B on the box it only moved accept probes from 0/12 to 1/12. It is not the main cause.

the open question (start here tomorrow)

Why is the accept fiber serviced only ~once per 45s when the loop thread is half idle and nothing fails to arm?

Two possibilities, and they are distinguishable with one counter each:

  • the listener's event is never delivered → instrument Epoll.wait to count events delivered per token/fd, or specifically for the listener fds.
  • the event is delivered but the fiber waits in the ready queue → instrument the accept fiber's wakeups (count + timestamp of last wake, exported as a gauge).

That single discriminator decides between a poller-delivery bug and a scheduler-fairness bug, and neither is guesswork once the counter exists.

Worth a look while there: max_batch is 256 against ~1,800 armed fds, and Epoll.wait computes cap = min(out.len / 2, raw.len). Whether the kernel's ready-list ordering can starve a rarely-ready fd (the listener) behind constantly-ready ones is untested.

caveat on the starvation fix

d6d77b7 also made the startup ramp visibly slower (~575 conns at 4 min vs ~1,700 before). The always-poll-with-zero-timeout path may be spinning. It should be measured properly, and possibly reworked to poll with a short non-zero timeout, before it goes anywhere near prod.

bottom line for the canary decision

Do not ship the canary yet. The failure prod hit is now reproducible and still unexplained; two contributing bugs are fixed but the primary cause is not. The instrumentation, the forensics script, and the reproduction harness (/root/repro.py pattern: hold N consumers, probe a NEW connection every 20s) are all in place to finish this quickly with a rested head.

overnight addendum — a NEGATIVE result that matters

The ready-queue/poller-starvation fix (d6d77b7) is NOT the cause of the field failure. A dedicated harness (zig build starve in zio) puts 2,000 fibers on hot socketpairs with an accept loop alongside — no relay, no external network — and measures how long a new connection waits to be accepted:

schedulerworst accept latency (2,000 hot fibers)
with the fix16 ms
pre-fix (drain-to-empty, skip poll)8 ms

Neither starves, and ready_now is 0 on every iteration: in this workload the ready queue always empties, so the poller is never skipped. The fix addresses a real hazard and should probably stay, but it does not explain production, and my earlier write-up overstated it.

Also invalid: the "the fix slowed the ramp (575 vs 1,700 conns)" comparison. Those two runs happened on the box in different states — the later one after fly's shared-CPU burst quota was exhausted. Not a like-for-like measurement.

What this narrows. A large parked-fiber population by itself does not starve accept. So the cause lies in what the relay adds on top: TLS processing on the loop thread, frame-pool cross-domain handoffs, reconnect timers, and real peers with real latency. The next harness should model those, not just fiber count.

Immediate blocker. The test box is CPU-throttled (fly shared-cpu burst exhausted after a day of builds): a cold zlay build is progressing at ~1.4 MB of cache per minute and would need hours. Options for tomorrow, in order of preference:

  1. build zlay locally (cross-compile works, ~25s incremental) and ship the binary — avoids building on fly entirely; needs a transfer method that handles ~145 MB (base64-over-ssh fails above ~100 KB)
  2. a short-lived performance-* machine (cents/hour) purely to get loop stats from a real relay under the failure
  3. wait for the shared-CPU quota to replenish

The measurement still wanted, unchanged: run the diagnostic build (zio_debug_loop_stats = true, prints [loop] iters/switches/polls/events/ batched/live/ready_now to stderr every 5s) on a relay while accept is starved. ready_now and polls discriminate between poller starvation, readiness never arriving, and accept losing a fairness race — and stderr works when the HTTP metrics path does not.


ROOT CAUSE FOUND AND FIXED (2026-08-05)

the bug

zio's scheduler clock is millisecond-granular, and Io.Timeout durations were converted to it with @divTrunc. A sub-millisecond sleep truncated to zero, producing a deadline of now: sleepUntil's while (nowMs() < deadline) was false immediately and the call returned without ever parking.

zlay uses the standard polling shape in three places:

while (!done) io.sleep(Io.Duration.fromMicroseconds(100), .awake) catch {};
  • src/internal/event_log.zig:111 — DbRequest.wait, which every DB request goes through
  • src/internal/broadcaster.zig:708
  • src/internal/slurper.zig:330

So any fiber waiting on the database busy-spun the single loop thread instead of yielding it. One spinner starves every other fiber on that thread: the accept loops on :3000 and :3001 go deaf, io throughput collapses, and the process still looks alive with ingest trickling. Worse with fleet size, because more hosts means more DB traffic means more spinners — which is why prod (2,763 hosts) failed where the 1,830-host soaks merely showed latency spikes.

Fix: zio beb13c8 — round any non-zero duration UP to at least 1ms, so a sleep actually parks. On main as d5c0a2e.

the evidence

Loop-internal counters (zio_debug_loop_stats, printed to stderr because the failure breaks the HTTP metrics path itself):

beforeafter
live fibers2271,831
polls returning events13%49%
fibers run per loop iteration0.624.7
accept probes succeeding0–1 of 1210 of 10

Before: 1,772 polls/sec delivering 238 events/sec — a loop spinning on nothing. After: the same relay carries 8x the fibers with the full fleet connected (1,818 conns), metrics answering, relay_seq advancing, zero arm failures.

Regression test: Zio: a sub-millisecond sleep parks instead of busy-spinning — 200 sub-ms sleeps must take >=150ms of wall time. Verified to FAIL (finishes instantly) with the truncating conversion restored.

what this retroactively explains

  • the metrics-latency spikes (0.4s, 1.4s) in soaks we called "passing"
  • the throughput decay I first blamed on my own builds competing for CPU
  • why the synthetic starve harness never reproduced it: no database, so no sub-millisecond sleeps, so no spinners
  • why it took ~35 minutes in prod: spin pressure grows as DB traffic does

corrections to earlier sections of this document

Both were written with more confidence than the evidence supported:

  • the "stack aliasing" diagnosis — an artifact of a detector bug of mine (snapshot taken at the pre-switch stack pointer), retracted earlier
  • the ready-queue/poller-starvation fix (d6d77b7) — a real hazard, but NOT this bug; the starve harness shows 16ms vs 8ms worst accept latency with and without it, neither starving

other real bugs fixed along the way (keep, but not the cause)

  1. netClose never overridden → fibers parked on a closed fd were stranded forever, leaking one per connection under churn (zio 71a66ba, with a regression test that hangs without it)
  2. group members held until teardown → unbounded Task accumulation for a long-lived server group; fixed with O(1) unlink, after a first attempt that introduced a use-after-free (caught by a zig zen review pass)
  3. poller arm failures were silently swallowed into a spin; now counted with errno and surfaced as an error
  4. per-direction epoll arms: a second fiber arming an fd stole the first's wake