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

zat.dev/zlay

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

0
0
393 lines · 22.8 KB Raw History
# Live-only zkv relay on disposable Fly machines

The full zkv-backed relay ran against real PDS WebSockets with normal host
bootstrap, authority resolution, signature/proof validation, collection indexing,
PostgreSQL account state and a real downstream WebSocket subscriber. Replay
history was disabled as requested. Production zlay and zeldi were untouched.

## Sustained-CPU comparison with relay-eval

The earlier shared-CPU result did not establish a zkv capacity limit. With
sustained CPU time available, **both collection-index implementations completed
ten minutes of live relay traffic**, ended with empty frame queues, and observed
more than 99% of the DIDs seen by both reference relays.

| Measurement | zkv | RocksDB |
|---|---:|---:|
| Events consumed by the checking client | 169,208 | 173,101 |
| DIDs seen by both independent references | 35,448 | 36,450 |
| Those DIDs also seen by the pilot | 35,198 (99.29%) | 36,215 (99.36%) |
| Final-minute event delivery | 299/s | 267/s |
| Final-minute relay CPU time / wall time | 0.29 cores | 0.28 cores |
| Final-minute whole-VM busy CPU | 0.58 cores | 0.59 cores |
| Final queued payload | 0 bytes | 0 bytes |
| Largest observed queue in final two minutes | 0.34 MiB | 0.03 MiB |
| Final relay RSS | 709 MiB | 733 MiB |
| Mean collection-index call wall time | 0.367 ms | 0.072 ms |
| Index share of aggregate frame-worker wall time | 3.14% | 0.59% |
| Authority-check share of aggregate worker wall time | 87.39% | 85.32% |

These are two live input windows, each measured once, not a primitive-engine
speed ranking. The reference subscriptions were simultaneous with each pilot;
the two pilot windows started at different times. The control uses the same
shared relay implementation, validator, PostgreSQL path, lalinsky/zio revision,
16 frame workers and replay configuration. Adapter-specific API plumbing,
backfill/resync integration and collection-index implementation differ.
RocksDB uses its existing adapter defaults, including `sync_writes=false`;
zkv uses the bounded profile with background writes and maintenance after ACK.
Their write/deduplication and durability policies were not normalized into
identical storage operations. Default application LRU limits were retained;
engine block-cache budgets were not equalized.

![Live delivery](zkv-load/live-fly/profile-eval/figures/events_per_second.svg)
![Processing queue](zkv-load/live-fly/profile-eval/figures/queued_mib.svg)
![Measured relay CPU](zkv-load/live-fly/profile-eval/figures/relay_cpu_cores.svg)
![Reference-agreement coverage](zkv-load/live-fly/profile-eval/figures/coverage.svg)
![Collection-index call cost](zkv-load/live-fly/profile-eval/figures/index.svg)

### Why the CPU preset matters

Fly documents a 6.25% sustained baseline per shared vCPU: two shared vCPUs
provide 0.125 CPU cores of baseline time for the entire VM, with temporary
bursting. They are not two sustained CPU cores. The earlier shared-CPU probe
therefore confounded application capacity with the VM's CPU allowance.
Its guest CPU-steal counters were substantial. Steal alone cannot distinguish
quota throttling from host contention; no provider quota-specific time series
was collected, so the exact fraction due to each was not established.

The controls used two performance vCPUs and 4 GiB RAM, the minimum memory
accepted by Fly for that CPU preset. This is an allocation, not a measured
minimum requirement. In the final minute, the entire VM used about 0.58–0.59
busy cores and the relay itself used 0.28–0.29 cores. CPU-steal shares were
0.11% and 0.16%. No claim about equivalent Raspberry Pi throughput follows from
x86 CPU-time measurements; Fig's small-hardware infrastructure remains relevant
prior art, rather than a reason to assume this pilot needs large hardware.

Sources: [Fly CPU performance](https://docs.fly.io/machines/cpu-performance)
and [Fig's community-infrastructure talk](https://2026.atmosphereconf.org/event/7Rrv0E0).

### What the stage timings establish

`-Dprofile-stages=true` enables the existing frame, validation, collection-index
and post-index duration counters on the live path and exposes count, total ns
and maximum ns in `/metrics`. Both controls use it. Timings include I/O,
locking and scheduler waits; they are not on-CPU samples or downstream latency.
The frame timer encloses the other stages. Counter differences use the first
and last successful scrapes, so in-flight work crossing a boundary can affect
the accounting. Whole-window index maximums were 260 ms for zkv and 8.3 ms for
RocksDB; no percentile histogram was measured.

RocksDB's collection-index calls were faster in these windows. The difference
was too small a fraction of total measured worker wall time to reproduce the
earlier persistent backlog in zkv. Authority checks dominate aggregate time,
particularly during cold account discovery; this does not mean they limit
steady throughput when the queue is empty. These results argue against treating
the earlier 47 events/s plateau as a zkv implementation ceiling.

### Coverage, correctness and limits

The coverage denominator is the intersection of the two references' DID sets,
`bsky.network` and `relay.waow.tech`, independent of the pilot. It is recovered
from relay-eval's three-source overlap histograms: the all-three bucket is the
pilot numerator; reference-only pair membership is half of the sum of the two
reference exactly-two buckets minus the pilot exactly-two bucket. The analysis
checks histogram consistency and a known three-set case.

The zkv pilot missed 250 reference-agreement DIDs and the RocksDB pilot missed
235 in their respective windows. Classification was disabled with
`--classify-limit 0` to avoid extra resolver traffic; these gaps remain
unexplained. relay-eval's current `connected` field means connected at least
once, not verified connected for the whole window. All collectors logged a
successful connection and no connection error; independent per-reference
connection-duration instrumentation was not added here. DID coverage does not
prove per-record revision completeness or low latency.

The separate checking WebSocket client reported zero CBOR decode errors,
sequence reversals, sequence gaps or unexpected disconnects in both runs.
All 32 sampled recent DID/collection memberships were found through the public
index endpoint in each run. RAM history entries and disk event payload bytes
stayed zero; cursor replay returned `ReplayDisabled`. The independent checking
client also counts `#sync` frames, which relay-eval's DID collector ignores;
independent handshakes and those protocol choices explain why their event
counts are not asserted equal.

The normal cold-key accept-while-resolving behavior was preserved. Successful
stream delivery does not imply all frames were cryptographically verified.
These are cold-start ten-minute, live-only observations with one downstream
checking client plus relay-eval. Replay-enabled load, long-term maintenance,
restart behavior, larger downstream fan-out, Raspberry Pi performance and a
maximum sustainable capacity remain unmeasured.

### Reproduction and cleanup

The stripped Linux ReleaseSafe binaries used lalinsky/zio. Their SHA-256 values
and source revisions are in each resource record; the embedded SHA can precede
pilot commits and is not the sole source identifier. zkv core and zeldi were
unchanged. Subscriptions and PostgreSQL ran on Fly; production was untouched.
The observer samples machine CPU and CPU/I/O pressure as well as relay counters.

All apps were deleted, with independent app-list absence verification. No
persistent volumes were created. The RocksDB finalizer timed out listing
machines after successfully exporting results, then deleted the app; manual
post-export validation and an independent absence check were recorded rather
than discarding the successful measurement or concealing the finalizer error.

Incomplete probes are preserved separately: the shared-CPU zkv run was
cancelled after finding the CPU confound; the shared-CPU RocksDB setup failed
because its index parent directory was absent; two performance-CPU RocksDB
attempts timed out uploading the compressed binary. The successful control
used an archived transfer driver with a longer upload/machine budget. The
tracked harness now includes that budget, an explicit index directory and
compressed evaluator upload. These setup failures are not engine measurements.

Evidence: [comparison data](zkv-load/live-fly/profile-eval/comparison.json),
[zkv run](zkv-load/live-fly/profile-eval/zkv/fly-resources.json),
[RocksDB run](zkv-load/live-fly/profile-eval/rocks/fly-resources.json), and
compressed raw scrapes, relay/evaluator logs and SQLite databases beside them.
The analysis is `scripts/zkv/fly_live_analysis.py`; the figures are generated by
`scripts/zkv/fly_live_plots.py`. Use the earlier ten-minute `samples.jsonl.gz`
with `--shared-samples` to regenerate the dashed shared-CPU reference.

## Earlier short probes

The 1 GiB VM OOM-killed zlay during the initial window. A 2 GiB VM completed
44 seconds of observation and delivered 9,824 events. This proves a working
live-only pilot, not sustainable relay-scale capacity: queued frame data reached
about 20 MiB, memory still grew, and cold-key frames use the existing validator's
accept-while-resolving path. There is no matched RocksDB live run here.

![Live relay observations](zkv-load/live-fly/comparison.svg)

## Ten-minute full-host consumer run

The zkv collection-index pilot, built with lalinsky/zio and ReleaseSafe, consumed
**52,162 events over 600.03 seconds** on two shared Fly CPUs and 2 GiB RAM.
Normal bootstrap spawned workers for **1,980 hosts**. This is the number of
workers started, not a count of successful simultaneous WebSocket handshakes;
DNS, TLS, handshake and read-loop failures/retries occurred during the run.
The consumer was on the same disposable VM as the relay and PostgreSQL.

The consumer observed zero CBOR decode errors, sequence reversals or sequence
gaps, and no unexpected disconnect. All 32 sampled recent DID/collection pairs
were found through `listReposByCollection`. RAM replay entries and disk event
history bytes stayed zero; cursor replay returned `ReplayDisabled`.

This establishes a working ten-minute live path, **not sustainable capacity**.
The consumer received 19,681 events in its first minute, but only about 2,832 in
the final minute (47 events/s). Queued frame payload grew from 6.7 MiB at one
minute to 121.9 MiB at the last sample. RSS grew from 692 MiB to 822 MiB.
A bounded queue and upstream backpressure can flatten memory while leaving the
relay behind; neither flat memory nor an ordered downstream sequence establishes
that upstream events are being kept current or captured without loss.

At the last sample, host-authority checks recorded 17,200 network checks,
1,727 aggregate seconds of network time and 1,083 aggregate seconds waiting for
a pool connection. These overlapping totals are across workers, not elapsed wall
time. They identify competing work worth isolating; they do not establish zkv
as the limiting component. Twelve of 600 metrics requests timed out.
The existing cold-key accept-while-resolving path skipped validation on 18,189
frames; downstream delivery does not imply every frame was cryptographically
verified. Source-event timestamps include old events and are not relay latency.

Disabling replay removes event-log I/O and RAM history retention while preserving
collection-index work. It can change resource contention. There is no paired
replay-enabled measurement or matched live RocksDB control in this result.

The app `zkv-live-d866c3057c` was deleted after export; machine absence, volume
absence and app absence were verified. No local/heavypad subscriber ran, and
production was untouched. PostgreSQL used about 85 MiB of ephemeral disk;
zero event history does not mean zero working disk usage.

Raw data: [summary](zkv-load/live-fly/ten-minutes/summary.json),
[resource provenance and cleanup](zkv-load/live-fly/ten-minutes/fly-resources.json),
[minute samples](zkv-load/live-fly/ten-minutes/minute-samples.json), and compressed
full samples/logs in the same directory. The binary was unchanged from the cache
audit; the resource record's binary SHA identifies it. Its embedded build SHA is
older than the pilot changes and should not be used as the sole source identifier.

## Cache audit and corrected live-only mode

The original live-only option disabled disk history but **still retained the
50,000-frame RAM replay ring**. That was a pilot configuration mistake. Current
live-only mode skips both. A regression checks that replay-off retains zero
frames and replay-on still retains frames; the live runner now requires every
available history sample to be zero.

A subsequent probe retained the default cache limits and ran on two shared CPUs
with 2 GiB RAM. It delivered **32,521 events**, with no decode or sequence-order
errors, no RAM history entries and zero disk event-history bytes. It survived
without OOM. The observer was configured for 120 seconds but actually completed
in 127.94 seconds: its fixed sample-count loop continued during request delays.
The exported timestamps preserve that overrun. The observer now checks elapsed
time before sampling and bounds the metrics request by the remaining time;
the existing 150-second relay watchdog and 900-second machine watchdog also
bounded this run. All owned machines/apps were deleted; there were no volumes.

![Live cache byte accounting](zkv-load/live-fly/cache-audit.svg)

| Component | Configured limit | Latest available measurement |
|---|---:|---:|
| Signing-key LRU | 250,000 entries | 11,504 entries; 1,288,356 key/node bytes |
| DID-to-UID LRU | 500,000 entries | 11,576 entries; 833,440 key/node bytes |
| UID-to-host LRU | 500,000 entries | 552,672 key/node bytes |
| zkv block caches | 1 MiB per handle; writer and reader | 1,048,536 bytes observed maximum combined |
| zkv writer memtable | 4 MiB pilot maintenance trigger | 33,272 payload bytes observed maximum |
| RAM replay ring | Disabled | 0 entries throughout |
| Frame queues | 16 workers, 4,096 entries per queue | 41,071,686 payload bytes at last metrics sample |

Combined zkv block-cache accounting reached about one handle's configured
budget and stayed near 1 MiB. The gauge does not split the writer and reader
handles, so it does not establish their individual occupancies.
The three LRUs account for about 2.55 MiB of live key/node storage at the end;
the signing and DID LRUs are still only about 4.6% and 2.3% of their entry limits.
They are **not fully warmed**. RSS was 684,208 KiB at 20 seconds, 713,552 KiB at
60 seconds, 720,000 KiB at about 101 seconds and 729,912 KiB (712.8 MiB) at the
last sample. The initial connection ramp dominates the early rise; this is not
proof that all later growth is bounded or that no leak exists.

These are deliberately partial memory accounts. LRU bytes include owned key
strings and nodes with inline values, excluding hash-table capacity and allocator
overhead. zkv block bytes use its existing cache accounting; writer memtable
bytes use its payload counter. They exclude other index metadata, TLS allocations,
socket buffers, stacks and allocator-retained/free pages. Metrics try locks and
omit a byte gauge when it is busy instead of reporting a false zero. The latest
index byte sample is at 121.86 seconds, while the final LRU/queue metrics are at
125.87 seconds. Do not subtract the series from RSS and call the remainder a leak.

Queue payload fell from about 27 MiB at 60 seconds to 3.2 MiB near 101 seconds,
then rose to 39.2 MiB as downstream delivery slowed near the end. Some metrics
requests timed out; available responses were HTTP 200. Thus cache warming is
one part of startup, but this still does not establish sustainable capacity or
explain the later processing slowdown. The run does show that the measured
zkv block cache and LRU payloads are much smaller than the roughly 713 MiB RSS.

Reproduce with the current binary and `fly_live.py --memory 2048 --seconds 120`.
The raw [cache audit](zkv-load/live-fly/cache-audit) preserves the samples,
configuration and hashes. Regenerate this figure with `fly_cache_chart.py`.

## Configuration and measured boundary

Both runs used two shared Fly CPUs in `ord`, x86_64 Linux, ReleaseSafe, zio with
four executors, libc allocation, 16 frame workers and 20 PostgreSQL connections.
PostgreSQL 15.19 ran on the same disposable machine with 32 MiB shared buffers.
This differs from the earlier local PostgreSQL 16, ARM64, retained-history tests.
Do not mix their results into a throughput ratio.

There were no Fly volumes, public services or production routing changes. A
2 GB disposable root filesystem held the application, database and index. Event
payloads were not written there. The relay watchdog was 150 seconds; the VM's
bootstrap watchdog was 900 seconds. The observer targeted at most 45 seconds
and also capped incoming VM traffic at 512 MiB. Observed sample timing and
observation duration, rather than the configured upper bound, are saved.

Bootstrap used `bsky.network`'s normal listHosts endpoint. Approximately 1,978
worker registrations were reached; this is not a count of successful upstream
handshakes. The public host list includes endpoints that failed DNS, TLS or
WebSocket handshakes. A Node subscriber on the VM decoded actual output and
checked increasing sequence numbers. No upstream bytes flowed through the
laptop or heavypad. During the observed windows the VMs received about 67.6 /
92.8 MiB, respectively; package setup traffic is outside those counters.

## Outcomes

| Observation | 1 GiB VM | 2 GiB VM |
|---|---:|---:|
| Observer elapsed | 42.91 s; relay exited | 44.02 s; completed |
| Downstream events | 2,568 | 9,824 |
| Downstream commit frames | 2,528 | 9,633 |
| CBOR decode / sequence-order errors | 0 / 0 | 0 / 0 |
| Last received-frame counter | 4,806 | 14,211 |
| Last fully-validated counter | 364 | 4,378 |
| Last validation-skipped counter | 1,698 | 5,284 |
| Last validation-failed counter | 28 | 406 |
| Last queued frame bytes | 11,686,903 | 20,644,077 |
| Replay event payload bytes on disk | 0 | 0 |
| Cursor replay rejected | Untested after relay death | `ReplayDisabled` |
| Teardown | Machine and app deleted; no volumes | Machine and app deleted; no volumes |

Metrics and client counts are separate snapshots. In the 1 GiB run the last
metrics response was at 26.04 seconds; requests later timed out while the
process remained alive, then its PID disappeared. Kernel output confirms an
OOM kill at 707,140 KiB anonymous RSS (about 691 MiB). Other VM users, including
PostgreSQL and page tables, need memory too. The final client count is not the
last successful metrics snapshot.

In the 2 GiB run relay RSS reached 744,212 KiB (726.8 MiB), with 46 OS threads.
Sampled relay CPU advanced by 30.05 seconds at the recorded 100 Hz clock rate.
Those figures exclude the PostgreSQL process and do not measure available CPU
capacity on a shared host. Queued frames grew while broadcast-queue depth stayed
small (high-water mark 11). This does not identify zkv as the bottleneck.

The configured cleanup uses a bounded TERM/KILL watchdog. The successful live
window logged the shutdown signal but not completion of orderly shutdown before
teardown. It is not a graceful-recovery or acknowledged-durability test.

## What the live run exposed

The first complete cold boot discovered 1,978 hosts but received zero frames.
The startup worker task read the empty PostgreSQL host table before the parallel
bootstrap inserted hosts. There was no subsequent load. That empty-start trace
is preserved, not counted as a capacity result.

The isolated pilot now retries that initially empty table after seed bootstrap
finishes. Existing-host startup remains immediate; no-seed offline runs do not
wait. The follow-up live run exercised this path and registered the discovered
workers. The runner now requires real downstream traffic, successful decoding,
sequence order, zero retained history bytes and an explicit cursor rejection.
A healthy HTTP endpoint alone cannot pass it.

The production validator also has a consequential existing behavior: signing-key
cache misses enqueue background resolution and return `valid=true, skipped=true`.
Those frames can be forwarded and indexed without that frame's signature/proof
check. This experiment did not change that policy. Fully-validated, skipped and
failed counters are therefore separate; output delivery is not proof that every
frame was cryptographically verified. The earlier offline fixture runs required
zero skipped frames, so they perform different validation work.

Source event ages include extremely old upstream events (months in the tail).
They are recorded for diagnosis, not presented as relay latency or an arrival
rate. The source demand, backlog outside the relay and production traffic mix
are not measured here.

Memory rose with the connection ramp while queued frame bytes were much smaller
than total RSS. That makes connection/TLS costs and process allocation behavior
worth profiling alongside index memory. It does not establish a leak or rule out
zkv memory. Longer bounded windows and attribution would be the next steps.

## Replay-disabled pilot mode

`RELAY_REPLAY_HISTORY=false` skips event serialization, buffering and disk flush
while retaining sequence assignment and live broadcast readiness. Sequences are
in memory and can reset on restart. Cursor subscriptions receive `ReplayDisabled`.
The collection index and PostgreSQL state still use working storage. Replay-on
behavior remains the default; the change lives only on `codex/zkv-live-fly`.

The no-history regression uses an allocator that always fails and undefined
storage handles, exercises sequence assignment and flush, and checks that replay
fails before storage is accessed. The unit suite and x86_64 zio build passed.
The live observer confirms the zero-byte event file and cursor response.

The pilot's zkv dependency remains the unchanged `zkv-read-prefix` revision
`221c87c8c18f0f177f3d7ede0994b27ed51e7035`. No core zkv or zeldi source was changed.

## Reproduction and cleanup

```sh
zig build relay -Dbackend=zio -Dtarget=x86_64-linux-gnu \
  -Doptimize=ReleaseSafe -Dstrip=true --prefix /tmp/zkv-zlay-live-amd64
PYTHONDONTWRITEBYTECODE=1 uv run --no-project python scripts/zkv/fly_live.py \
  --binary /tmp/zkv-zlay-live-amd64/bin/zlay --memory 2048 \
  --output /tmp/zkv-live-probe
```

The wrapper creates a uniquely named app, starts a bounded disposable machine,
uploads a compressed binary and the observer, exports logs/metrics even on
failure, destroys machines, verifies an empty volume list, deletes the app and
checks its absence. Setup installs PostgreSQL and the pinned CBOR decoder on
Fly, not locally. The original failed setup attempts are recorded too: a
rejected machine launch, Fly's 4 GiB minimum for two dedicated CPUs, and a
PostgreSQL log ownership error. All six attempted apps are absent after cleanup.

[Raw evidence](zkv-load/live-fly) includes the empty-start trace, OOM trace,
completed two-GiB trace, machine configuration, source/binary hashes and kernel
output. Regenerate the figure with `scripts/zkv/fly_live_chart.py`.