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

zat.dev/zlay

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

0
0
182 lines · 9.9 KB Raw History
# Why novel collection pairs cost more

The current pilot puts one durable immutable-file publication on the relay's
critical path for each frame containing a novel collection/DID pair. Production
RocksDB normally appends a buffered WAL record. That semantic difference explains
part of the gap; APFS hard-link publication explains much of the remainder on
this machine. This does not establish a production Linux throughput ceiling.

## What the relay actually does

`frame_worker.zig` calls `trackCommitOps` after validation and before
`DiskPersist.persist`, resequencing and broadcast. The fallback subscriber also
calls the index synchronously. This is a collection-membership index: create and
update establish membership; deleting one record does not establish that the
collection is empty. It is not one indexed entry for every live record.

The existing RocksDB adapter writes both column families in one WriteBatch per
relevant record operation. The binding defaults to `sync=false`,
`disable_wal=false`: WAL enabled, no forced sync per write. Its memtable handles
immediate reads; later flushes create SSTs and compaction merges them. It does not
publish an immutable file for each WriteBatch. The relay event log also buffers
events before asynchronous flushing. A synced index commit before that buffered
event append imposes an additional barrier; it does not make the whole relay
transaction atomic.

The pilot skips a pair only when both directions already exist, batches a
frame's operations, then calls zkv commit. `seglog.zig` publishes a new numbered
segment through `putIfAbsent`. `DirStore.stage` creates and writes a temporary
file and calls `fsync`; conditional publication hard-links it to the final name,
syncs the parent directory and unlinks the temporary name. Conditional publication
is part of the log protocol, not incidental file copying. The pilot also runs
flush/compaction/collection at 256 segments or 4 MiB while holding its mutex.

Relevant sources: [frame worker](../../../src/internal/frame_worker.zig),
[event log](../../../src/internal/event_log.zig), [pilot adapter](../../../src/internal/collection_index/index.zig),
[zkv DirStore](../../../../../zzstoatzz.io/zkv/src/store/dir.zig),
[zkv seglog](../../../../../zzstoatzz.io/zkv/src/seglog.zig).
RocksDB baseline is worktree `../zlay-zkv-pilot`, based on `f3346e9`; its benchmark
adds only an explicit sync control. The cached rocksdb-zig `WriteOptions` defaults
are in `src/database.zig` lines 414–425.

## Actual adapter phase measurements

Apple M5 Pro, macOS, native ReleaseSafe, local scratch directories; three fresh
runs of 8,192 novel pairs. Wall-clock instrumentation wraps the actual adapter
commit/maintenance and DirStore operations. Percentages are medians of each run's
share; they are nested measurements and should not all be summed.

| Component | Share of total novel-pair time |
|---|---:|
| Commit, including segment publication | 87.8% |
| Flush, compaction and collection | 12.0% |
| Hard-link publication within commit/maintenance | 55.5% |
| Directory/temp-file creation | 12.2% |
| Temporary-file cleanup | 7.5% |
| File sync | 5.8% |
| Parent open/sync | 3.1% |
| File write | 2.5% |
| File close | 0.6% |

Temporary source-copy ablations change exactly one policy; no library or adapter
policy was changed in the pilot. Sync-disabled rows provide causal diagnostics,
not equivalent durability or migration candidates.

| Diagnostic variant | µs per novel pair |
|---|---:|
| Instrumented baseline | 467.09 |
| Skip file sync | 436.38 |
| Skip parent sync | 472.51 |
| Skip both syncs | 443.28 |
| Skip maintenance | 408.88 |

Removing sync alone does not remove the Mac gap. Removing maintenance helps but
leaves most of it. Small differences, including the parent-sync inversion, are
noise rather than evidence that sync accelerates writes. Initial profiling
partly overlapped compilation of the corpus harness; use the large effects and
phase attribution, not percent-level variant rankings. The source-copy script
asserts every replacement site and the benchmark verifies its index contents.

## Filesystem mechanism probe

A separate C probe writes 512 160-byte records, reads all payloads back, and
checks that both hard-link publication and atomic no-replace rename refuse an
existing destination without changing either file. Three runs rotate mode order.
It compares mechanisms, not full engines or full crash recovery protocols.

| Mechanism | macOS µs/record | Linux Docker volume µs/record |
|---|---:|---:|
| Buffered append | 2.02 | 0.84 |
| Append, sync each record | 28.91 | 1,677.22 |
| Append, sync each 64 records | 2.57 | 43.34 |
| New file + hard link, no sync | 363.06 | 26.85 |
| New file + hard link, file and parent sync | 392.40 | 4,477.87 |
| New file + no-replace rename, no sync | 143.31 | 27.65 |
| New file + no-replace rename, file and parent sync | 163.06 | 4,405.36 |

Linux is ARM64 Debian in the existing local Docker VM, using an ephemeral named
volume, not a macOS bind mount. Network was disabled. Its storage stack is not
the production server's disk; these absolute latencies are not forecasts. The
ranking change is the useful result: APFS hard links are costly here, whereas
sync dominates the Linux volume. Rename is promising for the local backend on
Mac, but cannot be assumed to solve Linux writes. Collision and payload checks
do not substitute for crash-injection tests, cross-platform API support, or
proof that the full publication protocol is preserved. macOS measurements use
POSIX `fsync`, as Zig's Threaded backend does, not `F_FULLFSYNC`.

## Captured frame replay

The existing local atproto-bench `firehose-frames.bin` has 3,160 commit frames,
16,940,124 bytes and 2,588 distinct collection/DID pairs. Its SHA-256 and full
summary are in [corpus-summary.json](zkv-diagnostics/corpus-summary.json).
There are 3,122 creates, 16 updates and 79 deletes. Distinct relevant pairs per
frame: 64 frames have zero, 3,072 have one, 21 have two and three have three.
Starting empty, 599 frames introduce no new pair.

`index-corpus` decodes before timing, calls the actual `trackCommitOps` path,
then checks all expected forward pairs through cursor pagination, reverse
membership and the known-collection count after every pass. It repeats the same
frames three more times. These are index-only service times, not end-to-end
relay latency: validation, networking, event persistence and queueing are excluded.
Three independent scratch databases per engine use identical decoded work.
Cold means empty index, not evicted filesystem caches. Warm means all pairs
already known, not an assumed production mixture.

| Adapter | Empty-index replay, ms | Repeated replay, ms |
|---|---:|---:|
| rocks | 15.77 | 17.65 |
| rocks-sync | 99.40 | 104.32 |
| zkv | 1166.50 | 2.53 |

The fixture's event timestamps span May 23–June 1, 2026, so it is not evidence of
a contiguous arrival rate. Neither these replay times nor the cold unique-pair
fraction establishes production novelty or queue headroom. Warm speed includes
the pilot's deliberate duplicate-elision optimization; it is not proof that
zkv's underlying write engine is faster. Batch boundaries also differ: the
pilot batches within a frame, the current RocksDB adapter writes per operation.
Almost every relevant frame has one pair, limiting that distinction here.

## Interpretation and next experiments

There is no evidence here that serialization or the in-memory key algorithm is
the main novel-pair bottleneck. The dominant measured Mac cost is file lifecycle
and publication. The extra durable barrier is a semantic choice; one immutable
object per unbatched commit follows zkv's log design. The local hard-link
implementation is an optimization opportunity. The relay's synchronous,
serialized call site amplifies either cost into frame-worker blocking.

Before choosing a migration, measure novel-pair counts and write batches from a
bounded, representative relay workload without exporting record payloads. Run
fixed-arrival-rate replay over a range of novelty fractions with the complete
RocksDB and zkv maintenance paths, reporting backlog and worker stalls as well
as latency. The existing closed-loop benchmark cannot answer that question.

A bounded single-owner batch across frames is the strongest next pilot: it can
amortize zkv's durable publication while preserving per-batch durability. Measure
1/8/64 pairs and a maximum waiting-time bound; prove shutdown draining, backfill
cursor ordering, resync exclusion, write failure and restart behavior. A
frame-only batch is insufficient for this capture. Do not silently turn off sync
to reproduce RocksDB's numbers, or acknowledge upstream progress ahead of a
recoverable index boundary.

For zkv, ask first for a tested local no-replace publication optimization and
explicit documentation of the durability/publication contract. Evaluate the
existing pluggable log boundary and shared/group commit before requesting a new
storage design. If acceptable bounded batches still cause queue growth or
unacceptable reader stalls on representative Linux storage, retain RocksDB for
this index. An object-store-first engine need not become a RocksDB clone to
serve this one workload. These experiments changed no production code or data.

## Reproduction

Build `index-corpus -Doptimize=ReleaseSafe` in both pilot worktrees. Run
`scripts/zkv/run_corpus.py CORPUS ROCKS_BINARY ZKV_BINARY` for cold and repeated
frame replay; the RocksDB control accepts `--sync`. Use the existing
atproto-bench Python environment for `scripts/zkv/corpus_summary.py CORPUS`.
Run `python3 scripts/zkv/profile_index.py` for asserted disposable source-copy
instrumentation/ablations. Run `python3 scripts/zkv/run_publication_probe.py` for
native and Linux-volume mechanisms; the latter requires the cached Debian image
and Docker. No command captures live traffic or starts a relay.

Raw observations: [profile](zkv-diagnostics/profile.csv),
[publication](zkv-diagnostics/publication.csv), [corpus](zkv-diagnostics/corpus.csv).