# Independent readers for the zlay pilot The shared reader/writer mutex was a pilot integration choice. The adapter now uses zkv's existing independent reader and refresh APIs, with separate reader and writer mutexes. No engine change is justified by the lock-stall measurements. Further capacity comparisons remain gated on concurrency and runtime tests. ## Prior art and its application [RocksDB's compaction implementation](https://github.com/facebook/rocksdb/blob/main/db/db_impl/db_impl_compaction_flush.cc) releases the database mutex around the expensive compaction job and reacquires it for installation. Its [SuperVersion](https://github.com/facebook/rocksdb/blob/main/docs/components/read_flow/03_superversion_and_snapshots.md) bundles the read sources into retained state. [Pebble's readState](https://github.com/cockroachdb/pebble/blob/master/read_state.go) uses a separate short-held lock to acquire a reference to the current version and memtable list. Readers release that acquisition lock before performing the read. Reclamation waits for retained state to become unused. [SlateDB reads](https://slatedb.io/docs/design/reads/) select a snapshot and search memory, immutable memory and immutable files. Its [compactor](https://slatedb.io/docs/design/compaction/) separates scheduling and execution. These are examples of coordinating state publication separately from the expensive merge, not evidence that a background thread alone fixes reader blocking. [SILK, ATC 2019](https://www.usenix.org/system/files/atc19-balmau.pdf) studies interference between foreground work, flush and compaction, including priority, bandwidth scheduling and preemption. It also uses open-loop arrivals and includes queueing in latency. Eliminating the global lock is a prerequisite here; it does not establish that disk contention or CPU interference is solved. [cLSM, EuroSys 2015](https://webee.technion.ac.il/Sites/People/idish/ftp/clsm.pdf) addresses concurrent memory access and consistent scans. Sharing mutable zkv memtables between threads cannot be made safe simply by removing the pilot lock. ## What zkv already provides The existing reader owns its memtable, batch, cache and log state separately from the writer. Refresh replays complete committed log segments and adopts a changed manifest. An acknowledged commit preceding a new refresh must therefore be visible after successful refresh; staged writer changes are excluded. Independent readers do not register permanent file pins with the writer. Collection can remove a file a scan still needs. The README explicitly requires refreshing and retrying the scan. Point gets already retry a missing file once; scans expose the error to the caller. `reader_contract.zig` tests these existing APIs against actual local files. It checks both directions of a committed pair, excludes staged state, and forces an old-table scan to miss after compaction and collection. Closing the reader's cached file descriptors makes that last test independent of POSIX's ability to read an already-unlinked open file. Refresh and a scan from the original cursor then return every remaining key and value in order. ## Adapter contract under verification Separate DirStore and Db instances serve the writer and reader. Writer mutations remain serialized. Refresh and reads use the reader's own mutex and never acquire the writer mutex. Refresh precedes each externally visible read to preserve visibility of commits acknowledged before the call. A dedicated test holds the writer mutex and requires an acknowledged pair to be read independently. Build a complete output page before returning it. On `Missing`, discard that attempt, refresh and retry from the caller's original cursor. The adapter bounds retries to three attempts and returns an explicit error if no complete page can be obtained; never return a partial page or an empty result on failure. Refresh itself can retry manifest adoption, so bounded retry count alone does not prove a wall-time bound. Before integration, verify the interleaved and concurrent cases: collection mid-page, commits during refresh, writer fencing/reopen, failed refresh, reader shutdown, and backfill/resync ordering. A page may use a newer committed view after a retry, matching a fresh query's semantics; this does not provide a snapshot spanning separate pagination calls. ## std.Io and zio The initial main initialized lalinsky/zio for the relay backend but passed its separate Threaded pool Io to the entire collection index. The pilot now accepts a separate reader Io and wires the relay Io to reads, retaining Threaded Io for writes and maintenance. Old load tests still use threads; their results do not measure full zio scheduler behavior. zio can suspend file I/O without occupying an executor thread. A suspended fiber retains any mutex it holds. An independent reader avoids the writer's mutex dependency, while the runtime determines executor occupancy. The viable adapter must be tested with the actual runtime arrangement, including executor responsiveness during compaction and CPU-heavy merge work. Merely changing the Io argument is not a concurrency correctness proof. All changes and tests in this stage are in the isolated zlay worktree. zkv and zeldi remain unchanged. Any later engine proposal requires separate zeldi compatibility and workload evidence before adoption. ## Runtime probe `zig build index-runtime -Doptimize=ReleaseSafe` builds a finite, network-free probe. Give `zig-out/bin/index-runtime` a disposable scratch directory. It uses one zio executor, a native thread holding the reader mutex for 200 ms, a reader fiber, and an unrelated 10 ms timer fiber. Both reader configurations must return the acknowledged pair. The Threaded-Io control must delay the timer by at least 150 ms; the zio-Io reader must let it complete within 100 ms. These loose bounds check executor blocking, not a production latency SLO. Three sequential native Apple M5 Pro ReleaseSafe runs of the extended owner probe gave timer completions of 210–211 ms for Threaded reader Io and 10–11 ms for zio reader Io. The zio-path write acknowledgement took 1–2 ms. The [raw observations](zkv-runtime-native.csv) are not relay capacity measurements. The production-target Linux zio relay build also passes. Linux runtime execution and broader workload measurements remain gates. ## Ordered write owner The pilot main enables one native write owner: up to 16 requests per batch, 64 total unacknowledged requests, and a 1 ms aggregation window. Requests can contain a live frame, a backfill page, paired updates or a replacement. The window is not an end-to-end latency bound; service time and earlier work add to it. Existing frame and page size limits still determine bytes per request. All public mutations use the same admission path. Keys are validated before queue admission. Each request borrows its input until its caller's uncancelable completion wait returns; the owner stages/copies keys before signalling that completion. The index and owner must remain at stable addresses after enabling batching, and producers must stop before index destruction. The owner preserves accepted queue order, including replacements mixed with live updates. Its batch is one database transaction. A replacement therefore sees membership staged by earlier requests in that batch. Shutdown drains accepted requests; overflow and requests after close return errors. The owner uses the reader/relay Io for queue synchronization and completion signals, and the Threaded writer Io for database work. The owner can skip aggregation delay when its first request is already known or has no index effects. This check runs on the owner thread and obeys queue order; it is not a reader-side shortcut that can overtake a pending replacement. The generic owner remains usable without that policy. Unit tests cover mixed live/backfill/replacement order, staged replacement semantics, drain and reopen, known-member delay bypass, and a real filesystem obstacle causing maintenance failure through the owner. Live index errors now propagate through frame processing: pooled workers complete their receipt as failed, preventing the existing completed-prefix cursor from advancing past that frame. Backfill submits and waits for a page before its cursor update. The runtime probe additionally submits a live frame with a heap-backed path, which is freed when the call returns, then verifies its indexed membership. It checks that this write completes without waiting for the held reader mutex. Updated raw observations include the write acknowledgement time. ## Resync snapshot boundaries The owner now guards the single resync worker's active DID with a bounded, in-memory token. Mutations for other DIDs do not invalidate it. Live frames, including ones whose membership was already known, mark it changed. Explicit membership deletion or replacement additionally marks it destructive. A quiet snapshot replaces memberships atomically. If additions or live frames arrived during the fetch, the snapshot contributes additions while preserving current membership, and the resync worker queues another attempt before pruning. This lets a busy DID gain previously unknown collections without discarding observed live updates. If a destructive mutation intervened, the snapshot is superseded and cannot resurrect removed membership. Cancellation and stale tokens cannot clear a newer guard. Failed HTTP/JSON work releases its token. The guard adds no persistent index keys and no extra commit for ordinary frames. The parser requires an explicit collections array and the expected DID. Missing, null or mismatched data cannot be interpreted as an authoritative empty repo. Tests use real index storage, both direct and owner paths, and cover additions, known-pair writes, unrelated DIDs, explicit deletion, convergence on a later quiet snapshot, canceled tokens and malformed snapshots. This protection addresses local fetch/write interleavings. The [official describeRepo schema](https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/repo/describeRepo.json) returns collections but no repository revision tying them to a particular commit. As with the original relay, a quiet response is treated as authoritative; this is not a cryptographic or version-bound source snapshot guarantee. The [getLatestCommit schema](https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/sync/getLatestCommit.json) provides CID and revision separately, but separate endpoint responses alone do not prove that describeRepo used that revision. The audit must distinguish this pre-existing source limitation from committed-read visibility and avoid claiming that FIFO order solves it. Remaining gates include end-to-end cursor/failure tests, recovery with batching and independent readers, and remote workload qualification using actual zio reader scheduling and upstream backpressure.