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

zat.dev/zlay

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

0
0
158 lines · 8.0 KB Raw History
# Evented backend attempt (2026-04-03 to 2026-04-10)

> **Current status:** shelved, permanently as of `e6cdf84` (2026-04-09). zlay
> uses `Io.Threaded` (`src/main.zig:62`), and the Docker build no longer applies
> `patches/uring-networking.patch`. This document is a historical record.

log of getting zlay running on `Io.Evented` (io_uring fibers) instead of
`Io.Threaded` (one OS thread per task). goal: drop from ~2,800 threads to ~35.

Evented was shelved **twice**. the first revert (`42e1019`) was a
misdiagnosis: the production SIGSEGV turned out to be a websocket handshake bug
(TCP split mid-CRLF, fixed in websocket.zig `9ac64da`), not fiber machinery, so
Evented was re-enabled the same day (`02434de`). it was shelved again four days
later (`e6cdf84`) — that decision stuck, and for different reasons. see
[why it was shelved for good](#why-it-was-shelved-for-good).

## what we built

- **uring networking patch** (`patches/uring-networking.patch`): implemented 6
  networking operations that are stubbed as `error.NetworkDown` upstream —
  listen, accept, connect, send, read, write. all use proper io_uring opcodes
  except bind/listen (sync syscalls, kernel <6.11). tracked upstream as zig#31723.

- **dual-Io architecture**: Evented for network I/O (subscribers, broadcaster,
  metrics server), Threaded for blocking work (frame pool, DB, GC, resyncer).
  careful segregation to avoid cross-Io mutex/futex incompatibilities.

- **DNS fallback**: `Io.Uring` doesn't implement `netLookup`. subscribers
  resolve hostnames through `pool_io` (Threaded), then use the socket with
  Evented I/O for data transfer.

- **DbRequestQueue**: MPSC queue bridging Evented fibers to Threaded DB
  workers, replacing attempts at running pg.Pool from fiber context.

## what went wrong

28 commits between `39134d1` (first evented backend) and `b8ef148` (last fix),
most of them crash fixes:

| commit | issue |
|--------|-------|
| `6674812` | SIGSEGV: plain threads calling Evented Io.Mutex → NULL Thread.current() |
| `439c678` | startup deadlock: resyncer on Evented fiber blocked Uring thread |
| `2156d08` | heap corruption: GC using Threaded pg.Pool from Evented fiber |
| `3533416` | heap corruption: subscriber pg.Pool access from Evented fiber |
| `949e9a7` | heap corruption: remaining cross-Io pg.Pool paths |
| `72ba680` | use-after-free: broadcaster destroying consumers still referenced |
| `4a23671` | ReleaseSafe GPF: optimizer bug in fiber context-switch |
| `c3bc3be` | replace ev_db with DbRequestQueue (final cross-Io DB fix) |

the fundamental problem: `Io.Mutex`, `Io.Condition`, and `Io.Event` use
backend-specific futex operations. calling a Threaded mutex from an Evented
fiber (or vice versa) dereferences a NULL threadlocal → SIGSEGV or silent
heap corruption. this means any shared resource (pg.Pool, DiskPersist mutex)
must be carefully routed to the right Io backend. we fixed all of these, but
the architecture became fragile.

the final remaining bug: a probabilistic SIGSEGV in `std.Io.fiber.contextSwitch`
(fiber.zig:29) that manifests every 30-90 minutes under sustained load with
~2,800 fibers. under ReleaseSafe it's an immediate GPF; under ReleaseFast
it's probabilistic. the repro (`scripts/repro_evented.zig`) demonstrates the
ReleaseSafe case. this is a zig stdlib bug — the inline asm that swaps
rsp/rbp/rip between fiber contexts corrupts state under certain optimizer
configurations.

## why it was shelved for good

the second shelving (`e6cdf84`, 2026-04-09) was not triggered by a crash. per
that commit, three things together:

1. the 8 cross-Io crash classes above — all fixed, but the architecture stayed
   fragile
2. the ReleaseSafe GPF from the zig codegen bug
3. **a persistent ~10-15% coverage degradation that nobody could trace**

(3) is the one that matters most for any future attempt, and it is the least
understood. `Io.Threaded` restored the proven 0.15 model — thread-per-PDS at
99%+ coverage — and the regression went away. no root cause was ever found, so
it is not known whether it was specific to `Io.Uring`, to the networking patch,
or inherent to running ~2,800 subscribers as fibers. **any fiber-based retry
must explain this first**; a backend that fixes only the GPF does not address it.

what switching back bought, per the same commit: the entire cross-Io problem
class vanished, ReleaseSafe worked again, DNS worked natively, and the uring
networking patch became inert. the cost was ~2,800 OS threads instead of ~35
fibers.

## upstream status

**checked 2026-04-05** (against dev.3059/dev.3091):

- `fiber.zig`: **unchanged** between dev.3059 (our pin) and dev.3091 (latest)
- uring networking: **still fully stubbed** — all six `*Unavailable` functions
- zig team position: Evented is "experimental" with "important followup work
  to be done before they can be used reliably" (HN, feb 2026)
- `Io.Threaded` is the recommended production backend

**re-checked 2026-07-30** (against the pinned 0.16.0 release, `zig env`
`.std_dir`) — no movement:

- `Io.Evented` still resolves to `Io.Uring` on linux (`std/Io.zig:31-36`)
- `Uring.zig` networking **still fully stubbed**: `netListenIp`, `netConnectIp`,
  `netSend`, `netRead`, `netLookup` and the rest are `*Unavailable`
  (`std/Io/Uring.zig:774-789`). `Threaded.zig:1916-1961` implements them.
- so `patches/uring-networking.patch` and the Threaded DNS fallback remain
  load-bearing for any Evented path
- `std.Io` itself is a plain vtable interface (`std/Io.zig:26`, `VTable` at
  `:51`) with no instability markers — but it is **113 function pointers** wide
  (fs, process spawn, mmap, clocks, random, futex, net). that is the bar for any
  complete third-party implementation.

## what we kept

- `patches/uring-networking.patch` — the networking implementation, for
  reference and to resume from when upstream catches up
- `scripts/repro_evented.zig` — minimal reproduction of the fiber GPF
- `docs/history/stdlib-patches.md` — catalog of all 6 workarounds we needed
- this document

## timeline

commit dates from `git log`, not reconstructed:

- 2026-04-03: `6c83f11` Evented backend via patched Uring.zig networking
- 2026-04-03: `39134d1` evented backend with single ordered publication path
- 2026-04-03 to 2026-04-04: 28 commits fixing cross-Io crashes, ending
  `c3bc3be` (DbRequestQueue)
- 2026-04-05: `42e1019` reverted to Threaded after SIGSEGV blamed on fibers
- 2026-04-05: discovered real cause — websocket handshake TCP split bug
- 2026-04-05: `02434de` fixed websocket.zig (`9ac64da`), re-enabled Evented
- 2026-04-09: `e6cdf84` **switched back to Threaded and shelved Evented** —
  final, and the reason the rest of this doc is history
- 2026-04-10: `80eca78` cleaned up stale Evented-era comments in the codebase

## if someone tries fibers again

the backend swap itself is one line — `const Backend = Io.Threaded;`
(`src/main.zig:62`), with `Backend.init` already branched at `:199-203`. the
seam survived the revert: `pool_io_backend` (`:211`) is still a separate
Threaded runtime, documented in-place as "redundant since Backend is also
Threaded, but harmless". so the scaffolding is cheap to reuse.

what is *not* cheap, and what a swap does not fix:

- **`pg.Pool` is not Io-agnostic.** this is the root of the cross-Io rule and
  the source of three separate heap-corruption commits. `docs/history/notes.md` lists
  making it Io-agnostic as the follow-up that "would eliminate cross-Io issues".
  that is the real prerequisite.
- **the XRPC/admin hole was never closed** — API handlers ran on fibers and
  queried the Threaded `pg.Pool`. see `docs/history/notes.md`, "known remaining".
- **the ~10-15% coverage regression is unexplained.** see above.

a third-party `std.Io` implementation with its own stack-switching (e.g. the
**zio** spike noted in [design.md](../architecture/design.md)) would plausibly avoid the
`fiber.zig` GPF, since that bug is in stdlib inline asm. it does not address any
of the three items above, and it inherits the stubbed-networking problem unless
it implements the net vtable itself. **zio has never been tried in this repo** —
as of 2026-07-30 it exists only as a note in design.md.