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

zat.dev/zlay

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

0
0
310 lines · 18.9 KB Raw History
# Scratch handoff: replacing RocksDB with zkv

Snapshot: 2026-11-06. This is a working handoff and project history, not a new
benchmark qualification or deployment instruction. Numbers below are dated
observations; production was not rechecked for this writing task.

## What we were trying to achieve

Make zlay work correctly, lightly and economically with
[zkv](https://tangled.org/zzstoatzz.io/zkv). Matching RocksDB on the relay's
relevant workload is sufficient; winning every isolated operation is not the
objective. The work was meant to iterate on zkv, not force its existing form
into zlay or preserve a migration merely because we had invested in it.

Constraints that must survive a handoff:

- Preserve correctness and zeldi compatibility. A zlay optimization must not
  regress zeldi; core changes need both consumers considered.
- Measure equivalent work: durability, maintenance, allocator, cache state,
  read refresh, returned contents and offered versus achieved load all matter.
- Prefer small offline experiments at home. Do not send bulk firehose traffic
  through the laptop or heavypad. Use short remote runs with resource/network
  limits only where the live network is necessary, and clean up disposable assets.
- Account for build time, executable size, memory, disk, tail latency, restart
  behavior and failure cases, not just commit latency.
- Keep project READMEs about their projects. This handoff is explicitly requested
  scratch/history; durable actionable work should become discrete issues.

## Where the migration landed

Production was converted to zkv on November 6. This replaces the collection
membership index, including its forward/reverse namespaces. PostgreSQL account
state and the replay event log were retained; they were not converted to zkv.

| Item | Recorded state |
|---|---|
| Core zkv pin | `90f72c80284269c7caef06b455c00b64ae0c8128` |
| Runtime | Zig 0.17, ReleaseSafe, lalinsky/zio, x86_64-linux-gnu, C allocator |
| Store | Local DirStore on the production PVC |
| Active index | `/data/collection-index-zkv-20261106/index` |
| Retained RocksDB index | `/data/collection-index` — frozen since cutover |
| Index policy | `RELAY_INDEX_PROFILE=bounded`, `ZKV_TABLE_ENCODING=legacy` |
| Replay | `/data/events`, two-hour retention, 30 GiB byte backstop |
| Current diagnostic image | `atcr.io/zzstoatzz.io/zlay:ReleaseSafe-zio-3b107c8` |
| Last observed pod | `zlay-79b89b6799-88mb8` |

Production uses legacy encoding. Grouped-prefix compression is an opt-in format,
not an optimization that has silently been enabled on the production index.

Repository state when this handoff was written:

- zlay main is `34cfc17`; the collection-index migration is already on main.
- `codex/bounded-proof-diagnostics` contains `2e78738` (capture/replay),
  `3b107c8` (allocation-failure hardening), and `f01b9d1` (separate signature
  reporting in the offline replay tool). The runtime uses the first two;
  the last is an offline-tool change. These diagnostics are not on main.
- The [ops repository](https://tangled.org/zzstoatzz.io/relay) main is
  `7b0d63c`; its values and changelog record the running diagnostic image.
- A diagnostics PR was not opened: `tg pr create` failed while resolving the
  owner's repository metadata with HTTP 404. The branch itself is pushed.

The authoritative operational account is the
[ops changelog](https://tangled.org/zzstoatzz.io/relay/blob/7b0d63c/docs/ops-changelog.md).
The original cutover evidence is in the ops repository's
`docs/incidents/2026-11-06-zlay-index-migration/` directory.

## How the engineering and measurements evolved

Early per-request and novel-membership comparisons exposed real write costs.
RocksDB amortizes work internally; our adapter and maintenance policy also had
to be considered. Independent pinned readers, explicit write ownership and
coalescing changed the relay integration. Maintenance serialized behind a
writer mutex was an implementation/design problem to investigate, not proof
that zkv could never serve the relay.

Several measurements were useful precisely because they rejected an approach
or exposed a confound:

- A destination-overlap compaction experiment reduced localized object traffic,
  but selecting individual source tables worsened other shapes. That experiment
  is historical and must not be assumed deployed from its presence in docs.
- Million-pair tests showed severe maintenance-related acknowledgement tails.
  Those historical timings also used `std.process.Init.gpa`/SafeAllocator,
  unlike production's `c_allocator`; RocksDB's C++ allocations took another
  path. They are not an allocator-matched production ranking.
- The finite offline relay harness reused atproto-bench's signed corpus reader,
  rather than inventing a PDS write generator. It exercised the real relay
  queues, verifier, index, event files, PostgreSQL, downstream checks and restart.
  It excluded upstream discovery/TLS and cold signing-key resolution.
- Tiny live VMs were often saturated as whole systems, and later comparisons
  hit network guards. Collector failures and incomplete windows invalidated
  some tempting coverage/capacity conclusions. Passing an individual stream
  checker did not establish full-network completeness.

Useful evidence entry points:

- [Finite offline relay replay](../../measurements/storage/zkv-relay-replay.md).
  All 3,300 signed inputs were checked, including memberships and restart replay.
  At 16 workers, the short 1,000/s cases completed in about 3.35–3.38 s with zkv
  versus 3.85–4.00 s with RocksDB. Neither sustained the offered 5,000/s burst
  under the tested caps. This is screening evidence, not sustained capacity.
- [Grouped live controls](../../measurements/storage/zkv-grouped-live.md).
  Mean index-call wall times were 8.57 ms grouped zkv, 8.63 ms legacy zkv and
  9.12 ms durable RocksDB on the same-size pilots. All windows hit the network
  guard; these numbers do not qualify sustained coverage or prove a read bottleneck.
- [Process-crash recovery](../../measurements/storage/zkv-owner-recovery.md).
  Nine finite SIGKILL/reopen cases preserved the recorded acknowledged prefix
  and request atomicity. This is not power-loss or PostgreSQL-cursor qualification.
- [Allocator/comptime investigation](https://tangled.org/zzstoatzz.io/zkv/blob/main/docs/benchmarks/allocators/allocator-comptime.md).
  zeldi's allocator growth policy and two-MiB table choice differ from zlay's.

The event-log flush watermark means a positional write completed, without an
fsync. Earlier descriptions of end-to-end completion as a durable event
acknowledgement were incorrect. Synchronous index writes are a separate guarantee.

## Disk format and build costs

The [grouped-prefix fixture](https://tangled.org/zzstoatzz.io/zkv/blob/main/docs/benchmarks/compression/grouped-prefix-results.md)
reduced a two-million-membership index from 282,982,632 to 160,299,041 bytes,
a 43.4% saving, close to the 159,929,409-byte RocksDB reference on that logical
fixture; that RocksDB reference had general-purpose compression disabled.
Removing an extra allocation retained that saving but did not eliminate
the read penalty: the repeated follow-up still showed about 16.5% more total
random-hit time and 7.3% more time in the actual relay page method. Measured SST
range bytes are not physical disk I/O; those runs had a warm OS page cache.
See the [allocation follow-up](https://tangled.org/zzstoatzz.io/zkv/blob/main/docs/benchmarks/compression/prefix-read-allocation.md).

The production disk snapshot after migration was about 2.96 GiB for the live zkv
index, 2.05 GiB for retained RocksDB, and 22.32 GiB for replay. The RocksDB copy
was frozen while zkv kept changing, so that snapshot is not a controlled storage
comparison. Replay growth must not be attributed to the KV index.

The [matched build sample](../../measurements/storage/zkv-build-footprint.md)
measured 91.55 s versus 213.10 s for a fresh-cache build and roughly 4.0 MB
versus 15.0 MB for stripped executables, zkv versus RocksDB. It was one paired
sample on an M5 Pro with downloaded dependencies and network denied, not a
compile-time distribution. Debug ELF file size is not runtime RSS. A later
normal stripped candidate was 4,067,912 bytes. Normal builds do not instantiate
RocksDB; the optional migration executable still links the historical library.

## Cutover, health and recovery

The initial conversion ran while production remained on RocksDB. During the
final stop, reconciliation applied 6,558 changed entries in 33.440 s and a full
comparison checked 45,348,686 entries in 32.403 s. External HTTP unavailability
was bounded at 170.019 s. The user allowed five minutes for the planned cutover
and longer recovery if necessary. The two-worker migration helper was used;
the later four-range prototype was not production-qualified or used.

One-hour observations after the original cutover included 99.5% raw observed
DID overlap, about 549 frames/s, 0.79 CPU cores, an empty current queue and no
restarts. Process RSS was about 1.86 GiB; container working set was 3.14 GiB
and included filesystem cache. Those are different memory measures. Compaction,
flush and log-GC counters advanced. Live consumption, ordered collection pages
and replay from a pre-cutover cursor were checked.

After the subsequent diagnostic rollout, a fresh 120-second remote evaluation
observed 22,311/22,316 DIDs (99.98%) and 63,196 events. The reference observed
99.6%. This is sample overlap, not a completeness or uninterrupted-connection
guarantee. The latest recorded queues were empty and the new pod had no restarts.
Startup evaluations were materially worse until catch-up drained.

Recovery material is retained on the production node under
`/opt/zlay-index-cutover-20261106`. Follow the
[ops recovery procedure](https://tangled.org/zzstoatzz.io/relay/blob/7b0d63c/docs/deploying.md#zlay-index-recovery)
and [migration commands](https://tangled.org/zat.dev/zlay/blob/0beb42a/docs/operations/index-migration.md).
A rollback to RocksDB must reconcile post-cutover writes and deletions back into
the retained directory and verify it. An image-only RocksDB rollback loses state.
Restoring the prior zkv image for a diagnostics-only problem is a different case:
it uses the same live zkv directory and format. Do not run a second writer.

## Current validation investigation

This became a separate investigation after migration; the evidence does not
establish that changing the storage engine caused the validation changes.

The observed Sync 1.1 burst reached about 0.7 failures/s in a one-minute rate
around 21:24–21:28 UTC on November 6, versus a preceding seven-day maximum near
0.055/s in the five-minute rate. Those are different rate windows. The earlier
five-minute burst measurement was about 0.43/s. `commit_integrity` and
`sync_1_1` can count the same failure; adding the lines double-counts it.
The original burst has not been attributed to a particular captured frame.

The Operations/errors panel is our inbound rate-limit wait counter, not an
upstream HTTP 429 counter or a count of dropped frames. Hourly waits were about
9/s. Decode errors remained near their pre-cutover 0.07/s. Sampled host-authority
rejections matched the public PLC endpoints. None of this resolves the proof burst.

The new capture is opt-in through `RELAY_PROOF_CAPTURE_DIR`, currently
`/data/proof-captures-20261106`. It keeps at most 16 files across restarts, each
with at most a two-MiB original frame plus bounded metadata. It deduplicates
DID/error pairs per process, skips contention/oversized inputs, and stops on
allocation or storage failure. Successful verification does no capture allocation
or I/O. Each packet records the source host, error and verification public key.

The offline tool is documented in [deployment guidance](../../operations/deployment.md#capturing-rejected-commit-proofs):

```sh
zig build proof-replay -Doptimize=ReleaseSafe
zig-out/bin/proof-replay /path/to/proof-0.cbor
```

At `f01b9d1` it checks CAR/signature validity separately from the proof path,
because operation parsing can fail before signature verification.

Actual evidence collected:

| Input | Observation |
|---|---|
| Production `proof-0.cbor`, 6,840 B, `us-chi1.cove.seamark.dev` | Signed update to `io.atcr.hold.stats` omits `ops[].prev` while carrying `prevData`; zlay reproduces `InvalidCommitDiff`. |
| Production `proof-1.cbor`, 8,613 B, `lionsmane.us-east.host.bsky.network` | Valid signature; zlay reproduces `DuplicatePath`; Indigo rejects the create-operation metadata. |
| Separate outgoing-stream shadow capture, DID `did:plc:26arqmnb4omdbgcxs6fzplaa`, rev `3mzoft5se6c2l` | Signed delete then create for the same post path, with `prev` on both operations. zlay reproduces `DuplicatePath`; Indigo rejects `invalid repoOp: create`. Original incoming host was not captured by this checker. |

Indigo's `repo.VerifyCommitMessage` was taken from commit
`e076b63ff34a010d47ed1bfe82c767b23c3a7eb6`. On the legacy update it returns
success after explicitly skipping inversion. That is not proof verification.
For the shadow duplicate-path case, replacing only the unsigned operation list
with one equivalent update made both zlay and Indigo pass while retaining the
original signed CAR. This control isolates operation-envelope semantics; it does
not establish that the original ordered operation sequence was invalid.

### What Hydrant changed about our interpretation

The user asked for a behavior comparison with
[Hydrant](https://tangled.org/ptr.pet/hydrant), not a new framework or deployment.
Current upstream was checked at `0d8c485a0e7d7e7c570574c8494bc0843a9deca0`;
the relevant validation code was unchanged from the existing local checkout.

[Hydrant's inverter](https://tangled.org/ptr.pet/hydrant/blob/0d8c485a0e7d7e7c570574c8494bc0843a9deca0/src/ingest/validation.rs):

- Reverses the original operation sequence rather than rejecting duplicate paths
  first. Delete then create can be inverted back to the old value.
- Skips an update/delete operation whose `prev` is absent, but still compares
  the resulting root with `prevData` when present. It does not unconditionally
  skip the entire proof as Indigo's legacy path does.
- Runs inversion when explicitly requested or when a signing key was supplied.

The [default relay key path](https://tangled.org/ptr.pet/hydrant/blob/0d8c485a0e7d7e7c570574c8494bc0843a9deca0/src/ingest/relay/context.rs)
waits for an unresolved key instead of forwarding unchecked. Its per-DID parked
queues are bounded (64 messages, two MiB per DID, 1,024 DIDs per shard, 30-second
hold deadline). zlay's current cache-miss path instead forwards unverified and
queues resolution. Consequently a zero failure counter after restart is not
evidence that the problem was fixed, and good DID overlap is not proof coverage.

An earlier conclusion that agreement between zlay and Indigo proved “bad upstream
metadata” was premature. Hydrant provides a materially different, ordered
interpretation. No production validation policy was changed in this investigation.

A custom local Rust harness was unnecessary scope. It used Hydrant's real decoder,
CAR, signature and MST modules, but substituted configuration and prior-state
container types with an empty prior state. It downloaded about 38 MB of pinned
Jacquard source and 1.4 MB of missing registry crates, then compiled with two jobs.
It had already finished before the attempted interruption: it accepted the legacy
production frame, the original shadow duplicate-path frame and its normalized
control. These are **experimental harness observations, not a qualified Hydrant
pipeline result**. Do not upgrade them into a production compatibility claim.
The user explicitly called out this overcomplication; work on that harness stopped.
Hydrant's source and production were not changed after the comparison request.

## Mistakes and limits to carry forward

- Keep cold-cache, cache-hit, object range-read and physical disk I/O claims distinct.
- Do not omit flush/compaction/collection from the workload and present the result
  as sustained engine performance. Do not infer relay throughput from a get microbenchmark.
- Do not compare unsynced RocksDB acknowledgements with synchronous zkv publication.
- Respect real allocator choices and distinguish worker-wall intervals from CPU time.
- Do not infer source completeness from contiguous relay sequence numbers, a
  `connected` flag, or a small live sample. Consumer overlap and proof coverage differ.
- The diagnostics required two production restarts, about 93 s each. The second
  corrected an allocation-failure bug introduced in the capture helper. This was
  avoidable additional disruption and was acknowledged to the user.
- The custom image build omitted the normal publisher's `--cache-poison=poisoned`.
  The runtime commit-label metric therefore incorrectly says `2e78738a` even though
  the image contains the `3b107c8` hardening. The live ELF was matched to SHA-256
  `327ebebf9e3aff31dee5907a7c59434ddead169c8f4f26539bd42d28893f232b`;
  the image manifest is
  `f4b3d88c9f29f2ecf9337ccf91cbc2b69d86e6150d9814835cd20cb054eb0ed4`.
  Use the normal publisher and recorded image/executable identity. No third restart
  was done just to repair the label.
- Do not turn a request to read another implementation into an elaborate test
  harness with substitute types. Source review should answer the question first.

## What a next session should do

Start with this handoff and the linked evidence. The current request is to stop
and record the journey, not to continue deployments or widen experiments.

1. Reconcile main/diagnostic-branch status before any later rollout. The branch is
   pushed, but a pushed commit is not a merged PR or a successful CI verdict.
2. Review the Hydrant behavior differences with the user before choosing a
   validation-policy change. Duplicate paths, missing proof fields and unresolved
   keys are three different questions. Do not silently weaken proof checking.
3. If continuing the error investigation, inspect the bounded production captures
   read-only. Preserve raw frames and keys; compare identical inputs and explicitly
   report skipped verification. The earlier burst remains unattributed.
4. Treat cache-miss forwarding and the duplicate-path rejection policy as concrete
   correctness/compatibility questions. Do not attribute them to zkv without evidence.
5. Retain reconciliation-based RocksDB recovery until there is an explicit decision
   to retire it. Do not delete the old index as an incidental cleanup.
6. Keep format/performance work separate from this validation detour. Grouped
   encoding still has a measured read cost and is not enabled in production.

Temporary investigation breadcrumbs (not durable evidence): laptop
`/tmp/zlay-proof-probe/`, `/tmp/zlay-proof-*-eval.txt`,
`/tmp/hydrant-proof-harness/`, and the detached source worktree
`/tmp/hydrant-current/`. A short-lived shadow checker ran on the existing eval
server with a one-CPU/384-MiB cap and stopped at its first candidate after about
76 s and 13 CPU-seconds. Its stream stayed remote. No new VM was created for this
latest investigation. Temporary files/dependencies should be inventoried before
cleanup; do not assume every previous artifact is still present.