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

zat.dev/zlay

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

0
0
1851 lines · 81.5 KB Raw History
//! collection index — tracks which collections exist per repo
//!
//! Two ordered namespaces in one atomic batch: rbc and cbr.

const std = @import("std");
const zkv = @import("zkv");
const zat = @import("zat");
const owner_mod = @import("batch_owner.zig");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const BackgroundWriter = struct {
    inner: zkv.DirStore,
    writes: usize = 0,
    elapsed_ns: i96 = 0,

    pub fn put(self: *BackgroundWriter, key: []const u8, bytes: []const u8) !void {
        const started = Io.Clock.awake.now(self.inner.io).nanoseconds;
        defer {
            self.writes += 1;
            self.elapsed_ns += Io.Clock.awake.now(self.inner.io).nanoseconds - started;
        }
        try self.inner.put(key, bytes);
    }
};
const Store = zkv.AsyncStore(zkv.DirStore, BackgroundWriter);
const Db = zkv.Db(Store);
const ReaderStore = zkv.DirStoreWithHandles(32);
const ReadDb = zkv.Db(ReaderStore);
const log = std.log.scoped(.collection_index);
const separator = '\x00';
const rbc = "\x01";
const cbr = "\x02";

const IndexPair = struct { did: []const u8, collection: []const u8 };
const ResyncGuard = struct { did: [128]u8, len: usize, token: u64, changed: bool, destructive: bool };
const SnapshotResult = enum { replaced, merged, superseded };
const Mutation = union(enum) {
    pair: struct { pair: IndexPair, delete: bool },
    pairs: []const IndexPair,
    page: struct { dids: []const []const u8, collection: []const u8, delete: bool = false },
    replace: struct { did: []const u8, collections: []const []const u8 },
    frame: struct { did: []const u8, ops: zat.cbor.Value },
    guarded_replace: struct { did: []const u8, collections: []const []const u8, token: u64, applied: *SnapshotResult },
};

pub const CollectionIndex = struct {
    const WriteOwner = owner_mod.OwnerWithMaintenance(@This(), Mutation, applyMutations, mayDelay, maintainAfterAck);
    const PageQuery = struct {
        collection: []const u8,
        limit: usize,
        cursor: ?[]const u8,
        bytes: []u8,
        offsets: []Span,
        result: *ListResult,
    };
    const PageOwner = owner_mod.Owner(@This(), PageQuery, readPages);
    pub const MaintenancePolicy = struct {
        max_segments: u64 = 256,
        step_bytes: usize = 0,
        max_memtable_bytes: usize = 4 << 20,
        log_gc_names: usize = 0,
    };
    maintenance_policy: MaintenancePolicy = .{},
    write_owner: ?*WriteOwner = null,
    page_owner: ?*PageOwner = null,
    maintenance_after_ack: bool = false,
    background_writes: bool = false,
    log_collector: Db.LogCollector = .{},
    log_gc_pending: bool = false,
    maintenance_detail: struct {
        changed_commits: usize = 0,
        flushed_bytes: usize = 0,
        flushed_segments: u64 = 0,
        flush_ns: i96 = 0,
        compact_ns: i96 = 0,
        collect_ns: i96 = 0,
        collect_max_ns: i96 = 0,
        log_gc_steps: usize = 0,
        log_gc_max_ns: i96 = 0,
        compactions: usize = 0,
        compaction_steps: usize = 0,
        pending_polls: usize = 0,
    } = .{},
    maintenance_runs: usize = 0,
    maintenance_ns: i96 = 0,
    maintenance_max_ns: i96 = 0,
    resync_counter: u64 = 0,
    resync_guard: ?ResyncGuard = null,
    db: *Db,
    store: *zkv.DirStore,
    maintenance_store: *BackgroundWriter,
    async_store: *Store,
    read_db: *ReadDb,
    read_store: *ReaderStore,
    read_mutex: Io.Mutex = .init,
    read_io: Io,
    allocator: Allocator,
    io: Io,
    mutex: Io.Mutex = .init,
    failed: std.atomic.Value(bool) = .init(false),

    /// Both handles keep one fence key in 32 resident per table and fetch
    /// the rest through the block cache: with every fence resident, the
    /// 2026-11-08 index (2,595 tables, 22.8 GB) pinned about 1 GB per
    /// handle. The cache is wider than zkv's 1 MiB default so fence
    /// partitions and data blocks do not evict each other on every page.
    const db_options: zkv.Options = .{ .fence_stride = 32, .cache_bytes = 64 << 20 };

    pub fn open(allocator: Allocator, io: Io, data_dir: []const u8) !CollectionIndex {
        return openWithReaderIo(allocator, io, io, data_dir);
    }

    pub fn openWithReaderIo(allocator: Allocator, io: Io, read_io: Io, data_dir: []const u8) !CollectionIndex {
        var dir = try Io.Dir.cwd().createDirPathOpen(io, data_dir, .{ .open_options = .{ .iterate = true } });
        errdefer dir.close(io);
        // Refuse a RocksDB directory.
        if (dir.access(io, "CURRENT", .{})) |_| {
            return error.ExistingRocksDB;
        } else |err| if (err != error.FileNotFound) return err;
        const store = try allocator.create(zkv.DirStore);
        errdefer allocator.destroy(store);
        store.* = .init(allocator, io, dir);
        errdefer store.deinit();
        const maintenance_dir = try dir.openDir(io, ".", .{ .iterate = true });
        errdefer maintenance_dir.close(io);
        const maintenance_store = try allocator.create(BackgroundWriter);
        errdefer allocator.destroy(maintenance_store);
        maintenance_store.* = .{ .inner = .init(allocator, io, maintenance_dir) };
        errdefer maintenance_store.inner.deinit();
        const async_store = try allocator.create(Store);
        errdefer allocator.destroy(async_store);
        async_store.* = .init(io, store, maintenance_store);
        errdefer async_store.deinit();
        const db = try Db.open(allocator, async_store, db_options);
        errdefer db.close();
        const read_dir = try dir.openDir(read_io, ".", .{ .iterate = true });
        errdefer read_dir.close(read_io);
        const read_store = try allocator.create(ReaderStore);
        errdefer allocator.destroy(read_store);
        read_store.* = .init(allocator, read_io, read_dir);
        errdefer read_store.deinit();
        const read_db = try ReadDb.openReader(allocator, read_store, db_options);
        return .{ .db = db, .store = store, .maintenance_store = maintenance_store, .async_store = async_store, .read_db = read_db, .read_store = read_store, .read_io = read_io, .allocator = allocator, .io = io };
    }

    pub fn memoryUsage(self: *CollectionIndex) ?struct {
        blocks: usize,
        memtable: usize,
        resident_meta: usize,
        unflushed_segments: u64,
        l0_tables: usize,
        compaction_active: bool,
        changed_commits: usize,
        flushed_segments: u64,
        compaction_steps: usize,
        log_gc_steps: usize,
    } {
        if (!self.mutex.tryLock()) return null;
        defer self.mutex.unlock(self.io);
        if (!self.read_mutex.tryLock()) return null;
        defer self.read_mutex.unlock(self.read_io);
        return .{ .blocks = self.db.cache.bytes + self.read_db.cache.bytes, .memtable = self.db.memtableBytes(), .resident_meta = self.db.residentMetadataBytes() + self.read_db.residentMetadataBytes(), .unflushed_segments = self.db.unflushedSegments(), .l0_tables = self.db.version.tables[0].len, .compaction_active = self.db.compaction != null, .changed_commits = self.maintenance_detail.changed_commits, .flushed_segments = self.maintenance_detail.flushed_segments, .compaction_steps = self.maintenance_detail.compaction_steps, .log_gc_steps = self.maintenance_detail.log_gc_steps };
    }

    pub fn deinit(self: *CollectionIndex) void {
        if (self.write_owner) |owner| {
            owner.close();
            self.async_store.cancelPut();
            self.allocator.destroy(owner);
        }
        if (self.page_owner) |owner| {
            owner.close();
            self.allocator.destroy(owner);
        }
        self.read_db.close();
        self.read_store.deinit();
        self.read_store.dir.close(self.read_io);
        self.allocator.destroy(self.read_store);
        self.log_collector.deinit(self.allocator);
        self.db.close();
        self.async_store.deinit();
        self.allocator.destroy(self.async_store);
        self.maintenance_store.inner.deinit();
        self.maintenance_store.inner.dir.close(self.io);
        self.allocator.destroy(self.maintenance_store);
        self.store.deinit();
        self.store.dir.close(self.io);
        self.allocator.destroy(self.store);
    }

    fn lock(self: *CollectionIndex) !void {
        self.mutex.lockUncancelable(self.io);
        if (self.failed.load(.acquire)) {
            self.mutex.unlock(self.io);
            return error.IndexUnavailable;
        }
    }

    fn lockReader(self: *CollectionIndex) !void {
        self.read_mutex.lockUncancelable(self.read_io);
        if (self.failed.load(.acquire)) {
            self.read_mutex.unlock(self.read_io);
            return error.IndexUnavailable;
        }
    }

    fn commit(self: *CollectionIndex) !void {
        self.db.commit() catch |err| {
            self.failed.store(true, .release);
            return err;
        };
        self.maintenance_detail.changed_commits += 1;
        if (!self.maintenance_after_ack) _ = try self.maintain();
    }

    fn maintainAfterAck(self: *CollectionIndex) owner_mod.Maintenance {
        if (!self.maintenance_after_ack) return .idle;
        self.lock() catch return .idle;
        defer self.mutex.unlock(self.io);
        return self.maintain() catch |err| {
            self.failed.store(true, .release);
            log.warn("collection index deferred maintenance failed: {t}", .{err});
            return .idle;
        };
    }

    fn compactMaintenance(self: *CollectionIndex) !zkv.CompactionProgress {
        if (self.background_writes) return self.db.compactPoll(self.maintenance_policy.step_bytes);
        return if (try self.db.compactStep(self.maintenance_policy.step_bytes)) .progress else .idle;
    }

    fn collectMaintenance(self: *CollectionIndex) !void {
        if (self.maintenance_policy.log_gc_names == 0) return self.db.collect();
        try self.db.collectTables();
        self.log_gc_pending = true;
    }

    fn maintain(self: *CollectionIndex) !owner_mod.Maintenance {
        var worked = false;
        var waiting = false;
        if (self.db.unflushedSegments() >= self.maintenance_policy.max_segments or self.db.memtableBytes() >= self.maintenance_policy.max_memtable_bytes) {
            worked = true;
            const maintenance_started = Io.Clock.awake.now(self.io).nanoseconds;
            defer {
                const elapsed = Io.Clock.awake.now(self.io).nanoseconds - maintenance_started;
                self.maintenance_runs += 1;
                self.maintenance_ns += elapsed;
                self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
            }
            const flush_started = Io.Clock.awake.now(self.io).nanoseconds;
            self.maintenance_detail.flushed_bytes += self.db.memtableBytes();
            self.maintenance_detail.flushed_segments += self.db.unflushedSegments();
            self.db.flush() catch |err| {
                self.failed.store(true, .release);
                log.warn("collection index flush failed: {t}", .{err});
                return err;
            };
            const compact_started = Io.Clock.awake.now(self.io).nanoseconds;
            self.maintenance_detail.flush_ns += compact_started - flush_started;
            while (self.maintenance_policy.step_bytes == 0 and (self.db.compact() catch |err| {
                self.failed.store(true, .release);
                log.warn("collection index compaction failed: {t}", .{err});
                return err;
            })) {
                self.maintenance_detail.compactions += 1;
            }
            const collect_started = Io.Clock.awake.now(self.io).nanoseconds;
            self.maintenance_detail.compact_ns += collect_started - compact_started;
            self.collectMaintenance() catch |err| {
                self.failed.store(true, .release);
                log.warn("collection index collection failed: {t}", .{err});
                return err;
            };
            const collect_elapsed = Io.Clock.awake.now(self.io).nanoseconds - collect_started;
            self.maintenance_detail.collect_ns += collect_elapsed;
            self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, collect_elapsed);
        }
        if (self.maintenance_policy.step_bytes > 0) {
            if (comptime @hasDecl(Db, "compactStep")) {
                const started = Io.Clock.awake.now(self.io).nanoseconds;
                const progress = self.compactMaintenance() catch |err| {
                    self.failed.store(true, .release);
                    return err;
                };
                const elapsed = Io.Clock.awake.now(self.io).nanoseconds - started;
                self.maintenance_detail.compact_ns += elapsed;
                if (progress != .idle) {
                    worked = worked or progress != .waiting;
                    waiting = progress == .waiting;
                    if (progress == .waiting) self.maintenance_detail.pending_polls += 1 else self.maintenance_detail.compaction_steps += 1;
                    self.maintenance_runs += 1;
                    self.maintenance_ns += elapsed;
                    self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
                    if (progress != .waiting and self.maintenance_after_ack and self.db.compaction == null) {
                        const collect_started = Io.Clock.awake.now(self.io).nanoseconds;
                        try self.collectMaintenance();
                        const collect_elapsed = Io.Clock.awake.now(self.io).nanoseconds - collect_started;
                        self.maintenance_detail.collect_ns += collect_elapsed;
                        self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, collect_elapsed);
                        self.maintenance_ns += collect_elapsed;
                        self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed + collect_elapsed);
                    }
                }
            } else return error.SteppedCompactionUnavailable;
        }
        if (self.log_gc_pending) {
            const started = Io.Clock.awake.now(self.io).nanoseconds;
            const applied = if (self.log_collector.names != null) self.log_collector.applied else self.db.version.applied;
            const more = self.db.collectLogStep(&self.log_collector, self.maintenance_policy.log_gc_names) catch |err| {
                self.failed.store(true, .release);
                return err;
            };
            self.log_gc_pending = more or self.db.version.applied > applied;
            const elapsed = Io.Clock.awake.now(self.io).nanoseconds - started;
            self.maintenance_detail.log_gc_steps += 1;
            self.maintenance_detail.log_gc_max_ns = @max(self.maintenance_detail.log_gc_max_ns, elapsed);
            self.maintenance_detail.collect_ns += elapsed;
            self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, elapsed);
            self.maintenance_runs += 1;
            self.maintenance_ns += elapsed;
            self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
            worked = true;
        }
        return if (worked) .progress else if (waiting) .waiting else .idle;
    }

    pub const Pair = IndexPair;
    pub const BatchOptions = struct {
        max_batch: usize = 16,
        queue_limit: usize = 64,
        delay_ns: i96 = 1_000_000,
        maintenance_after_ack: bool = false,
        background_writes: bool = false,
    };

    pub fn enableBatching(self: *CollectionIndex, options: BatchOptions) !void {
        if (self.write_owner != null) return error.AlreadyStarted;
        if (options.background_writes and (!options.maintenance_after_ack or self.maintenance_policy.step_bytes == 0)) return error.InvalidBatchPolicy;
        const owner = try self.allocator.create(WriteOwner);
        errdefer self.allocator.destroy(owner);
        owner.* = .{ .context = self, .io = self.read_io, .max_batch = options.max_batch, .queue_limit = options.queue_limit, .delay_ns = options.delay_ns };
        self.maintenance_after_ack = options.maintenance_after_ack;
        errdefer self.maintenance_after_ack = false;
        self.background_writes = options.background_writes;
        errdefer self.background_writes = false;
        if (options.background_writes) self.async_store.notify = .{ .context = owner, .call = wakeMaintenance };
        errdefer self.async_store.notify = null;
        try owner.start();
        self.write_owner = owner;
    }

    fn wakeMaintenance(context: *anyopaque) void {
        const owner: *WriteOwner = @ptrCast(@alignCast(context));
        owner.wakeMaintenance();
    }

    fn submitMutation(self: *CollectionIndex, mutation: Mutation) !void {
        try validateMutation(mutation);
        if (self.write_owner) |owner| {
            var request: WriteOwner.Request = .{ .item = mutation };
            try owner.submit(&request);
            request.done.waitUncancelable(self.read_io);
            try request.outcome;
        } else {
            try self.applyMutations(&.{mutation});
        }
    }

    fn mayDelay(self: *CollectionIndex, mutation: Mutation) bool {
        self.lock() catch return false;
        defer self.mutex.unlock(self.io);
        return switch (mutation) {
            .frame => |frame| blk: {
                const items = switch (frame.ops) {
                    .array => |items| items,
                    else => break :blk false,
                };
                for (items) |op| {
                    const action = op.getString("action") orelse continue;
                    if (!std.mem.eql(u8, action, "create") and !std.mem.eql(u8, action, "update")) continue;
                    const path = op.getString("path") orelse continue;
                    const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
                    if (slash == 0) continue;
                    if (!(self.knownPair(frame.did, path[0..slash]) catch return true)) break :blk true;
                }
                break :blk false;
            },
            .pair => |item| item.delete or !(self.knownPair(item.pair.did, item.pair.collection) catch return true),
            .pairs => |pairs| blk: {
                for (pairs) |pair| if (!(self.knownPair(pair.did, pair.collection) catch return true)) break :blk true;
                break :blk false;
            },
            .page => |page| blk: {
                if (page.delete) break :blk true;
                for (page.dids) |did| if (!(self.knownPair(did, page.collection) catch return true)) break :blk true;
                break :blk false;
            },
            .replace, .guarded_replace => true,
        };
    }

    fn knownPair(self: *CollectionIndex, did: []const u8, collection: []const u8) !bool {
        const forward = try makeKey(self.allocator, rbc, collection, did);
        defer self.allocator.free(forward);
        const reverse = try makeKey(self.allocator, cbr, did, collection);
        defer self.allocator.free(reverse);
        return (try self.db.get(forward)) != null and (try self.db.get(reverse)) != null;
    }

    fn applyMutations(self: *CollectionIndex, mutations: []const Mutation) anyerror!void {
        try self.lock();
        defer self.mutex.unlock(self.io);
        errdefer self.discard();
        for (mutations) |mutation| switch (mutation) {
            .pair => |item| try self.stagePair(item.pair.did, item.pair.collection, item.delete),
            .pairs => |pairs| for (pairs) |pair| {
                try self.stagePair(pair.did, pair.collection, false);
            },
            .page => |page| for (page.dids) |did| {
                try self.stagePair(did, page.collection, page.delete);
            },
            .replace => |replacement| {
                try self.stageRemoveAll(replacement.did);
                for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
            },
            .frame => |frame| try self.stageCommitOps(frame.did, frame.ops),
            .guarded_replace => |replacement| {
                replacement.applied.* = .superseded;
                if (self.resync_guard) |guard| {
                    if (guard.token == replacement.token and std.mem.eql(u8, guard.did[0..guard.len], replacement.did)) {
                        if (!guard.changed) {
                            try self.stageRemoveAll(replacement.did);
                            for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
                            replacement.applied.* = .replaced;
                        } else if (!guard.destructive) {
                            for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
                            replacement.applied.* = .merged;
                        }
                        self.resync_guard = null;
                    }
                }
            },
        };
        if (self.db.stagedBytes() != 0) try self.commit();
    }

    fn validateKey(key: []const u8) !void {
        if (key.len == 0 or std.mem.indexOfScalar(u8, key, separator) != null) return error.InvalidIndexKey;
    }

    fn validateMutation(mutation: Mutation) !void {
        switch (mutation) {
            .pair => |item| {
                try validateKey(item.pair.did);
                try validateKey(item.pair.collection);
            },
            .pairs => |pairs| for (pairs) |pair| {
                try validateKey(pair.did);
                try validateKey(pair.collection);
            },
            .page => |page| {
                try validateKey(page.collection);
                for (page.dids) |did| try validateKey(did);
            },
            .replace => |replacement| {
                try validateKey(replacement.did);
                for (replacement.collections) |collection| try validateKey(collection);
            },
            .guarded_replace => |replacement| {
                try validateKey(replacement.did);
                for (replacement.collections) |collection| try validateKey(collection);
            },
            .frame => |frame| {
                const items = switch (frame.ops) {
                    .array => |items| items,
                    else => return,
                };
                for (items) |op| {
                    const action = op.getString("action") orelse continue;
                    if (!std.mem.eql(u8, action, "create") and !std.mem.eql(u8, action, "update")) continue;
                    const path = op.getString("path") orelse continue;
                    const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
                    if (slash == 0) continue;
                    try validateKey(frame.did);
                    try validateKey(path[0..slash]);
                }
            },
        }
    }

    pub fn addPairs(self: *CollectionIndex, pairs: []const Pair) !void {
        try self.submitMutation(.{ .pairs = pairs });
    }

    fn stagePair(self: *CollectionIndex, did: []const u8, collection: []const u8, delete: bool) !void {
        self.noteMutation(did, delete);
        if (did.len == 0 or collection.len == 0 or
            std.mem.indexOfScalar(u8, did, separator) != null or
            std.mem.indexOfScalar(u8, collection, separator) != null) return error.InvalidIndexKey;
        const a = try makeKey(self.allocator, rbc, collection, did);
        defer self.allocator.free(a);
        const b = try makeKey(self.allocator, cbr, did, collection);
        defer self.allocator.free(b);
        if (delete) {
            try self.db.del(a);
            try self.db.del(b);
        } else {
            // Sources other than validated firehose commits (describeRepo
            // snapshots, backfill pages) can carry arbitrary strings.
            if (!isValidCollection(collection)) return;
            if ((try self.db.get(a)) != null and (try self.db.get(b)) != null) return;
            try self.db.put(a, "");
            try self.db.put(b, "");
        }
    }

    fn discard(self: *CollectionIndex) void {
        self.db.discard() catch {
            self.failed.store(true, .release);
        };
    }

    fn mutatePair(self: *CollectionIndex, did: []const u8, collection: []const u8, delete: bool) !void {
        try self.submitMutation(.{ .pair = .{ .pair = .{ .did = did, .collection = collection }, .delete = delete } });
    }

    pub fn addCollection(self: *CollectionIndex, did: []const u8, collection: []const u8) !void {
        try self.mutatePair(did, collection, false);
    }

    pub fn removeCollection(self: *CollectionIndex, did: []const u8, collection: []const u8) !void {
        try self.mutatePair(did, collection, true);
    }

    pub fn addCollectionPage(self: *CollectionIndex, dids: []const []const u8, collection: []const u8) !void {
        try self.submitMutation(.{ .page = .{ .dids = dids, .collection = collection } });
    }

    pub fn removeCollectionPage(self: *CollectionIndex, dids: []const []const u8, collection: []const u8) !void {
        try self.submitMutation(.{ .page = .{ .dids = dids, .collection = collection, .delete = true } });
    }

    /// Remove every pair filed under a collection name that is not an NSID.
    /// Pages through each such name with a cursor, so it does not depend on
    /// the reader observing its own deletions.
    pub fn purgeInvalidCollections(
        self: *CollectionIndex,
        allocator: Allocator,
        stop: *const std.atomic.Value(bool),
        removed: *std.atomic.Value(u64),
    ) !void {
        const known = try self.listKnownCollections(allocator);
        defer {
            for (known) |collection| allocator.free(collection);
            allocator.free(known);
        }
        const bytes = try allocator.alloc(u8, 65536);
        defer allocator.free(bytes);
        const spans = try allocator.alloc(Span, 1000);
        defer allocator.free(spans);
        const dids = try allocator.alloc([]const u8, spans.len);
        defer allocator.free(dids);
        var cursor_buf: [2048]u8 = undefined;
        for (known) |collection| {
            if (isValidCollection(collection)) continue;
            var cursor: ?[]const u8 = null;
            while (!stop.load(.acquire)) {
                const page = try self.listReposByCollection(collection, spans.len, cursor, bytes, spans);
                if (page.count == 0) break;
                for (0..page.count) |i| dids[i] = page.getDid(i);
                try self.removeCollectionPage(dids[0..page.count], collection);
                _ = removed.fetchAdd(page.count, .monotonic);
                const last = page.last_did.?;
                if (last.len > cursor_buf.len) return error.BufferTooSmall;
                @memcpy(cursor_buf[0..last.len], last);
                cursor = cursor_buf[0..last.len];
            }
        }
    }

    pub fn removeAll(self: *CollectionIndex, did: []const u8) !void {
        try self.replaceCollections(did, &.{});
    }

    pub fn replaceCollections(self: *CollectionIndex, did: []const u8, collections: []const []const u8) !void {
        try self.submitMutation(.{ .replace = .{ .did = did, .collections = collections } });
    }

    pub const ResyncResult = SnapshotResult;

    pub fn beginResync(self: *CollectionIndex, did: []const u8) !u64 {
        try validateKey(did);
        if (did.len > 128) return error.InvalidIndexKey;
        try self.lock();
        defer self.mutex.unlock(self.io);
        if (self.resync_guard != null) return error.ResyncBusy;
        if (self.resync_counter == std.math.maxInt(u64)) return error.ResyncTokenExhausted;
        self.resync_counter += 1;
        var guard: ResyncGuard = .{ .did = undefined, .len = did.len, .token = self.resync_counter, .changed = false, .destructive = false };
        @memcpy(guard.did[0..did.len], did);
        self.resync_guard = guard;
        return guard.token;
    }

    pub fn cancelResync(self: *CollectionIndex, token: u64) void {
        self.mutex.lockUncancelable(self.io);
        defer self.mutex.unlock(self.io);
        if (self.resync_guard) |guard| if (guard.token == token) {
            self.resync_guard = null;
        };
    }

    pub fn finishResync(self: *CollectionIndex, did: []const u8, token: u64, collections: []const []const u8) !ResyncResult {
        var applied: ResyncResult = .superseded;
        try self.submitMutation(.{ .guarded_replace = .{ .did = did, .token = token, .collections = collections, .applied = &applied } });
        return applied;
    }

    fn noteMutation(self: *CollectionIndex, did: []const u8, destructive: bool) void {
        if (self.resync_guard) |*guard| if (std.mem.eql(u8, guard.did[0..guard.len], did)) {
            guard.changed = true;
            guard.destructive = guard.destructive or destructive;
        };
    }

    fn stageRemoveAll(self: *CollectionIndex, did: []const u8) !void {
        self.noteMutation(did, true);
        if (did.len == 0 or std.mem.indexOfScalar(u8, did, separator) != null)
            return error.InvalidIndexKey;
        const prefix = try makeKey(self.allocator, cbr, did, "");
        defer self.allocator.free(prefix);
        {
            var iter = try self.db.scan(.{ .start = prefix });
            defer iter.deinit();
            while (try iter.next()) |entry| {
                if (!std.mem.startsWith(u8, entry.key, prefix)) break;
                try self.stagePair(did, entry.key[prefix.len..], true);
            }
        }
    }

    /// process commit ops to update collection index.
    /// extracts collection from each op path (<collection>/<rkey>).
    /// for creates: ensures collection is tracked.
    ///
    /// `ops` is a cbor Value (expected to be an array of {action, path, cid?} maps).
    pub fn trackCommitOps(self: *CollectionIndex, did: []const u8, ops: zat.cbor.Value) !void {
        try self.submitMutation(.{ .frame = .{ .did = did, .ops = ops } });
    }

    fn stageCommitOps(self: *CollectionIndex, did: []const u8, ops: zat.cbor.Value) !void {
        self.noteMutation(did, false);
        const items = switch (ops) {
            .array => |items| items,
            else => return,
        };
        for (items) |op| {
            const action = op.getString("action") orelse continue;
            const path = op.getString("path") orelse continue;
            const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
            if (slash == 0) continue;
            if (std.mem.eql(u8, action, "create") or std.mem.eql(u8, action, "update")) {
                try self.stagePair(did, path[0..slash], false);
            }
            // A record delete does not establish that the collection is empty.
        }
    }

    /// list DIDs that have records in a collection. returns up to `limit` DIDs
    /// starting after `cursor_did` (or from the beginning if null).
    /// The result borrows both caller-owned output buffers.
    pub fn listReposByCollection(
        self: *CollectionIndex,
        collection: []const u8,
        limit: usize,
        cursor_did: ?[]const u8,
        out_buf: []u8,
        did_offsets: []Span,
    ) !ListResult {
        if (limit > did_offsets.len) return error.BufferTooSmall;
        if (self.page_owner) |owner| {
            var result: ListResult = undefined;
            var request: PageOwner.Request = .{ .item = .{
                .collection = collection,
                .limit = limit,
                .cursor = cursor_did,
                .bytes = out_buf,
                .offsets = did_offsets,
                .result = &result,
            } };
            try owner.submit(&request);
            request.done.waitUncancelable(self.read_io);
            try request.outcome;
            return result;
        }
        return self.listReposDirect(collection, limit, cursor_did, out_buf, did_offsets);
    }

    pub fn enablePageWorker(self: *CollectionIndex, queue_limit: usize) !void {
        if (self.page_owner != null) return error.AlreadyStarted;
        const owner = try self.allocator.create(PageOwner);
        errdefer self.allocator.destroy(owner);
        owner.* = .{ .context = self, .io = self.read_io, .max_batch = 1, .queue_limit = queue_limit, .delay_ns = 0 };
        try owner.start();
        self.page_owner = owner;
    }

    fn readPages(self: *CollectionIndex, queries: []const PageQuery) !void {
        for (queries) |query| query.result.* = try self.listReposDirect(query.collection, query.limit, query.cursor, query.bytes, query.offsets);
    }

    fn listReposDirect(self: *CollectionIndex, collection: []const u8, limit: usize, cursor_did: ?[]const u8, out_buf: []u8, did_offsets: []Span) !ListResult {
        try self.lockReader();
        defer self.read_mutex.unlock(self.read_io);
        for (0..3) |_| {
            self.read_db.refresh() catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
            return self.pageOnce(collection, limit, cursor_did, out_buf, did_offsets) catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
        }
        return error.ReaderRetryExhausted;
    }

    fn pageOnce(self: *CollectionIndex, collection: []const u8, limit: usize, cursor_did: ?[]const u8, out_buf: []u8, did_offsets: []Span) !ListResult {
        const prefix = try makeKey(self.allocator, rbc, collection, "");
        defer self.allocator.free(prefix);
        const seek_key = if (cursor_did) |cursor|
            try std.mem.concat(self.allocator, u8, &.{ prefix, cursor, "\x00" })
        else
            prefix;
        defer if (cursor_did != null) self.allocator.free(seek_key);
        var iter = try self.read_db.scan(.{ .start = seek_key });
        defer iter.deinit();

        var count: usize = 0;
        var buf_pos: usize = 0;
        var last_did: ?[]const u8 = null;

        while (count < limit) {
            const entry = (try iter.next()) orelse break;
            const key_data = entry.key;

            // stop when prefix no longer matches
            if (!std.mem.startsWith(u8, key_data, prefix)) break;

            // extract DID after prefix
            const did = key_data[prefix.len..];
            if (did.len == 0) continue;

            // copy DID into output buffer
            if (buf_pos + did.len > out_buf.len) break;
            @memcpy(out_buf[buf_pos..][0..did.len], did);
            did_offsets[count] = .{ .start = buf_pos, .len = did.len };
            buf_pos += did.len;

            last_did = out_buf[did_offsets[count].start..][0..did_offsets[count].len];
            count += 1;
        }

        return .{
            .count = count,
            .offsets = did_offsets[0..count],
            .buf = out_buf[0..buf_pos],
            .last_did = last_did,
        };
    }

    /// scan the RBC column family for unique collection prefixes.
    /// returns a deduplicated list of collection names (caller owns the slice and each string).
    /// Every collection with at least one RBC entry, found by seeking from
    /// one collection's last possible key to the next: one short scan per
    /// collection instead of a walk over every pair, and the reader is held
    /// only for that seek, so pages keep being served while this runs. The
    /// reader is refreshed once up front; a table collected mid-walk surfaces
    /// as Missing and refreshes again.
    pub fn listKnownCollections(self: *CollectionIndex, allocator: Allocator) ![][]const u8 {
        var found: std.ArrayListUnmanaged([]const u8) = .empty;
        errdefer {
            for (found.items) |c| allocator.free(c);
            found.deinit(allocator);
        }
        var cursor: std.ArrayListUnmanaged(u8) = .empty;
        defer cursor.deinit(allocator);
        try cursor.appendSlice(allocator, rbc);
        {
            try self.lockReader();
            defer self.read_mutex.unlock(self.read_io);
            try self.read_db.refresh();
        }
        while (try self.nextCollectionFrom(allocator, cursor.items)) |collection| {
            errdefer allocator.free(collection);
            try found.append(allocator, collection);
            cursor.clearRetainingCapacity();
            try cursor.appendSlice(allocator, rbc);
            try cursor.appendSlice(allocator, collection);
            try cursor.append(allocator, separator + 1);
        }
        return found.toOwnedSlice(allocator);
    }

    fn nextCollectionFrom(self: *CollectionIndex, allocator: Allocator, start: []const u8) !?[]const u8 {
        try self.lockReader();
        defer self.read_mutex.unlock(self.read_io);
        for (0..3) |attempt| {
            if (attempt > 0) self.read_db.refresh() catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
            return self.firstCollectionOnce(allocator, start) catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
        }
        return error.ReaderRetryExhausted;
    }

    fn firstCollectionOnce(self: *CollectionIndex, allocator: Allocator, start: []const u8) !?[]const u8 {
        var iter = try self.read_db.scan(.{ .start = start, .end = cbr });
        defer iter.deinit();
        while (try iter.next()) |entry| {
            const key_data = entry.key[1..];
            const sep_pos = std.mem.indexOfScalar(u8, key_data, separator) orelse continue;
            const collection = key_data[0..sep_pos];
            if (collection.len == 0) continue;
            return try allocator.dupe(u8, collection);
        }
        return null;
    }

    /// check if a DID has any collection entries
    pub fn hasCollections(self: *CollectionIndex, did: []const u8) bool {
        return self.hasCollectionsChecked(did) catch false;
    }

    pub fn hasCollectionsChecked(self: *CollectionIndex, did: []const u8) !bool {
        try self.lockReader();
        defer self.read_mutex.unlock(self.read_io);
        const prefix = try makeKey(self.allocator, cbr, did, "");
        defer self.allocator.free(prefix);
        for (0..3) |_| {
            self.read_db.refresh() catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
            return self.hasOnce(prefix) catch |err| {
                if (err == error.Missing) continue;
                return err;
            };
        }
        return error.ReaderRetryExhausted;
    }

    fn hasOnce(self: *CollectionIndex, prefix: []const u8) !bool {
        var iter = try self.read_db.scan(.{ .start = prefix });
        defer iter.deinit();
        const entry = (try iter.next()) orelse return false;
        return std.mem.startsWith(u8, entry.key, prefix);
    }
};

pub fn isValidCollection(collection: []const u8) bool {
    return zat.Nsid.parse(collection) != null;
}

pub const Span = struct { start: usize, len: usize };

pub const ListResult = struct {
    count: usize,
    offsets: []const Span,
    buf: []const u8,
    last_did: ?[]const u8,

    /// get the DID at index i
    pub fn getDid(self: ListResult, i: usize) []const u8 {
        const off = self.offsets[i];
        return self.buf[off.start..][0..off.len];
    }
};

fn makeKey(allocator: Allocator, namespace: []const u8, a: []const u8, b: []const u8) ![]u8 {
    return std.mem.concat(allocator, u8, &.{ namespace, a, "\x00", b });
}

// --- tests ---

test "collection index: open and close" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    ci.deinit();
}

test "collection index: basic put and get" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    // add a single collection entry
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");

    try testing.expect(ci.hasCollections("did:plc:alice"));
}

test "collection index: list and cursor" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.addCollection("did:plc:bob", "app.bsky.feed.post");
    try ci.addCollection("did:plc:carol", "app.bsky.graph.follow");

    // list repos by collection
    var buf: [4096]u8 = undefined;
    var offsets: [2000]Span = undefined;
    const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
    try testing.expectEqual(@as(usize, 2), result.count);
    try testing.expectEqualStrings("did:plc:alice", result.getDid(0));
    try testing.expectEqualStrings("did:plc:bob", result.getDid(1));

    // cursor pagination
    const result2 = try ci.listReposByCollection("app.bsky.feed.post", 100, "did:plc:alice", &buf, &offsets);
    try testing.expectEqual(@as(usize, 1), result2.count);
    try testing.expectEqualStrings("did:plc:bob", result2.getDid(0));
}

test "collection index: removeAll" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.addCollection("did:plc:alice", "app.bsky.feed.like");
    try ci.addCollection("did:plc:bob", "app.bsky.feed.post");

    try ci.removeAll("did:plc:alice");
    try testing.expect(!ci.hasCollections("did:plc:alice"));

    var buf: [4096]u8 = undefined;
    var offsets: [2000]Span = undefined;
    const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
    try testing.expectEqual(@as(usize, 1), result.count);
    try testing.expectEqualStrings("did:plc:bob", result.getDid(0));
}

test "collection index: listKnownCollections" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.addCollection("did:plc:bob", "app.bsky.feed.post");
    try ci.addCollection("did:plc:alice", "app.bsky.feed.like");
    try ci.addCollection("did:plc:carol", "app.bsky.graph.follow");

    const collections = try ci.listKnownCollections(allocator);
    defer {
        for (collections) |c| allocator.free(c);
        allocator.free(collections);
    }

    try testing.expectEqual(@as(usize, 3), collections.len);

    // verify all three collections are present (order not guaranteed)
    var found_post = false;
    var found_like = false;
    var found_follow = false;
    for (collections) |c| {
        if (std.mem.eql(u8, c, "app.bsky.feed.post")) found_post = true;
        if (std.mem.eql(u8, c, "app.bsky.feed.like")) found_like = true;
        if (std.mem.eql(u8, c, "app.bsky.graph.follow")) found_follow = true;
    }
    try testing.expect(found_post);
    try testing.expect(found_like);
    try testing.expect(found_follow);
}

test "collection index: listKnownCollections seeks across flushed tables and adjacent prefixes" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    const names = [_][]const u8{ "app.bsky.feed.post", "app.bsky.feed.post.extra", "app.bsky.feed.postscript", "sh.tangled.repo" };
    var buffers: [64][64]u8 = undefined;
    var ids: [64][]const u8 = undefined;
    for (names, 0..) |name, n| {
        for (0..4) |chunk| {
            for (&buffers, &ids, 0..) |*buf, *id, i| id.* = try std.fmt.bufPrint(buf, "did:plc:{d:0>3}{d:0>3}{d:0>18}", .{ n, chunk, i });
            try ci.addCollectionPage(&ids, name);
            if (chunk % 2 == 1) try ci.db.flush();
        }
    }
    while (try ci.db.compact()) {}
    try ci.addCollection("did:plc:late", "zzz.last.collection");

    const collections = try ci.listKnownCollections(allocator);
    defer {
        for (collections) |c| allocator.free(c);
        allocator.free(collections);
    }
    try testing.expectEqual(@as(usize, names.len + 1), collections.len);
    for (names) |name| {
        var found = false;
        for (collections) |c| found = found or std.mem.eql(u8, c, name);
        try testing.expect(found);
    }
    try testing.expectEqualStrings("zzz.last.collection", collections[collections.len - 1]);
}

test "collection index: invalid collection names are not added and existing ones are purged" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(t.allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();

    const junk = [_][]const u8{ "app.bsky.feed.post&", "app.bsky.feed.post;DECLARE/**/@x", "community.lexicon.calendar.event#uri" };
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    for (junk) |name| try ci.addCollection("did:plc:alice", name);
    try ci.addCollectionPage(&.{ "did:plc:bob", "did:plc:carol" }, junk[0]);
    try ci.replaceCollections("did:plc:dave", &.{ "app.bsky.graph.follow", junk[1] });
    {
        const known = try ci.listKnownCollections(t.allocator);
        defer {
            for (known) |name| t.allocator.free(name);
            t.allocator.free(known);
        }
        try t.expectEqual(@as(usize, 2), known.len);
    }

    // Junk written before the check existed.
    var id: [32]u8 = undefined;
    try ci.lock();
    {
        defer ci.mutex.unlock(ci.io);
        for (junk) |name| for (0..2500) |i| {
            const did = try std.fmt.bufPrint(&id, "did:plc:{d:0>24}", .{i});
            const forward = try makeKey(t.allocator, rbc, name, did);
            defer t.allocator.free(forward);
            const reverse = try makeKey(t.allocator, cbr, did, name);
            defer t.allocator.free(reverse);
            try ci.db.put(forward, "");
            try ci.db.put(reverse, "");
        };
        try ci.commit();
    }
    try ci.addCollection("did:plc:000000000000000000000007", "app.bsky.feed.post");

    var stop = std.atomic.Value(bool).init(false);
    var removed = std.atomic.Value(u64).init(0);
    try ci.purgeInvalidCollections(t.allocator, &stop, &removed);
    try t.expectEqual(@as(u64, junk.len * 2500), removed.load(.monotonic));

    const known = try ci.listKnownCollections(t.allocator);
    defer {
        for (known) |name| t.allocator.free(name);
        t.allocator.free(known);
    }
    try t.expectEqual(@as(usize, 2), known.len);
    try t.expectEqualStrings("app.bsky.feed.post", known[0]);
    try t.expectEqualStrings("app.bsky.graph.follow", known[1]);
    var bytes: [4096]u8 = undefined;
    var spans: [8]Span = undefined;
    const page = try ci.listReposByCollection("app.bsky.feed.post", spans.len, null, &bytes, &spans);
    try t.expectEqual(@as(usize, 2), page.count);
    try t.expect(ci.hasCollections("did:plc:000000000000000000000007"));
    try t.expect(!ci.hasCollections("did:plc:000000000000000000000008"));
}

test "collection index: idempotent add" {
    const testing = std.testing;
    const allocator = testing.allocator;

    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
    defer allocator.free(path);

    var ci = try CollectionIndex.open(allocator, testing.io, path);
    defer ci.deinit();

    // add same entry twice — should not duplicate
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");

    var buf: [4096]u8 = undefined;
    var offsets: [2000]Span = undefined;
    const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
    try testing.expectEqual(@as(usize, 1), result.count);
}

test "collection index: cursor, deletion and maintenance survive reopen" {
    const testing = std.testing;
    const allocator = testing.allocator;
    var dir = testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(testing.io, ".", allocator);
    defer allocator.free(path);
    const collection = "app.bsky.feed.post";
    {
        var ci = try CollectionIndex.open(allocator, testing.io, path);
        defer ci.deinit();
        for (0..260) |i| {
            var buf: [64]u8 = undefined;
            try ci.addCollection(try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i}), collection);
        }
        try ci.addCollection("did:web:example.org", collection);
        try ci.addCollection("did:web:example.org:alice", collection);
        try ci.addCollection("did:web:example.org", "app.bsky.feed.like");
        try ci.removeCollection("did:web:example.org", "app.bsky.feed.like");
        try ci.removeAll("did:web:absent.example");
    }
    {
        var ci = try CollectionIndex.open(allocator, testing.io, path);
        defer ci.deinit();
        var buf: [128]u8 = undefined;
        var offsets: [2]Span = undefined;
        const page = try ci.listReposByCollection(collection, 1, "did:web:example.org", &buf, &offsets);
        try testing.expectEqual(@as(usize, 1), page.count);
        try testing.expectEqualStrings("did:web:example.org:alice", page.getDid(0));
        try ci.removeAll("did:web:example.org");
        try testing.expect(!ci.hasCollections("did:web:example.org"));
        try testing.expect(ci.hasCollections("did:web:example.org:alice"));
    }
}

test "collection index: concurrent producers publish both index directions" {
    const testing = std.testing;
    var dir = testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(testing.io, ".", testing.allocator);
    defer testing.allocator.free(path);
    var ci = try CollectionIndex.open(testing.allocator, testing.io, path);
    defer ci.deinit();

    const Worker = struct {
        fn run(index: *CollectionIndex, did: []const u8, ok: *bool) void {
            for (0..32) |_| index.addCollection(did, "app.bsky.feed.post") catch return;
            ok.* = true;
        }
    };
    var alice = false;
    var bob = false;
    const first = try std.Thread.spawn(.{}, Worker.run, .{ &ci, "did:plc:alice", &alice });
    const second = std.Thread.spawn(.{}, Worker.run, .{ &ci, "did:plc:bob", &bob }) catch |err| {
        first.join();
        return err;
    };
    first.join();
    second.join();
    try testing.expect(alice and bob);
    var buf: [128]u8 = undefined;
    var spans: [2]Span = undefined;
    const page = try ci.listReposByCollection("app.bsky.feed.post", spans.len, null, &buf, &spans);
    try testing.expectEqual(@as(usize, 2), page.count);
    try testing.expectEqualStrings("did:plc:alice", page.getDid(0));
    try testing.expectEqualStrings("did:plc:bob", page.getDid(1));
    try testing.expect(ci.hasCollections("did:plc:alice"));
    try testing.expect(ci.hasCollections("did:plc:bob"));
}

test "collection index: rejected page or replacement leaves prior state intact" {
    const testing = std.testing;
    var dir = testing.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(testing.io, ".", testing.allocator);
    defer testing.allocator.free(path);
    var ci = try CollectionIndex.open(testing.allocator, testing.io, path);
    defer ci.deinit();

    const post = "app.bsky.feed.post";
    const like = "app.bsky.feed.like";
    const alice = "did:plc:alice";
    try ci.addCollection(alice, post);
    try testing.expectError(error.InvalidIndexKey, ci.addCollectionPage(&.{ "did:plc:bob", "bad\x00did" }, post));
    try testing.expectError(error.InvalidIndexKey, ci.replaceCollections(alice, &.{ like, "" }));
    try testing.expect(ci.hasCollections(alice));
    try testing.expect(!ci.hasCollections("did:plc:bob"));
    var bytes: [64]u8 = undefined;
    var offsets: [2]Span = undefined;
    try testing.expectEqual(@as(usize, 1), (try ci.listReposByCollection(post, 2, null, &bytes, &offsets)).count);
    try testing.expectEqual(@as(usize, 0), (try ci.listReposByCollection(like, 2, null, &bytes, &offsets)).count);

    try ci.replaceCollections(alice, &.{like});
    try testing.expectEqual(@as(usize, 0), (try ci.listReposByCollection(post, 2, null, &bytes, &offsets)).count);
    try testing.expectEqual(@as(usize, 1), (try ci.listReposByCollection(like, 2, null, &bytes, &offsets)).count);
}

test "collection index: cross-frame batch is atomic and survives reopen" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        try ci.addPairs(&.{
            .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" },
            .{ .did = "did:plc:bob", .collection = "app.bsky.feed.like" },
            .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" },
        });
        try t.expectError(error.InvalidIndexKey, ci.addPairs(&.{
            .{ .did = "did:plc:carol", .collection = "app.bsky.feed.post" },
            .{ .did = "invalid\x00did", .collection = "app.bsky.feed.post" },
        }));
        try t.expect(!ci.hasCollections("did:plc:carol"));
    }
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        try t.expect(ci.hasCollections("did:plc:alice"));
        try t.expect(ci.hasCollections("did:plc:bob"));
        try t.expect(!ci.hasCollections("did:plc:carol"));
        var bytes: [128]u8 = undefined;
        var spans: [4]Span = undefined;
        const page = try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans);
        try t.expectEqual(@as(usize, 1), page.count);
        try t.expectEqualStrings("did:plc:alice", page.getDid(0));
    }
}

test "collection index: maintenance failure is reported and prevents later acknowledgements" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.enableBatching(.{ .delay_ns = 0 });
    const obstacle = try dir.dir.createFile(t.io, "sst", .{});
    obstacle.close(t.io);
    var observed_failure = false;
    for (0..300) |i| {
        var bytes: [64]u8 = undefined;
        const id = try std.fmt.bufPrint(&bytes, "did:plc:{d:0>24}", .{i});
        ci.addCollection(id, "app.bsky.feed.post") catch {
            observed_failure = true;
            break;
        };
    }
    try t.expect(observed_failure);
    try t.expectError(error.IndexUnavailable, ci.hasCollectionsChecked("did:plc:later"));
    try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
}

test "collection index: a fresh read completes while the writer mutex is held" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    const Reader = struct {
        ci: *CollectionIndex,
        done: Io.Event = .unset,
        outcome: anyerror!bool = false,
        fn run(self: *@This()) void {
            self.outcome = self.ci.hasCollectionsChecked("did:plc:alice");
            self.done.set(self.ci.io);
        }
    };
    var reader: Reader = .{ .ci = &ci };
    ci.mutex.lockUncancelable(t.io);
    const thread = std.Thread.spawn(.{}, Reader.run, .{&reader}) catch |err| {
        ci.mutex.unlock(t.io);
        return err;
    };
    const completed = if (reader.done.waitTimeout(t.io, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } })) |_| true else |_| false;
    ci.mutex.unlock(t.io);
    thread.join();
    try t.expect(completed);
    try t.expect(try reader.outcome);
}

test "collection index: fresh complete pages survive concurrent flush compaction and collection" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    const Writer = struct {
        ci: *CollectionIndex,
        acknowledged: std.atomic.Value(usize) = .init(0),
        done: std.atomic.Value(bool) = .init(false),
        outcome: anyerror!void = {},
        fn run(self: *@This()) void {
            self.outcome = self.write();
            self.done.store(true, .release);
        }
        fn write(self: *@This()) !void {
            for (0..16) |chunk| {
                var bytes: [32][64]u8 = undefined;
                var dids: [32][]const u8 = undefined;
                for (&bytes, &dids, 0..) |*buf, *id, i| id.* = try std.fmt.bufPrint(buf, "did:plc:{d:0>24}", .{chunk * 32 + i});
                try self.ci.addCollectionPage(&dids, "app.bsky.feed.post");
                self.acknowledged.store((chunk + 1) * 32, .release);
                self.ci.mutex.lockUncancelable(self.ci.io);
                defer self.ci.mutex.unlock(self.ci.io);
                try self.ci.db.flush();
                while (try self.ci.db.compact()) {}
                try self.ci.db.collect();
            }
        }
    };
    var writer: Writer = .{ .ci = &ci };
    const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer});
    var joined = false;
    defer if (!joined) thread.join();
    var reads: usize = 0;
    while (!writer.done.load(.acquire) or reads < 100) : (reads += 1) {
        const required = @min(writer.acknowledged.load(.acquire), 100);
        var bytes: [4096]u8 = undefined;
        var spans: [100]Span = undefined;
        const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
        try t.expect(page.count >= required);
        if (page.count < 100) try t.expect(page.count % 32 == 0);
        for (0..page.count) |i| {
            var expected: [64]u8 = undefined;
            try t.expectEqualStrings(try std.fmt.bufPrint(&expected, "did:plc:{d:0>24}", .{i}), page.getDid(i));
        }
    }
    thread.join();
    joined = true;
    try writer.outcome;
    try t.expectEqual(@as(usize, 512), writer.acknowledged.load(.acquire));
    try t.expect(try ci.hasCollectionsChecked("did:plc:000000000000000000000511"));
}

test "collection index: live frame indexing reports rejected writes" {
    const t = std.testing;
    const Value = @import("zat").cbor.Value;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    const ops: Value = .{ .array = &.{.{ .map = &.{
        .{ .key = "action", .value = .{ .text = "create" } },
        .{ .key = "path", .value = .{ .text = "app.bsky.feed.post/record" } },
    } }} };
    try ci.trackCommitOps("did:plc:alice", ops);
    try t.expectError(error.InvalidIndexKey, ci.trackCommitOps("bad\x00did", ops));
    try t.expect(try ci.hasCollectionsChecked("did:plc:alice"));
    try t.expect(!(try ci.hasCollectionsChecked("bad\x00did")));
}

test "collection index: ordered mutations within a commit replace earlier staged membership" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.applyMutations(&.{
        .{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" }, .delete = false } },
        .{ .replace = .{ .did = "did:plc:alice", .collections = &.{"app.bsky.feed.like"} } },
        .{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.repost" }, .delete = false } },
    });
    var bytes: [128]u8 = undefined;
    var spans: [4]Span = undefined;
    try t.expectEqual(@as(usize, 0), (try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans)).count);
    try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.like", 4, null, &bytes, &spans)).count);
    try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.repost", 4, null, &bytes, &spans)).count);
}

test "collection index: owner drains ordered live backfill and resync requests before reopen" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        try ci.enableBatching(.{ .max_batch = 4, .queue_limit = 4 });
        const ops: zat.cbor.Value = .{ .array = &.{.{ .map = &.{
            .{ .key = "action", .value = .{ .text = "create" } },
            .{ .key = "path", .value = .{ .text = "app.bsky.feed.repost/record" } },
        } }} };
        const mutations: [4]Mutation = .{
            .{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" }, .delete = false } },
            .{ .replace = .{ .did = "did:plc:alice", .collections = &.{"app.bsky.feed.like"} } },
            .{ .frame = .{ .did = "did:plc:alice", .ops = ops } },
            .{ .page = .{ .dids = &.{"did:plc:bob"}, .collection = "app.bsky.feed.post" } },
        };
        var requests: [4]CollectionIndex.WriteOwner.Request = undefined;
        ci.mutex.lockUncancelable(t.io);
        var locked = true;
        defer if (locked) ci.mutex.unlock(t.io);
        for (&requests, mutations) |*request, mutation| {
            request.* = .{ .item = mutation };
            try ci.write_owner.?.submit(request);
        }
        ci.mutex.unlock(t.io);
        locked = false;
        ci.write_owner.?.close();
        for (&requests) |*request| {
            try t.expect(request.done.isSet());
            try request.outcome;
        }
        try t.expectError(error.Closed, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
    }
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        var bytes: [128]u8 = undefined;
        var spans: [4]Span = undefined;
        const post = try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans);
        try t.expectEqual(@as(usize, 1), post.count);
        try t.expectEqualStrings("did:plc:bob", post.getDid(0));
        try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.like", 4, null, &bytes, &spans)).count);
        try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.repost", 4, null, &bytes, &spans)).count);
    }
}

test "collection index: known membership does not incur the aggregation deadline" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.enableBatching(.{ .delay_ns = 2_000_000_000 });
    const before = Io.Clock.awake.now(t.io);
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    const elapsed = before.durationTo(Io.Clock.awake.now(t.io)).toNanoseconds();
    try t.expect(elapsed < 1_000_000_000);
    try t.expect(try ci.hasCollectionsChecked("did:plc:alice"));
}

test "collection index: resync merges concurrent additions and cannot undo destructive updates" {
    const t = std.testing;
    for ([_]bool{ false, true }) |batched| {
        var dir = t.tmpDir(.{});
        defer dir.cleanup();
        const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
        defer t.allocator.free(path);
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        if (batched) try ci.enableBatching(.{ .delay_ns = 0 });
        const alice = "did:plc:alice";
        const post = "app.bsky.feed.post";
        const like = "app.bsky.feed.like";
        const follow = "app.bsky.graph.follow";
        try ci.addCollection(alice, post);
        const quiet = try ci.beginResync(alice);
        try ci.addCollection("did:plc:bob", like);
        try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, quiet, &.{like}));
        const racing = try ci.beginResync(alice);
        try ci.addCollection(alice, follow);
        try t.expectEqual(CollectionIndex.ResyncResult.merged, try ci.finishResync(alice, racing, &.{post}));
        var bytes: [256]u8 = undefined;
        var spans: [4]Span = undefined;
        try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection(follow, 4, null, &bytes, &spans)).count);
        try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection(post, 4, null, &bytes, &spans)).count);
        try t.expectEqual(@as(usize, 2), (try ci.listReposByCollection(like, 4, null, &bytes, &spans)).count);
        const converge = try ci.beginResync(alice);
        try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, converge, &.{follow}));
        try t.expectEqual(@as(usize, 0), (try ci.listReposByCollection(post, 4, null, &bytes, &spans)).count);
        const duplicate = try ci.beginResync(alice);
        try ci.addCollection(alice, follow);
        try t.expectEqual(CollectionIndex.ResyncResult.merged, try ci.finishResync(alice, duplicate, &.{}));
        try t.expect(try ci.hasCollectionsChecked(alice));
        const deleted = try ci.beginResync(alice);
        try ci.removeAll(alice);
        try t.expectEqual(CollectionIndex.ResyncResult.superseded, try ci.finishResync(alice, deleted, &.{post}));
        try t.expect(!(try ci.hasCollectionsChecked(alice)));
        const canceled = try ci.beginResync(alice);
        try t.expectError(error.ResyncBusy, ci.beginResync("did:plc:bob"));
        ci.cancelResync(canceled);
        const current = try ci.beginResync(alice);
        ci.cancelResync(canceled);
        try t.expectEqual(CollectionIndex.ResyncResult.superseded, try ci.finishResync(alice, canceled, &.{like}));
        try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, current, &.{post}));
        try t.expect(try ci.hasCollectionsChecked(alice));
    }
}

test "collection index: bounded log policy flushes and recovers acknowledged pairs" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        ci.maintenance_policy = .{ .max_segments = 8, .max_memtable_bytes = 1 << 20 };
        for (0..9) |i| {
            var bytes: [64]u8 = undefined;
            const id = try std.fmt.bufPrint(&bytes, "did:plc:{d}", .{i});
            try ci.addCollection(id, "app.bsky.feed.post");
        }
        try t.expectEqual(@as(usize, 1), ci.maintenance_runs);
        try t.expectEqual(@as(u64, 8), ci.maintenance_detail.flushed_segments);
        try t.expectEqual(@as(u64, 2), ci.db.unflushedSegments());
    }
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    for (0..9) |i| {
        var bytes: [64]u8 = undefined;
        const id = try std.fmt.bufPrint(&bytes, "did:plc:{d}", .{i});
        try t.expect(try ci.hasCollectionsChecked(id));
    }
    ci.maintenance_policy = .{ .max_segments = 4096, .max_memtable_bytes = 1 };
    try ci.addCollection("did:plc:byte-limit", "app.bsky.feed.post");
    try t.expectEqual(@as(usize, 1), ci.maintenance_runs);
    try t.expectEqual(@as(u64, 0), ci.db.unflushedSegments());
}

test "stepped maintenance returns with pending work and preserves acknowledged pairs" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    ci.maintenance_policy = .{ .max_segments = 1, .step_bytes = 1 };
    ci.db.options.l0_tables = 1;
    ci.db.options.table_bytes = 1;
    ci.db.options.block_bytes = 1;
    const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
    try ci.addCollectionPage(&ids, "app.bsky.feed.post");
    try t.expect(ci.db.compaction != null);
    try t.expect(ci.maintenance_detail.compaction_steps > 0);
    var bytes: [4096]u8 = undefined;
    var spans: [100]Span = undefined;
    const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
    try t.expectEqual(@as(usize, 3), page.count);
    for (ids, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
    while (try ci.db.compact()) {}
    try ci.db.collect();
}

test "deferred maintenance drains while idle and fresh readers see acknowledged pairs" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
        ci.db.options.l0_tables = 1;
        ci.db.options.table_bytes = 1;
        ci.db.options.block_bytes = 1;
        try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true });
        const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
        try ci.addCollectionPage(&ids, "app.bsky.feed.post");
        var bytes: [4096]u8 = undefined;
        var spans: [100]Span = undefined;
        const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
        try t.expectEqual(@as(usize, 3), page.count);
        for (ids, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
        ci.write_owner.?.close();
        try t.expect(ci.db.compaction == null);
        try t.expectEqual(@as(usize, 0), ci.db.version.tables[0].len);
        try t.expectEqual(@as(u64, 0), ci.db.unflushedSegments());
        try t.expect(ci.maintenance_detail.compaction_steps > 1);
    }
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    for ([_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" }) |id| try t.expect(try ci.hasCollectionsChecked(id));
}

test "deferred maintenance failure preserves an acknowledgement and rejects later writes" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
        const obstacle = try dir.dir.createFile(t.io, "sst", .{});
        obstacle.close(t.io);
        try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true });
        try ci.addCollection("did:plc:acknowledged", "app.bsky.feed.post");
        try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
        try t.expectError(error.IndexUnavailable, ci.hasCollectionsChecked("did:plc:acknowledged"));
        ci.write_owner.?.close();
        try t.expectEqual(@as(usize, 1), ci.maintenance_detail.changed_commits);
    }
    try dir.dir.deleteFile(t.io, "sst");
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try t.expect(try ci.hasCollectionsChecked("did:plc:acknowledged"));
    try t.expect(!try ci.hasCollectionsChecked("did:plc:later"));
    var bytes: [4096]u8 = undefined;
    var spans: [100]Span = undefined;
    const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
    try t.expectEqual(@as(usize, 1), page.count);
    try t.expectEqualStrings("did:plc:acknowledged", page.getDid(0));
}

test "page worker bounds admission and drains borrowed output buffers" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try t.expectError(error.InvalidBatchPolicy, ci.enablePageWorker(0));
    try ci.enablePageWorker(1);
    try t.expectError(error.AlreadyStarted, ci.enablePageWorker(1));
    var bytes: [256]u8 = undefined;
    var offsets: [2]Span = undefined;
    var result: ListResult = undefined;
    var request: CollectionIndex.PageOwner.Request = .{ .item = .{ .collection = "app.bsky.feed.post", .limit = 2, .cursor = null, .bytes = &bytes, .offsets = &offsets, .result = &result } };
    ci.read_mutex.lockUncancelable(t.io);
    var locked = true;
    defer if (locked) ci.read_mutex.unlock(t.io);
    try ci.page_owner.?.submit(&request);
    var rejected: CollectionIndex.PageOwner.Request = .{ .item = request.item };
    try t.expectError(error.QueueFull, ci.page_owner.?.submit(&rejected));
    try t.expect(!request.done.isSet());
    ci.read_mutex.unlock(t.io);
    locked = false;
    ci.page_owner.?.close();
    try t.expect(ci.page_owner.?.thread == null);
    try t.expectEqual(@as(usize, 0), ci.page_owner.?.outstanding);
    try t.expect(request.done.isSet());
    try request.outcome;
    try t.expectEqual(@as(usize, 1), result.count);
    try t.expect(result.buf.ptr == bytes[0..].ptr);
    try t.expectEqualStrings("did:plc:alice", result.getDid(0));
    try t.expectError(error.Closed, ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets));
}

test "page worker propagates a missing manifest and serves later recovered reads" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
    try ci.enablePageWorker(2);
    try dir.dir.rename("manifest", dir.dir, "manifest.saved", t.io);
    var bytes: [256]u8 = undefined;
    var offsets: [2]Span = undefined;
    try t.expectError(error.ReaderRetryExhausted, ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets));
    try dir.dir.rename("manifest.saved", dir.dir, "manifest", t.io);
    const page = try ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets);
    try t.expectEqual(@as(usize, 1), page.count);
    try t.expectEqualStrings("did:plc:alice", page.getDid(0));
}

test "log collection schedules a second sweep after an interleaved flush" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    ci.maintenance_after_ack = true;
    ci.maintenance_policy = .{ .max_segments = 1, .log_gc_names = 1 };
    try ci.addCollection("did:plc:a", "app.bsky.feed.post");
    _ = try ci.maintain();
    try t.expect(ci.log_gc_pending);
    try t.expect(ci.log_collector.names != null);
    try ci.addCollection("did:plc:b", "app.bsky.feed.post");
    _ = try ci.maintain();
    try t.expect(ci.log_gc_pending);
    var steps: usize = 0;
    while (try ci.maintain() != .idle) {
        steps += 1;
        try t.expect(steps < 32);
    }
    try t.expect(!ci.log_gc_pending);
    try t.expect(ci.log_collector.names == null);
    const names = try ci.store.list(t.allocator, "log/");
    defer zkv.freeNames(t.allocator, names);
    try t.expectEqual(@as(usize, 1), names.len);
    try t.expect(try ci.hasCollectionsChecked("did:plc:a"));
    try t.expect(try ci.hasCollectionsChecked("did:plc:b"));
}

test "bounded log maintenance drains with idle pending writes and reopens" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        ci.db.options.l0_tables = 1;
        ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 64, .log_gc_names = 1 };
        try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
        for (0..32) |i| {
            var buffer: [32]u8 = undefined;
            const id = try std.fmt.bufPrint(&buffer, "did:plc:{d}", .{i});
            try ci.addCollection(id, "app.bsky.feed.post");
        }
        ci.write_owner.?.close();
        try t.expect(!ci.log_gc_pending);
        try t.expect(ci.log_collector.names == null);
        try t.expect(ci.db.compaction == null);
        try t.expect(ci.maintenance_detail.log_gc_steps > 0);
        try t.expect(ci.maintenance_store.writes > 0);
    }
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    for (0..32) |i| {
        var buffer: [32]u8 = undefined;
        const id = try std.fmt.bufPrint(&buffer, "did:plc:{d}", .{i});
        try t.expect(try ci.hasCollectionsChecked(id));
    }
}

test "pending SST writes wake the idle owner and survive shutdown and reopen" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
        ci.db.options.l0_tables = 1;
        ci.db.options.table_bytes = 1;
        ci.db.options.block_bytes = 1;
        try t.expectError(error.InvalidBatchPolicy, ci.enableBatching(.{ .background_writes = true }));
        try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
        const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
        try ci.addCollectionPage(&ids, "app.bsky.feed.post");
        for (ids) |id| try t.expect(try ci.hasCollectionsChecked(id));
        ci.write_owner.?.close();
        try t.expect(ci.db.compaction == null);
        try t.expect(ci.async_store.pending == null);
        try t.expect(ci.maintenance_detail.pending_polls > 0);
        try t.expectEqual(@as(usize, 0), ci.db.version.tables[0].len);
    }
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    var bytes: [4096]u8 = undefined;
    var spans: [100]Span = undefined;
    const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
    try t.expectEqual(@as(usize, 3), page.count);
    for ([_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" }, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
}

test "background concurrency failure preserves acknowledged pairs and stops later writes" {
    const t = std.testing;
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    var acknowledged: usize = 0;
    {
        var limited = Io.Threaded.init(t.allocator, .{ .concurrent_limit = .nothing });
        defer limited.deinit();
        var ci = try CollectionIndex.openWithReaderIo(t.allocator, limited.io(), t.io, path);
        defer ci.deinit();
        ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
        ci.db.options.l0_tables = 1;
        ci.db.options.table_bytes = 1;
        ci.db.options.block_bytes = 1;
        try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
        var failed = false;
        for (0..16) |i| {
            var buf: [64]u8 = undefined;
            const did = try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i});
            ci.addCollection(did, "app.bsky.feed.post") catch |err| {
                try t.expectEqual(error.IndexUnavailable, err);
                failed = true;
                break;
            };
            acknowledged += 1;
        }
        try t.expect(failed);
        try t.expect(acknowledged > 0);
        try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
        ci.write_owner.?.close();
        try t.expect(ci.async_store.pending == null);
    }
    var ci = try CollectionIndex.open(t.allocator, t.io, path);
    defer ci.deinit();
    for (0..16) |i| {
        var buf: [64]u8 = undefined;
        const did = try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i});
        try t.expectEqual(i < acknowledged, try ci.hasCollectionsChecked(did));
    }
    try t.expect(!try ci.hasCollectionsChecked("did:plc:later"));
}