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

zat.dev/zlay

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

0
0
206 lines · 11.7 KB Raw History
# Finite offline relay replay

The isolated pilot processes and recovers the same 3,300 signed frames as the
RocksDB control, without a PDS HTTP producer or Internet access. Production
concurrency lets zkv submit the short 1,000/s burst on schedule in two runs.
Neither engine sustains the offered 5,000/s fresh-account burst under these
resource caps. These are screening results, not sustained relay-scale capacity.

## Reused components and measured boundary

The signed-frame reader was extracted from atproto-bench into its std-only
`relay-corpus` module (`atproto-bench-relay-corpus`, `6ab1e2d`). The original
CPU benchmark uses that reader too; its full corpus passes and three reader
tests pass. The fixture format and public keys are unchanged. No ZDS dependency
or new protocol writer was needed for this first check.

`Subscriber.acceptFrame` calls the existing WebSocket message callback. The
actual DID-partitioned queues, signature and Sync 1.1 proof verifier, collection
index, event files, PostgreSQL updates and downstream server execute normally.
The fixture is prevalidated and its captured keys installed before timing. The
source context uses `host_id=0`: this excludes host association/discovery and
upstream socket/TLS costs. It is not an authorization or cold-key test.

Each case uses fresh account rows and index state. Every input must increment
the verified count, with no skipped or failed frames. A separate client checks
revision identities, CAR bytes and ordered operations, rejects duplicates, and
compares every membership across all 30 observed collections, including paged
results. After graceful restart it checks those memberships and replays all
3,300 commits from disk. Cursor zero also produces the expected `OutdatedCursor`
info message; the oracle asserts that separately from commit counts.

## Results

Relay cap: two CPUs / 512 MiB. PostgreSQL cap: one CPU / 256 MiB unless noted.
The fixture client is separately capped at one CPU / 256 MiB. Both engines use
ReleaseSafe, zio, libc allocation and identical inputs. RocksDB uses synchronous
index writes; zkv uses the existing bounded maintenance/page-worker profile.

The screening target of 5,000/s comes from zlay's configured trusted-PDS rate
limit, not a claim about current global firehose traffic. The corpus is finite,
historical and not a contiguous arrival-rate sample.

| Workers / DB pool | Offered rate | Completion through final event-file write, zkv / RocksDB | Max submission lateness, zkv / RocksDB |
|---|---:|---:|---:|
| 4 / 5, before probes | 1,000/s | 16.02 / 10.68 s | 12.13 / 7.11 s |
| 4 / 5, with probes | 1,000/s | 10.42 / 7.25 s | 6.75 / 3.58 s |
| 16 / 20, first | 1,000/s | 3.347 / 3.999 s | 3.83 / 622.70 ms |
| 16 / 20, reversed order | 1,000/s | 3.383 / 3.852 s | 4.47 / 379.22 ms |
| 16 / 20 | 5,000/s | 4.178 / 3.851 s | 3.45 / 3.14 s |
| 16 / 20, two PostgreSQL CPUs | 5,000/s | 5.481 / 4.455 s | 4.73 / 3.69 s |

Completion through final event-file write is measured inside the relay, from first scheduled input
through completion receipts and final event flush. It includes queue waits,
validation, indexing, event flushes and account-state updates, but does not wait
for the external subscriber. The separate
`delivery_ms` field includes detection/oracle work and must not be treated as a
pure network latency. Offered rate is never substituted for achieved rate.
The event flush completes a positional write without an fsync. It is not a
power-loss durability measurement; synchronous collection-index writes are a
separate guarantee. Earlier versions called this durable completion, incorrectly.
The before/after-probe rows show run variation, not an improvement caused by
profiling.

![Offline replay measurements](zkv-load/relay-replay/comparison.svg)

The four-worker profiled case averages 5.56 ms in zkv's index call versus
2.49 ms in RocksDB's, including waits. Signature/proof validation is about
0.25 ms for both. The figure's remaining worker time includes account/state
reads, decoding and cleanup; it is not all CPU time. Per-worker intervals
overlap, so their sums do not equal wall time.

With 16 workers, zkv's write owner coalesces more changes: 889 changed commits
in the first 1,000/s case versus 2,076 in the four-worker profiled case. This
changes the cost of the actual pipeline, not just an isolated commit timing.
It also means these 16-worker bursts do not reach a full compaction cycle:
they end with two or three L0 tables. The four-worker full-corpus cases do
exercise stepped compaction. Sustained maintenance at production concurrency
is therefore still open.

The one-CPU PostgreSQL quota matters: in the first 5,000/s case, PostgreSQL
accumulates 2.70 s of throttling with RocksDB and 0.04 s with zkv. Giving it two
CPUs does not remove the shortfall or improve either observed completion time.
The results do not support a CPU-quota-only explanation, and local I/O/run
variation is substantial. The table deliberately retains the slower runs.

In the first 16-worker 1,000/s pair, relay-container CPU is 2.25 / 2.70 s and
peak cgroup memory is 94.7 / 105.3 MiB, zkv / RocksDB. PostgreSQL CPU is
2.96 / 3.56 s and peak memory about 128 / 126 MiB. Relay data occupies about
18.1 MB for either engine. CPU spans the client run and readback; memory peaks
include setup and charged cache. They are not steady-state CPU or process RSS.

## Reproduction and cleanup

Build only the relay with
`zig build relay -Dbackend=zio -Doffline-replay=true -Dtarget=aarch64-linux-gnu -Doptimize=ReleaseSafe -Dstrip=true`. Replay and
timing instrumentation are opt-in; normal builds retain the original intake
behavior. The lazy reader dependency points to the isolated atproto-bench
worktree. Its reader has no protocol-library dependency.

```sh
PYTHONDONTWRITEBYTECODE=1 uv run --no-project python scripts/zkv/replay_run.py \
  --binary /tmp/zkv-zlay-replay-zkv/bin/zlay \
  --corpus /Users/nate/tangled.org/zzstoatzz.io/atproto-bench/fixtures/relay-corpus.bin \
  --output /tmp/replay-case --count 3300 --rate 1000 --workers 16 --db-pool 20
```

The runner reuses the earlier isolated process/resource probes and Compose
services. Its overlay creates an internal project-scoped network with no host
ports and mounts the corpus read-only. Readiness, client execution, stop and
restart have deadlines. It removes containers and volumes on success or error,
then checks all labeled containers, networks and volumes are absent. Metadata
records actual network names, limits, binary/corpus hashes and cleanup results.
Private database passwords and failure logs are never exported to docs.

All reported cases passed content, index, restart and cleanup checks. No Fly
machine or heavypad work was used. Production checkouts, core zkv and zeldi
were unchanged. Raw reports are in [zkv-load/relay-replay](zkv-load/relay-replay).
Earlier raw metadata uses `count=10000` as a requested limit; the actual selected
count is 3,300 in `result.json` and `REPLAY_DONE`.

## Remaining capacity work

The captured stream cannot simply be looped into a stateful relay: repeated
revisions become stale. The next sustained/mixed case needs fresh valid commits
and a warmup prefix, using existing authoring machinery where possible. It must
cover mostly-known identities, explicit novelty ratios, larger repo state and
at least a complete maintenance cycle at production concurrency.

Per-frame queue/processing traces, upstream transport, additional fan-out and
abrupt-stop recovery are not yet qualified here. If local I/O variation prevents
useful attribution, repeat short cases on a disposable resource-bounded Fly
machine. The capacity goal remains active; these short bursts do not complete it.

## Fresh revisions and known memberships

The ZDS benchmark tool now exports its actual `applyWrites` sequenced events
in the shared atproto-bench format (`zds-relay-fixture`, `7eef515`). Signing,
MST updates and event serialization remain ZDS's implementation. Temporary
SQLite/blob state is deleted; only raw frames and public keys are exported.
The exporter passed ZDS's required test and endpoint smoke suites, including
per-commit checks with `git rebase -x`.

Two new paired screens rotate across 16 accounts. Each starts with one record
per account in the shared collection, then creates fresh records. Five or
20 percent of subsequent frames introduce unique collection pairs; the rest
use existing pairs. The 16-frame prefix is included in timing. Repositories
grow from empty; these are controlled distributions, not a claim about actual
relay novelty or large-repository performance. Every pair uses the identical
exported file and checks its SHA-256. Generation is outside measurement.

| Input / demand | Completion seconds, zkv / RocksDB | Achieved frames/s, zkv / RocksDB | Max submission lateness, zkv / RocksDB |
|---|---:|---:|---:|
| 2,064 frames, 5% new pairs, 500/s | 4.128 / 5.136 | 500 / 402 | 4.39 / 686.18 ms |
| 8,016 frames, 20% new pairs, 1,000/s | 16.540 / 27.283 | 485 / 294 | 8.09 / 18.83 s |

Both engines passed validation, exact downstream content, every collection
membership, graceful restart and disk replay. Workers/pool remain 16/20,
relay 2 CPUs/512 MiB, PostgreSQL 1 CPU/256 MiB, durable index writes. The
2,064-frame pair ran zkv then RocksDB; the 8,016-frame pair reversed order.
These pairs have not yet been repeated. A 68-frame exporter calibration also
passed both engines; it overlaps compilation and is excluded from performance
conclusions and charts.

![Generated signed relay workloads](zkv-load/generated-relay/comparison.svg)

The mostly-known case changes the work substantially: zkv's adapter checks both
membership keys and skips an already-present pair; RocksDB's current adapter
writes both empty keys on every create/update. This preserves API membership
semantics but is an adapter optimization, not evidence of superior primitive
engine throughput. A duplicate-suppressing RocksDB control is an outstanding
attribution experiment.

The 8,016-frame case exercises 1,536 flushed segments, seven compaction steps
and 198 collection steps. It ends with five unflushed segments and two L0
tables. Steps are not completed-cycle counters, and a final snapshot does not
prove bounded debt. Both engines fall behind the offered load; the short
captured 1,000/s success does not qualify sustained capacity.

Mean index call time in that longer case is 2.56 / 4.54 ms, zkv / RocksDB;
persistence plus state updates average 3.64 / 5.24 ms. Validation is about
0.21 / 0.23 ms. These include waits and overlap across workers. PostgreSQL
throttling is 0 / 0.092 s, so CPU quota alone is not an adequate explanation.
The small fixed identity set can also interact with DID-partitioned queues;
it is not equivalent to the captured workload's identity distribution.

Relay CPU across measurement plus delivery/readback is 6.48 / 10.93 s; peak
cgroup memory is 101.0 / 117.1 MiB. These are charged cache-inclusive peaks,
not RSS. Engine-specific cache misses, write amplification, paired per-frame
latency, abrupt failure and repeated sustained maintenance remain open.

Reproduce a fresh shared fixture with:

```sh
cd /Users/nate/tangled.org/zat.dev/zds-relay-fixture
zig build bench -Doptimize=ReleaseSafe -- --scenario relay-corpus \
  --accounts 16 --records 8000 --novel-percent 20 --output /tmp/relay.bin
```

Feed that exact file to both engines with the existing runner, `--count 8016
--rate 1000 --workers 16 --db-pool 20`. Raw results are under
[zkv-load/generated-relay](zkv-load/generated-relay). Regenerate its figure
with `replay_chart.py` using that directory as the first argument. The shared
`replay_report.py` exports numeric chart data directly from successful raw runs,
checks delivered/recovered/validated counts and cleanup, and preserves each
corpus hash. No Fly resources were created. All six owned projects were removed
and their container/network/volume absence checked again after the runs.