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

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
906 lines · 37.4 KB Raw History
//! Authenticated asynchronous whole-repo repair for live Sync 1.1 ingest.
//!
//! This is the Atmos/Jetstream V2 state machine, expressed in Stream's
//! ordered pipeline: 32 fetch workers, a 64-job bounded queue, five repairs
//! per DID per minute (burst five), 2,048 pending commits per DID, unlocked
//! five-minute getRepo fetches, stale-head rejection, authenticated apply,
//! and ordered replay before the per-DID lane is released.

const std = @import("std");
const zat = @import("zat");
const fetched_car = @import("backfill/fetched_car.zig");
const prepared_fetch = @import("backfill/prepared_fetch.zig");
const verify = @import("verify.zig");
const metrics = @import("../runtime/metrics.zig");
const lru = @import("../storage/lru.zig");
const meta_store = @import("../storage/meta_store.zig");

const Io = std.Io;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.stream);

pub const worker_count = 32;
pub const queue_capacity = worker_count * 2;
pub const pending_capacity = 2048;
const lane_count = 4096;
const limiter_capacity = 16_384;
const refill_us = 12 * std.time.us_per_s; // five tokens per minute

const Bucket = struct { tokens: u8 = 5, last_us: i64 };

pub const PendingVerified = struct {
    arena: *std.heap.ArenaAllocator,
    event: zat.FirehoseEvent,
    verdict: verify.Result,
};

/// Ownership handed to the single archive writer. The fetched mmap and parse
/// arena remain live until all replacement rows have been emitted.
pub const Completion = struct {
    allocator: Allocator,
    io: Io,
    did: []u8,
    prepared_arena: *std.heap.ArenaAllocator,
    prepared: prepared_fetch.Prepared,
    fetched_chain: verify.ChainUpdate,
    pending: std.ArrayList(PendingVerified) = .empty,
    witnessed_at: i64,
    /// Successful synchronous #sync repair carries the original firehose
    /// cursor. Commit-triggered and retry repairs are synthetic and carry nil.
    upstream_seq: ?i64 = null,
    /// Byte-exact typed #sync envelope which triggered a synchronous repair.
    /// It must survive the trigger Job: the repair completion is emitted only
    /// after that Job has been retired and its decode arena freed.
    sync_payload: ?[]u8 = null,
    /// The trigger ticket must complete ordered emission before this repair
    /// may enter the archive. This preserves the verifier collector's global
    /// result order while per-DID apply remains asynchronous.
    after_ticket: u64,

    pub fn deinit(self: *Completion) void {
        for (self.pending.items) |item| {
            item.arena.deinit();
            self.allocator.destroy(item.arena);
        }
        self.pending.deinit(self.allocator);
        self.prepared.deinit(self.io);
        self.prepared_arena.deinit();
        self.allocator.destroy(self.prepared_arena);
        if (self.sync_payload) |payload| self.allocator.free(payload);
        self.allocator.free(self.did);
        self.allocator.destroy(self);
    }
};

const Status = enum { idle, resyncing };
const State = struct {
    did: []u8,
    status: Status = .idle,
    pending: std.ArrayList([]u8) = .empty,
    trigger_ticket: u64 = 0,
    sync_payload: ?[]u8 = null,
};
const Job = struct { did: []const u8, upstream_seq: ?i64 = null };

pub const Coordinator = struct {
    allocator: Allocator,
    io: Io,
    verifier: *verify.Verifier,
    relay_http: []const u8,
    scratch_dir: []const u8,
    stats: ?*metrics.Stats = null,
    emit_failure_logs: bool = true,
    publish_ctx: *anyopaque,
    publish: *const fn (*anyopaque, *Completion) anyerror!void,

    lanes: [lane_count]Io.Mutex = @splat(.init),
    states_mu: Io.Mutex = .init,
    states: std.StringHashMapUnmanaged(*State) = .empty,
    limiter_mu: Io.Mutex = .init,
    limiters: ?lru.LruCache(Bucket) = null,

    queue_mu: Io.Mutex = .init,
    queue_cond: Io.Condition = .init,
    queue_space: Io.Condition = .init,
    queue: [queue_capacity]?Job = @splat(null),
    queue_read: u64 = 0,
    queue_write: u64 = 0,
    accepting: bool = true,
    alive: bool = true,
    fatal_error: ?anyerror = null,
    futures: [worker_count]?Io.Future(void) = @splat(null),

    pub fn start(self: *Coordinator) !void {
        self.limiters = lru.LruCache(Bucket).init(self.allocator, limiter_capacity, self.io);
        var spawned: usize = 0;
        errdefer {
            self.stop();
            for (self.futures[0..spawned]) |*slot| {
                if (slot.*) |*future| _ = future.cancel(self.io);
            }
        }
        for (&self.futures) |*slot| {
            slot.* = try self.io.concurrent(workerLoop, .{self});
            spawned += 1;
        }
    }

    pub fn stop(self: *Coordinator) void {
        self.queue_mu.lockUncancelable(self.io);
        self.accepting = false;
        self.alive = false;
        self.queue_cond.broadcast(self.io);
        self.queue_space.broadcast(self.io);
        self.queue_mu.unlock(self.io);
        for (&self.futures) |*slot| {
            if (slot.*) |*future| _ = future.cancel(self.io);
            slot.* = null;
        }
    }

    /// Close the job queue and wait for accepted repairs to publish their
    /// completion. This is part of the archive cutover durability boundary.
    pub fn drainAndStop(self: *Coordinator) !void {
        self.queue_mu.lockUncancelable(self.io);
        self.accepting = false;
        self.queue_cond.broadcast(self.io);
        self.queue_mu.unlock(self.io);
        for (&self.futures) |*slot| {
            if (slot.*) |*future| _ = future.await(self.io);
            slot.* = null;
        }
        self.queue_mu.lockUncancelable(self.io);
        const failure = self.fatal_error;
        self.alive = false;
        self.queue_mu.unlock(self.io);
        if (failure) |err| return err;
    }

    pub fn deinit(self: *Coordinator) void {
        self.stop();
        var it = self.states.iterator();
        while (it.next()) |entry| self.freeState(entry.value_ptr.*);
        self.states.deinit(self.allocator);
        if (self.limiters) |*limiters| limiters.deinit();
        self.limiters = null;
    }

    pub fn fatalError(self: *Coordinator) ?anyerror {
        self.queue_mu.lockUncancelable(self.io);
        defer self.queue_mu.unlock(self.io);
        return self.fatal_error;
    }

    /// Verify one decoded frame while holding the same bounded per-DID lane
    /// used by repair apply. A commit arriving during fetch is copied into the
    /// bounded pending FIFO; the reader and other DIDs continue immediately.
    pub fn process(
        self: *Coordinator,
        resolver: *zat.DidResolver,
        frame: []const u8,
        event: zat.FirehoseEvent,
        ticket: u64,
    ) !verify.Result {
        const did = eventDid(event) orelse return .{};
        const lane = self.laneFor(did);
        lane.lockUncancelable(self.io);
        var lane_locked = true;
        defer if (lane_locked) lane.unlock(self.io);

        if (event == .commit) {
            if (self.getState(did)) |state| if (state.status == .resyncing) {
                try self.bufferPending(state, frame);
                return .{ .outcome = .needs_resync };
            };
        }

        const result = switch (event) {
            .commit => |value| try self.verifier.verifyCommit(resolver, value),
            .sync => |value| try self.verifier.verifySync(resolver, value),
            .identity => |value| blk: {
                self.verifier.evict(value.did);
                break :blk verify.Result{};
            },
            .account => |value| try self.verifier.onAccount(value),
            .info => verify.Result{},
        };
        if (result.outcome != .needs_resync) return result;

        // Unlike a broken #commit, Atmos first repairs #sync inline. The
        // network fetch is unlocked, and only a retry enters the async queue.
        if (event == .sync) {
            const sync_payload = try encodeSyncPayload(self.allocator, event.sync);
            const started = self.beginSynchronousRepairLocked(did, ticket, sync_payload) catch |err| {
                self.allocator.free(sync_payload);
                return err;
            };
            if (!started) {
                self.allocator.free(sync_payload);
                return result;
            }
            const state = self.getState(did).?;
            lane.unlock(self.io);
            lane_locked = false;
            self.runJob(resolver, .{ .did = state.did, .upstream_seq = event.sync.seq }) catch |err| {
                if (self.emit_failure_logs)
                    log.err("synchronous sync repair failed for {s}: {s}", .{ did, @errorName(err) });
                if (retryableSyncFailure(err)) {
                    lane.lockUncancelable(self.io);
                    lane_locked = true;
                    const retry_state = self.getState(did) orelse return error.RepairStateMissing;
                    retry_state.status = .idle;
                    self.noteFailed(err);
                    try self.scheduleLocked(did, ticket);
                } else {
                    self.failJob(did, err);
                }
            };
            return result;
        }

        try self.scheduleLocked(did, ticket);
        return result;
    }

    /// Begin the inline #sync attempt. Caller holds the DID lane. A repair
    /// already in flight is sufficient, so the sync directive is withheld.
    fn beginSynchronousRepairLocked(self: *Coordinator, did: []const u8, ticket: u64, sync_payload: []u8) !bool {
        const existing = self.getState(did);
        if (existing) |state| if (state.status == .resyncing) return false;
        const state = existing orelse try self.createState(did);
        state.status = .resyncing;
        state.trigger_ticket = ticket;
        if (state.sync_payload) |old| self.allocator.free(old);
        state.sync_payload = sync_payload;
        return true;
    }

    fn scheduleLocked(self: *Coordinator, did: []const u8, ticket: u64) !void {
        const existing = self.getState(did);
        const state = existing orelse try self.createState(did);
        if (state.status == .resyncing) return;
        state.status = .resyncing;
        state.trigger_ticket = ticket;

        self.queue_mu.lockUncancelable(self.io);
        defer self.queue_mu.unlock(self.io);
        while (self.alive and self.accepting and self.queue_write - self.queue_read >= queue_capacity)
            try self.queue_space.wait(self.io, &self.queue_mu);
        if (!self.alive or !self.accepting) return error.Closed;
        self.queue[self.queue_write % queue_capacity] = .{ .did = state.did };
        self.queue_write += 1;
        self.queue_cond.signal(self.io);
        if (self.stats) |stats| stats.resync_queue_depth.store(@intCast(self.queue_write - self.queue_read), .monotonic);
    }

    fn bufferPending(self: *Coordinator, state: *State, frame: []const u8) !void {
        const owned = try self.allocator.dupe(u8, frame);
        const grew = state.pending.items.len != pending_capacity;
        if (!grew) {
            const dropped = state.pending.orderedRemove(0);
            self.allocator.free(dropped);
            if (self.stats) |stats| _ = stats.resync_pending_dropped_total.fetchAdd(1, .monotonic);
            if (self.emit_failure_logs)
                log.err("repair pending overflow: {s}; dropped oldest commit", .{state.did});
        }
        try state.pending.append(self.allocator, owned);
        if (grew) {
            if (self.stats) |stats| _ = stats.resync_pending.fetchAdd(1, .monotonic);
        }
    }

    fn workerLoop(self: *Coordinator) void {
        var resolver = self.verifier.makeResolver();
        defer resolver.deinit();
        while (self.takeJob()) |job| self.runJob(&resolver, job) catch |err| {
            if (self.emit_failure_logs)
                log.err("repair worker failed for {s}: {s}", .{ job.did, @errorName(err) });
            self.failJob(job.did, err);
        };
    }

    fn takeJob(self: *Coordinator) ?Job {
        self.queue_mu.lockUncancelable(self.io);
        defer self.queue_mu.unlock(self.io);
        while (self.alive and self.queue_read == self.queue_write and self.accepting)
            self.queue_cond.wait(self.io, &self.queue_mu) catch {};
        if (!self.alive or (self.queue_read == self.queue_write and !self.accepting)) return null;
        const index = self.queue_read % queue_capacity;
        const job = self.queue[index].?;
        self.queue[index] = null;
        self.queue_read += 1;
        self.queue_space.signal(self.io);
        if (self.stats) |stats| stats.resync_queue_depth.store(@intCast(self.queue_write - self.queue_read), .monotonic);
        return job;
    }

    fn runJob(self: *Coordinator, resolver: *zat.DidResolver, job: Job) !void {
        if (self.stats) |stats| _ = stats.resync_active.fetchAdd(1, .monotonic);
        defer {
            if (self.stats) |stats| _ = stats.resync_active.fetchSub(1, .monotonic);
        }

        const now_us = Io.Timestamp.now(self.io, .real).toMicroseconds();
        if (!try self.takeRepairToken(job.did, now_us)) {
            if (self.stats) |stats| _ = stats.resync_rate_limited_total.fetchAdd(1, .monotonic);
            log.warn("repair rate limited: {s}", .{job.did});
            return error.RepairRateLimited;
        }

        var parse_arena = try self.allocator.create(std.heap.ArenaAllocator);
        parse_arena.* = std.heap.ArenaAllocator.init(self.allocator);
        errdefer {
            parse_arena.deinit();
            self.allocator.destroy(parse_arena);
        }
        var final_host: fetched_car.FinalHost = .{};
        const outcome = try prepared_fetch.fetch(
            self.allocator,
            parse_arena.allocator(),
            self.io,
            self.scratch_dir,
            self.relay_http,
            job.did,
            &final_host,
        );
        var prepared = switch (outcome) {
            .ok => |value| value,
            else => return error.GetRepoFailed,
        };
        errdefer prepared.deinit(self.io);

        const lane = self.laneFor(job.did);
        lane.lockUncancelable(self.io);
        defer lane.unlock(self.io);
        const state = self.getState(job.did) orelse return error.RepairStateMissing;
        if (state.status != .resyncing) return error.RepairStateMissing;
        const fetched = try self.verifier.verifyFetchedRepo(resolver, job.did, &prepared.repo);
        const fetched_chain = fetched.chain orelse return error.RepairAuthenticationFailed;
        try validateFetchedHead(try self.verifier.chainFor(job.did), fetched_chain);
        try self.verifier.rememberChain(job.did, fetched_chain);

        const completion = try self.allocator.create(Completion);
        errdefer self.allocator.destroy(completion);
        completion.* = .{
            .allocator = self.allocator,
            .io = self.io,
            .did = try self.allocator.dupe(u8, job.did),
            .prepared_arena = parse_arena,
            .prepared = prepared,
            .fetched_chain = fetched_chain,
            .witnessed_at = Io.Timestamp.now(self.io, .real).toMicroseconds(),
            .after_ticket = state.trigger_ticket,
            .upstream_seq = job.upstream_seq,
            .sync_payload = state.sync_payload,
        };
        state.sync_payload = null;
        errdefer {
            self.allocator.free(completion.did);
            if (completion.sync_payload) |payload| self.allocator.free(payload);
            for (completion.pending.items) |item| {
                item.arena.deinit();
                self.allocator.destroy(item.arena);
            }
            completion.pending.deinit(self.allocator);
        }

        for (state.pending.items) |raw| {
            const arena = try self.allocator.create(std.heap.ArenaAllocator);
            arena.* = std.heap.ArenaAllocator.init(self.allocator);
            const event = zat.firehose.decodeFrame(arena.allocator(), raw) catch {
                arena.deinit();
                self.allocator.destroy(arena);
                continue;
            };
            const verdict = switch (event) {
                .commit => |value| try self.verifier.verifyCommit(resolver, value),
                else => {
                    arena.deinit();
                    self.allocator.destroy(arena);
                    continue;
                },
            };
            switch (verdict.outcome) {
                .valid => try completion.pending.append(self.allocator, .{
                    .arena = arena,
                    .event = event,
                    .verdict = verdict,
                }),
                .replay => {
                    arena.deinit();
                    self.allocator.destroy(arena);
                },
                else => {
                    log.err("pending repair replay rejected: {s} reason={s}", .{ job.did, @tagName(verdict.outcome) });
                    arena.deinit();
                    self.allocator.destroy(arena);
                },
            }
        }
        // Registration under the DID lane is the ordered outbox boundary:
        // no later same-DID verification can finish before this callback.
        try self.publish(self.publish_ctx, completion);
        parse_arena = undefined;
        prepared = undefined;
        self.removeState(state);
        if (self.stats) |stats| _ = stats.resync_completed_total.fetchAdd(1, .monotonic);
    }

    fn failJob(self: *Coordinator, did: []const u8, err: anyerror) void {
        const lane = self.laneFor(did);
        lane.lockUncancelable(self.io);
        defer lane.unlock(self.io);
        if (self.getState(did)) |state| {
            if (state.pending.items.len == 0)
                self.removeState(state)
            else
                state.status = .idle;
        }
        self.noteFailed(err);
        // Local allocation/write/publication failures are fatal. Remote and
        // validation failures remain observable and allow a later retry.
        switch (err) {
            error.OutOfMemory, error.WriteFailed, error.ArchiveAppendFailed => self.setFatal(err),
            else => {},
        }
    }

    fn noteFailed(self: *Coordinator, err: anyerror) void {
        if (self.stats) |stats| _ = stats.resync_failed_total.fetchAdd(1, .monotonic);
        if (err == error.StaleRepair) {
            if (self.stats) |stats| _ = stats.resync_stale_total.fetchAdd(1, .monotonic);
        }
    }

    fn setFatal(self: *Coordinator, err: anyerror) void {
        self.queue_mu.lockUncancelable(self.io);
        defer self.queue_mu.unlock(self.io);
        if (self.fatal_error == null) self.fatal_error = err;
    }

    fn laneFor(self: *Coordinator, did: []const u8) *Io.Mutex {
        return &self.lanes[std.hash.Wyhash.hash(0, did) % lane_count];
    }

    fn getState(self: *Coordinator, did: []const u8) ?*State {
        self.states_mu.lockUncancelable(self.io);
        defer self.states_mu.unlock(self.io);
        return self.states.get(did);
    }

    fn createState(self: *Coordinator, did: []const u8) !*State {
        const state = try self.allocator.create(State);
        errdefer self.allocator.destroy(state);
        state.* = .{ .did = try self.allocator.dupe(u8, did) };
        errdefer self.allocator.free(state.did);
        self.states_mu.lockUncancelable(self.io);
        defer self.states_mu.unlock(self.io);
        try self.states.put(self.allocator, state.did, state);
        return state;
    }

    fn removeState(self: *Coordinator, state: *State) void {
        self.states_mu.lockUncancelable(self.io);
        _ = self.states.remove(state.did);
        self.states_mu.unlock(self.io);
        if (self.stats) |stats| _ = stats.resync_pending.fetchSub(state.pending.items.len, .monotonic);
        self.freeState(state);
    }

    fn freeState(self: *Coordinator, state: *State) void {
        for (state.pending.items) |frame| self.allocator.free(frame);
        state.pending.deinit(self.allocator);
        if (state.sync_payload) |payload| self.allocator.free(payload);
        self.allocator.free(state.did);
        self.allocator.destroy(state);
    }

    fn takeRepairToken(self: *Coordinator, did: []const u8, now_us: i64) !bool {
        self.limiter_mu.lockUncancelable(self.io);
        defer self.limiter_mu.unlock(self.io);
        const limiters = &(self.limiters orelse return error.CoordinatorNotStarted);
        var bucket = limiters.get(did) orelse Bucket{ .last_us = now_us };
        const allowed = takeToken(&bucket, now_us);
        try limiters.put(did, bucket);
        return allowed;
    }
};

fn encodeSyncPayload(allocator: Allocator, sync_event: zat.firehose.SyncEvent) ![]u8 {
    const entries = [_]zat.cbor.Value.MapEntry{
        .{ .key = "did", .value = .{ .text = sync_event.did } },
        .{ .key = "rev", .value = .{ .text = sync_event.rev } },
        .{ .key = "seq", .value = .{ .unsigned = @intCast(@max(sync_event.seq, 0)) } },
        .{ .key = "time", .value = .{ .text = sync_event.time } },
        .{ .key = "blocks", .value = .{ .bytes = sync_event.blocks } },
    };
    return zat.cbor.encodeAlloc(allocator, .{ .map = &entries });
}

fn takeToken(bucket: *Bucket, now_us: i64) bool {
    if (now_us > bucket.last_us) {
        const steps: u64 = @intCast(@divFloor(now_us - bucket.last_us, refill_us));
        if (steps != 0) {
            bucket.tokens = @intCast(@min(@as(u64, bucket.tokens) + steps, 5));
            bucket.last_us += @as(i64, @intCast(steps)) * refill_us;
        }
    }
    if (bucket.tokens == 0) return false;
    bucket.tokens -= 1;
    return true;
}

fn validateFetchedHead(current: ?verify.ChainUpdate, fetched: verify.ChainUpdate) !void {
    const seen = current orelse return;
    switch (std.mem.order(u8, &fetched.rev, &seen.rev)) {
        .lt => return error.StaleRepair,
        .eq => if (!std.mem.eql(u8, fetched.dataSlice(), seen.dataSlice()))
            return error.ContradictoryRepair,
        .gt => {},
    }
}

/// Match Atmos's one deferred retry for transport/rate-limit failures of a
/// synchronous #sync repair. Authentication and rev-regression failures are
/// deterministic and deliberately do not retry the same authoritative head.
fn retryableSyncFailure(err: anyerror) bool {
    return switch (err) {
        error.GetRepoFailed,
        error.AttemptTimeout,
        error.TransferTooSlow,
        error.RepairRateLimited,
        error.ConnectionRefused,
        error.ConnectionResetByPeer,
        error.NetworkUnreachable,
        error.TemporaryNameServerFailure,
        => true,
        else => false,
    };
}

fn eventDid(event: zat.FirehoseEvent) ?[]const u8 {
    return switch (event) {
        .commit => |value| value.repo,
        .sync => |value| value.did,
        .identity => |value| value.did,
        .account => |value| value.did,
        .info => null,
    };
}

test "repair limiter matches upstream five per minute burst five" {
    var bucket: Bucket = .{ .last_us = 1_000_000 };
    for (0..5) |_| try std.testing.expect(takeToken(&bucket, 1_000_000));
    try std.testing.expect(!takeToken(&bucket, 1_000_000));
    try std.testing.expect(!takeToken(&bucket, 1_000_000 + 11 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 12 * std.time.us_per_s));
    try std.testing.expect(!takeToken(&bucket, 1_000_000 + 12 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
    try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
    try std.testing.expect(!takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
}

test "repair apply rejects older and contradictory authoritative heads" {
    var current: verify.ChainUpdate = .{ .rev = undefined, .data_len = 3 };
    @memcpy(&current.rev, "3k2abcdefghij");
    @memcpy(current.data[0..3], "one");
    var fetched = current;
    try validateFetchedHead(current, fetched);
    @memcpy(fetched.data[0..3], "two");
    try std.testing.expectError(error.ContradictoryRepair, validateFetchedHead(current, fetched));
    @memcpy(&fetched.rev, "3k2abc0000000");
    try std.testing.expectError(error.StaleRepair, validateFetchedHead(current, fetched));
    @memcpy(&fetched.rev, "3k2zzzzzzzzzz");
    try validateFetchedHead(current, fetched);
}

test "pending FIFO is bounded at 2048 and drops the oldest real frame" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    var stats: metrics.Stats = .{};
    var coordinator: Coordinator = .{
        .allocator = testing.allocator,
        .io = threaded.io(),
        .verifier = undefined,
        .relay_http = "http://offline.invalid",
        .scratch_dir = "unused",
        .stats = &stats,
        .emit_failure_logs = false,
        .publish_ctx = undefined,
        .publish = undefined,
    };
    var state: State = .{ .did = @constCast("did:plc:pending-fixture") };
    defer {
        for (state.pending.items) |frame| testing.allocator.free(frame);
        state.pending.deinit(testing.allocator);
    }
    var frame_buf: [16]u8 = undefined;
    for (0..pending_capacity + 1) |i| {
        const frame = try std.fmt.bufPrint(&frame_buf, "frame-{d}", .{i});
        try coordinator.bufferPending(&state, frame);
    }
    try testing.expectEqual(@as(usize, pending_capacity), state.pending.items.len);
    try testing.expectEqualStrings("frame-1", state.pending.items[0]);
    try testing.expectEqualStrings("frame-2048", state.pending.items[pending_capacity - 1]);
    try testing.expectEqual(@as(u64, 1), stats.resync_pending_dropped_total.load(.monotonic));
    try testing.expectEqual(@as(usize, pending_capacity), stats.resync_pending.load(.monotonic));
}

test "offline worker pool performs exactly 32 concurrent real HTTP fetches" {
    const testing = std.testing;
    const request_count = 40;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer server.deinit(io);
    var active: std.atomic.Value(usize) = .init(0);
    var maximum: std.atomic.Value(usize) = .init(0);
    var reached_pool: Io.Event = .unset;
    var release: Io.Event = .unset;

    const Fixture = struct {
        fn serveOne(
            stream_value: Io.net.Stream,
            task_io: Io,
            active_count: *std.atomic.Value(usize),
            max_count: *std.atomic.Value(usize),
            reached: *Io.Event,
            release_gate: *Io.Event,
        ) void {
            var stream = stream_value;
            defer stream.close(task_io);
            var read_buf: [2048]u8 = undefined;
            var write_buf: [2048]u8 = undefined;
            var reader = stream.reader(task_io, &read_buf);
            var writer = stream.writer(task_io, &write_buf);
            var http_server = std.http.Server.init(&reader.interface, &writer.interface);
            var request = http_server.receiveHead() catch return;
            const now = active_count.fetchAdd(1, .acq_rel) + 1;
            var seen = max_count.load(.acquire);
            while (now > seen) {
                seen = max_count.cmpxchgWeak(seen, now, .acq_rel, .acquire) orelse break;
            }
            if (now == worker_count) reached.set(task_io);
            release_gate.wait(task_io) catch return;
            request.respond("", .{ .status = .service_unavailable, .keep_alive = false }) catch return;
            _ = active_count.fetchSub(1, .acq_rel);
        }

        fn run(
            listener: *Io.net.Server,
            task_io: Io,
            active_count: *std.atomic.Value(usize),
            max_count: *std.atomic.Value(usize),
            reached: *Io.Event,
            release_gate: *Io.Event,
        ) !void {
            var futures: [request_count]?Io.Future(void) = @splat(null);
            for (&futures) |*slot| {
                const stream = try listener.accept(task_io);
                slot.* = try task_io.concurrent(serveOne, .{ stream, task_io, active_count, max_count, reached, release_gate });
            }
            for (&futures) |*slot| {
                if (slot.*) |*future| _ = future.await(task_io);
            }
        }
    };
    var server_future = try io.concurrent(Fixture.run, .{ &server, io, &active, &maximum, &reached_pool, &release });
    defer _ = server_future.cancel(io) catch {};
    var url_buf: [96]u8 = undefined;
    const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const root_len = try tmp.dir.realPath(io, &root_buf);
    const root = root_buf[0..root_len];
    var meta = try meta_store.Store.open(testing.allocator, root);
    defer meta.deinit();
    var verifier = verify.Verifier.init(testing.allocator, io, "http://offline.invalid", &meta);
    defer verifier.deinit();
    const NoPublish = struct {
        fn publish(_: *anyopaque, _: *Completion) !void {
            return error.UnexpectedCompletion;
        }
    };
    var scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const scratch = try std.fmt.bufPrint(&scratch_buf, "{s}/scratch", .{root});
    var coordinator: Coordinator = .{
        .allocator = testing.allocator,
        .io = io,
        .verifier = &verifier,
        .relay_http = url,
        .scratch_dir = scratch,
        .emit_failure_logs = false,
        .publish_ctx = undefined,
        .publish = NoPublish.publish,
    };
    defer coordinator.deinit();
    try coordinator.start();
    for (0..request_count) |i| {
        var did_buf: [64]u8 = undefined;
        const did = try std.fmt.bufPrint(&did_buf, "did:plc:worker-{d}", .{i});
        const lane = coordinator.laneFor(did);
        lane.lockUncancelable(io);
        try coordinator.scheduleLocked(did, i);
        lane.unlock(io);
    }
    try reached_pool.waitTimeout(io, .{ .duration = .{ .raw = Io.Duration.fromSeconds(2), .clock = .awake } });
    try testing.expectEqual(@as(usize, worker_count), active.load(.acquire));
    release.set(io);
    try coordinator.drainAndStop();
    _ = try server_future.await(io);
    try testing.expectEqual(@as(usize, worker_count), maximum.load(.acquire));
}

test "offline coordinator fetches and authenticates a real complete repo" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(21));
    const did = "did:plc:repairfixture";
    const did_key = try keypair.did(alloc);
    const multibase = did_key["did:key:".len..];
    const record = try zat.cbor.encodeAlloc(alloc, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
        .{ .key = "text", .value = .{ .text = "offline repair" } },
    } });
    const record_cid = try zat.cbor.Cid.forDagCbor(alloc, record);
    var tree = zat.mst.Mst.init(alloc);
    try tree.put("app.bsky.feed.post/3k2abcdefghij", record_cid);
    const data_cid = try tree.rootCid();
    const signed = try zat.signCommit(alloc, .{
        .did = did,
        .rev = "3k2abcdefghij",
        .data = data_cid,
    }, &keypair);
    var blocks: std.ArrayList(zat.car.Block) = .empty;
    try blocks.append(alloc, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
    try tree.collectBlocks(&blocks);
    try blocks.append(alloc, .{ .cid_raw = record_cid.raw, .data = record });
    const car_bytes = try zat.car.writeAlloc(alloc, .{ .roots = &.{signed.cid}, .blocks = blocks.items });
    const did_doc = try std.fmt.allocPrint(alloc,
        \\{{"id":"{s}","verificationMethod":[{{"id":"{s}#atproto","type":"Multikey","controller":"{s}","publicKeyMultibase":"{s}"}}]}}
    , .{ did, did, did, multibase });

    var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer server.deinit(io);
    var fetch_started: Io.Event = .unset;
    var release_fetch: Io.Event = .unset;
    const Fixture = struct {
        fn run(listener: *Io.net.Server, task_io: Io, doc: []const u8, car: []const u8, started: *Io.Event, release: *Io.Event) !void {
            for (0..2) |_| {
                var stream = try listener.accept(task_io);
                defer stream.close(task_io);
                var read_buf: [4096]u8 = undefined;
                var write_buf: [4096]u8 = undefined;
                var reader = stream.reader(task_io, &read_buf);
                var writer = stream.writer(task_io, &write_buf);
                var http_server = std.http.Server.init(&reader.interface, &writer.interface);
                var request = try http_server.receiveHead();
                const is_repo = std.mem.startsWith(u8, request.head.target, "/xrpc/");
                if (is_repo) {
                    started.set(task_io);
                    try release.wait(task_io);
                }
                const body = if (is_repo) car else doc;
                try request.respond(body, .{
                    .status = .ok,
                    .keep_alive = false,
                    .extra_headers = &.{.{
                        .name = "content-type",
                        .value = if (is_repo) "application/vnd.ipld.car" else "application/json",
                    }},
                });
            }
        }
    };
    var server_future = try io.concurrent(Fixture.run, .{ &server, io, did_doc, car_bytes, &fetch_started, &release_fetch });
    defer _ = server_future.cancel(io) catch {};
    var url_buf: [96]u8 = undefined;
    const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const root_len = try tmp.dir.realPath(io, &root_buf);
    const root = root_buf[0..root_len];
    var meta = try meta_store.Store.open(testing.allocator, root);
    defer meta.deinit();
    var verifier = verify.Verifier.init(testing.allocator, io, url, &meta);
    defer verifier.deinit();

    const Published = struct {
        completion: ?*Completion = null,
        fn publish(ctx: *anyopaque, completion: *Completion) !void {
            const self: *@This() = @ptrCast(@alignCast(ctx));
            if (self.completion != null) return error.DuplicateCompletion;
            self.completion = completion;
        }
    };
    var published: Published = .{};
    var scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const scratch = try std.fmt.bufPrint(&scratch_buf, "{s}/scratch", .{root});
    var coordinator: Coordinator = .{
        .allocator = testing.allocator,
        .io = io,
        .verifier = &verifier,
        .relay_http = url,
        .scratch_dir = scratch,
        .publish_ctx = &published,
        .publish = Published.publish,
    };
    defer coordinator.deinit();
    try coordinator.start();
    var resolver = verifier.makeResolver();
    defer resolver.deinit();
    const sync_event: zat.FirehoseEvent = .{ .sync = .{
        .seq = 1,
        .did = did,
        .rev = "3k2abcdefghij",
        .time = "2026-07-16T00:00:00Z",
        .blocks = &.{},
    } };
    const SyncTask = struct {
        coordinator: *Coordinator,
        resolver: *zat.DidResolver,
        event: zat.FirehoseEvent,
        result: ?(anyerror!verify.Result) = null,

        fn run(self: *@This()) void {
            self.result = self.coordinator.process(self.resolver, "", self.event, 0);
        }
    };
    var sync_task: SyncTask = .{ .coordinator = &coordinator, .resolver = &resolver, .event = sync_event };
    var sync_future = try io.concurrent(SyncTask.run, .{&sync_task});
    defer _ = sync_future.cancel(io);
    try fetch_started.wait(io);

    // The HTTP response is deliberately held open. A same-DID commit must
    // still return immediately into the real pending FIFO: fetch I/O never
    // owns the per-DID apply lane.
    const pending_frame = try zat.firehose.encodeCommitEvent(alloc, .{
        .seq = 2,
        .repo_did = did,
        .commit_cid = signed.cid,
        .rev = "3k2abcdefghij",
        .blocks = car_bytes,
        .ops = &.{.{
            .action = .create,
            .collection = "app.bsky.feed.post",
            .rkey = "3k2abcdefghij",
            .cid = record_cid,
        }},
        .time = "2026-07-16T00:00:01Z",
    });
    var pending_arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer pending_arena.deinit();
    const pending_event = try zat.firehose.decodeFrame(pending_arena.allocator(), pending_frame);
    const buffered = try coordinator.process(&resolver, pending_frame, pending_event, 1);
    try testing.expectEqual(verify.Outcome.needs_resync, buffered.outcome);
    release_fetch.set(io);
    _ = sync_future.await(io);
    const result = try sync_task.result.?;
    try testing.expectEqual(verify.Outcome.needs_resync, result.outcome);
    try coordinator.drainAndStop();
    _ = try server_future.await(io);

    const completion = published.completion orelse return error.MissingCompletion;
    defer completion.deinit();
    try testing.expectEqualStrings(did, completion.did);
    try testing.expectEqualStrings("3k2abcdefghij", &completion.fetched_chain.rev);
    try testing.expectEqualSlices(u8, data_cid.raw, completion.fetched_chain.dataSlice());
    try testing.expectEqual(@as(usize, 0), completion.pending.items.len);
    try testing.expectEqual(@as(?i64, 1), completion.upstream_seq);
    try testing.expectEqual(@as(?anyerror, null), coordinator.fatalError());
}