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

zat.dev/stream

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

0
0
914 lines · 40.2 KB Raw History
//! retry — steady-state failed-repo retry loop
//!
//! upstream RunFailedRepoRetry (docs/upstream-bootstrap-spec.md): every
//! interval (default 4h), scan failed repos and resync each via the
//! relay (sync tombstone + create_resync rows, see resync.zig). appends
//! land on the shared archive beside the live consumer — safe under the
//! archive writer mutex, and the on_append hook keeps the compactor's
//! live tombstone set coherent.
//!
//! The relay redirects getRepo to independently operated PDSes. Retry
//! attribution and 429 parking therefore use the final post-redirect host,
//! never the relay host.

const std = @import("std");
const archive_mod = @import("../../storage/archive.zig");
const metrics = @import("../../runtime/metrics.zig");
const meta_store = @import("../../storage/meta_store.zig");
const observability = @import("../../runtime/observability.zig");
const repo_store = @import("repo_store.zig");
const repos = @import("repos.zig");
const resync = @import("resync.zig");

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

pub const Stats = struct {
    candidates: u64 = 0,
    succeeded: u64 = 0,
    failed: u64 = 0,
    deferred: u64 = 0,
};

pub const default_interval_ns: u64 = 4 * std.time.ns_per_hour;
pub const default_workers: usize = 16;
pub const default_host_workers: usize = 4;
pub const default_max_delay_ns: u64 = 7 * 24 * std.time.ns_per_hour;

const HostGate = struct {
    mu: Io.Mutex = .init,
    available: Io.Condition = .init,
    active: usize = 0,

    fn acquire(self: *HostGate, io: Io, limit: usize) void {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        while (self.active >= limit) self.available.waitUncancelable(io, &self.mu);
        self.active += 1;
    }

    fn release(self: *HostGate, io: Io) void {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        self.active -= 1;
        self.available.signal(io);
    }
};

pub const Retry = struct {
    allocator: Allocator,
    io: Io,
    archive: *archive_mod.Archive,
    meta: *meta_store.Store,
    data_dir: []const u8,
    relay_http: []const u8,
    /// nanoseconds between passes; 0 disables (run() returns immediately)
    interval_ns: u64 = default_interval_ns,
    /// backoff ceiling (upstream DefaultFailedRepoRetryMaxDelay: 7d)
    max_delay_ns: u64 = default_max_delay_ns,
    workers: usize = default_workers,
    host_workers: usize = default_host_workers,
    stop_flag: std.atomic.Value(bool) = .init(false),
    stop_event: Io.Event = .unset,
    stats: ?*metrics.Stats = null,
    trace_context: observability.Context = observability.root_context,
    emit_failure_logs: bool = true,
    jitter_ctx: ?*anyopaque = null,
    jitter: ?*const fn (?*anyopaque, u64) u64 = null,
    /// Set when a pass fails for a reason that is ours rather than a remote's.
    /// Upstream runs this loop inside an errgroup, so returning an error there
    /// cancels the steady-state consumer; this is how that reaches the process.
    shutdown: ?*std.atomic.Value(bool) = null,
    /// Latched terminal error, exposed so health can report why we are going
    /// down rather than leaving a dead subsystem behind a green check.
    terminal_error: std.atomic.Value(bool) = .init(false),
    /// Hosts parked by a 429, held for this runner's lifetime like upstream's
    /// `hostParked` map rather than in durable metadata.
    parked: std.StringHashMapUnmanaged(i64) = .empty,
    park_mu: Io.Mutex = .init,
    /// Which repositories a pass selects. Upstream's RunPendingRepoRetryPass is
    /// the same runner with eligibleStatus flipped to pending, so the merge's
    /// pending pass inherits the worker pool, per-host gate, backoff and 429
    /// parking instead of reimplementing a weaker version of them.
    eligible_status: repo_store.Status = .failed,

    pub fn failed(self: *const Retry) bool {
        return self.terminal_error.load(.acquire);
    }

    pub fn init(allocator: Allocator, io: Io, archive: *archive_mod.Archive, meta: *meta_store.Store, data_dir: []const u8, relay_http: []const u8) Retry {
        return .{
            .allocator = allocator,
            .io = io,
            .archive = archive,
            .meta = meta,
            .data_dir = data_dir,
            .relay_http = relay_http,
        };
    }

    pub fn deinit(self: *Retry) void {
        var it = self.parked.keyIterator();
        while (it.next()) |key| self.allocator.free(key.*);
        self.parked.deinit(self.allocator);
    }

    pub fn requestStop(self: *Retry) void {
        self.stop_flag.store(true, .release);
        self.stop_event.set(self.io);
    }

    /// timer loop; spawn via io.concurrent, stop via requestStop. a pass that
    /// fails for our own reasons latches terminal_error and requests shutdown,
    /// mirroring upstream's errgroup; per-repo remote failures never get here.
    pub fn run(self: *Retry) void {
        if (self.interval_ns == 0) return;
        const interval: Io.Clock.Duration = .{
            .raw = Io.Duration.fromNanoseconds(@intCast(self.interval_ns)),
            .clock = .awake,
        };
        while (!self.stop_flag.load(.acquire)) {
            const deadline = Io.Clock.Timestamp.fromNow(self.io, interval);
            while (Io.Clock.Timestamp.now(self.io, .awake).compare(.lt, deadline)) {
                self.stop_event.waitTimeout(self.io, .{ .deadline = deadline }) catch |err| switch (err) {
                    // Event waits may wake spuriously. Preserve the configured
                    // interval by checking the absolute monotonic deadline.
                    error.Timeout => continue,
                    error.Canceled => return,
                };
                if (self.stop_flag.load(.acquire)) return;
            }
            if (self.stop_flag.load(.acquire)) return;
            const stats = self.runPass() catch |err| {
                // Remote failures never reach here: processDid converts them
                // into per-repo backoff. An error escaping a pass means our own
                // store, archive, or memory failed. Upstream returns it out of
                // RunFailedRepoRetry and its errgroup takes the service down;
                // continuing would leave repositories silently unhealed behind
                // a green health check.
                if (self.stop_flag.load(.acquire)) return;
                if (self.emit_failure_logs)
                    log.err("failed-repo retry pass failed: {s}; stopping stream", .{@errorName(err)});
                if (self.stats) |s| _ = s.retry_terminal_failures_total.fetchAdd(1, .monotonic);
                self.terminal_error.store(true, .release);
                if (self.shutdown) |flag| flag.store(true, .release);
                return;
            };
            if (stats.candidates > 0)
                log.info("failed-repo retry pass: {d} candidates, {d} resynced, {d} re-deferred, {d} skipped", .{
                    stats.candidates, stats.succeeded, stats.failed, stats.deferred,
                });
        }
    }

    /// one streaming scan over failed repos; also the test seam
    pub fn runPass(self: *Retry) !Stats {
        if (self.stats) |s| _ = s.retry_passes_total.fetchAdd(1, .monotonic);
        var store = try repo_store.Store.init(self.allocator, self.io, self.meta);
        defer store.deinit();

        const worker_count = self.effectiveWorkers();
        // Upstream feeds a channel of Workers*2. Bounding the hand-off is the
        // point: the scan must never materialize the whole failed set.
        const slots = try self.allocator.alloc(Candidate, worker_count * 2);
        defer self.allocator.free(slots);

        var work: RetryWork = .{
            .retry = self,
            .store = &store,
            .queue = .{ .buffer = slots },
        };
        defer work.deinitGates(self.allocator);

        var group: Io.Group = .init;
        var settled = false;
        // Cancelled workers can leave candidates in the ring; their copies are
        // ours to free. Runs after the group is settled, so no worker can be
        // holding one.
        defer work.queue.drain(self.io, self.allocator);
        errdefer if (!settled) {
            work.queue.close(self.io);
            group.cancel(self.io);
        };
        for (0..worker_count) |_| try group.concurrent(self.io, RetryWork.runWorker, .{&work});

        const scan_result = store.streamByStatus(self.eligible_status, &work, RetryWork.offer);
        work.queue.close(self.io);
        group.await(self.io) catch |err| {
            // The group is settled either way; cancelling it again here would
            // double-manage it.
            settled = true;
            return err;
        };
        settled = true;
        // RetryPassAborted only means the scan stopped early because a worker
        // failed or shutdown was requested. The real cause, if any, is
        // fatal_error; reporting the sentinel would turn an ordinary stop into
        // a terminal failure.
        scan_result catch |err| if (err != error.RetryPassAborted) return err;
        if (work.fatal_error) |err| return err;
        return .{
            .candidates = work.candidates.load(.monotonic),
            .succeeded = work.succeeded.load(.monotonic),
            .failed = work.failed.load(.monotonic),
            .deferred = work.deferred.load(.monotonic),
        };
    }

    /// Park state lives in memory for the runner's lifetime, as upstream's
    /// `retryRunner.hostParked` does. It was persisted here for no recorded
    /// reason — swept into a durability commit — which made a restart honour a
    /// rate limit upstream would have forgotten, and added a metadata read to
    /// a path that does not need one. Zero means not parked.
    fn loadHostPark(self: *Retry, host: []const u8) !i64 {
        self.park_mu.lockUncancelable(self.io);
        defer self.park_mu.unlock(self.io);
        return self.parked.get(host) orelse 0;
    }

    /// Upstream's parkHost keeps the later deadline: a park never shortens, so
    /// a second rate limit cannot un-park a host early. Ours did not have that
    /// rule while it was persisted.
    fn saveHostPark(self: *Retry, host: []const u8, deadline: i64) !void {
        self.park_mu.lockUncancelable(self.io);
        defer self.park_mu.unlock(self.io);
        const existing = try self.parked.getOrPut(self.allocator, host);
        if (existing.found_existing) {
            if (existing.value_ptr.* >= deadline) return;
        } else {
            existing.key_ptr.* = try self.allocator.dupe(u8, host);
        }
        existing.value_ptr.* = deadline;
    }

    /// Upstream's exponential delay plus [0, delay/2) jitter, capped at
    /// max_delay. retry_count is one-based after recording this failure.
    fn backoffDelayUs(self: *Retry, retry_count: u32) u64 {
        const attempt = retry_count -| 1;
        const max_delay_ns = self.effectiveMaxDelayNs();
        var delay_ns = max_delay_ns;
        if (self.interval_ns > 0 and attempt < @clz(self.interval_ns)) {
            const shifted = self.interval_ns << @intCast(attempt);
            if (shifted < max_delay_ns) delay_ns = shifted;
        }
        const half = delay_ns / 2;
        if (half > 0) delay_ns +|= self.jitterBelow(half);
        return @min(delay_ns, max_delay_ns) / std.time.ns_per_us;
    }

    fn jitterBelow(self: *Retry, upper: u64) u64 {
        if (self.jitter) |jitter| return @min(jitter(self.jitter_ctx, upper), upper - 1);
        var source: std.Random.IoSource = .{ .io = self.io };
        return source.interface().uintLessThan(u64, upper);
    }

    fn effectiveWorkers(self: *const Retry) usize {
        return if (self.workers == 0) default_workers else self.workers;
    }

    fn effectiveHostWorkers(self: *const Retry) usize {
        return if (self.host_workers == 0) default_host_workers else self.host_workers;
    }

    fn effectiveMaxDelayNs(self: *const Retry) u64 {
        return if (self.max_delay_ns == 0) default_max_delay_ns else self.max_delay_ns;
    }
};

/// One repository handed from the scan to a worker. The strings are copies:
/// the scan's borrow ends when the iterator advances.
const Candidate = struct {
    did: []u8,
    host: []u8,

    fn deinit(self: Candidate, allocator: Allocator) void {
        allocator.free(self.did);
        allocator.free(self.host);
    }
};

/// Bounded hand-off. `put` blocks while full, which is what applies
/// backpressure to the scan and keeps the failed set off the heap.
const CandidateQueue = struct {
    buffer: []Candidate,
    head: usize = 0,
    len: usize = 0,
    closed: bool = false,
    mu: Io.Mutex = .init,
    not_empty: Io.Condition = .init,
    not_full: Io.Condition = .init,

    fn put(self: *CandidateQueue, io: Io, item: Candidate) bool {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        while (self.len == self.buffer.len and !self.closed)
            self.not_full.waitUncancelable(io, &self.mu);
        if (self.closed) return false;
        self.buffer[(self.head + self.len) % self.buffer.len] = item;
        self.len += 1;
        self.not_empty.signal(io);
        return true;
    }

    fn pop(self: *CandidateQueue, io: Io) ?Candidate {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        while (self.len == 0 and !self.closed)
            self.not_empty.waitUncancelable(io, &self.mu);
        if (self.len == 0) return null;
        const item = self.buffer[self.head];
        self.head = (self.head + 1) % self.buffer.len;
        self.len -= 1;
        self.not_full.signal(io);
        return item;
    }

    fn close(self: *CandidateQueue, io: Io) void {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        self.closed = true;
        self.not_empty.broadcast(io);
        self.not_full.broadcast(io);
    }

    /// Free anything workers never claimed. Only safe once the worker group
    /// has settled.
    fn drain(self: *CandidateQueue, io: Io, allocator: Allocator) void {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io);
        while (self.len > 0) {
            self.buffer[self.head].deinit(allocator);
            self.head = (self.head + 1) % self.buffer.len;
            self.len -= 1;
        }
    }
};

const RetryWork = struct {
    retry: *Retry,
    store: *repo_store.Store,
    queue: CandidateQueue,
    /// Created on demand like upstream's acquireHost, so a pass never
    /// allocates a gate for every host in the archive up front.
    gates: std.StringHashMapUnmanaged(*HostGate) = .empty,
    gates_mu: Io.Mutex = .init,
    candidates: std.atomic.Value(u64) = .init(0),
    succeeded: std.atomic.Value(u64) = .init(0),
    failed: std.atomic.Value(u64) = .init(0),
    deferred: std.atomic.Value(u64) = .init(0),
    fatal_mu: Io.Mutex = .init,
    fatal_error: ?anyerror = null,

    /// Scan callback. Filters exactly what upstream's scanDue filters before
    /// a candidate ever occupies a queue slot.
    fn offer(self: *RetryWork, did: []const u8, state: repo_store.RepoState) !void {
        if (self.retry.stop_flag.load(.acquire) or self.fatal() != null) return error.RetryPassAborted;
        const now_us: i64 = Io.Timestamp.now(self.retry.io, .real).toMicroseconds();
        if (!state.active or state.next_attempt_us > now_us) {
            _ = self.deferred.fetchAdd(1, .monotonic);
            return;
        }
        const host = if (state.host.len > 0) state.host else "unknown";
        const did_copy = try self.retry.allocator.dupe(u8, did);
        errdefer self.retry.allocator.free(did_copy);
        const host_copy = try self.retry.allocator.dupe(u8, host);
        errdefer self.retry.allocator.free(host_copy);
        const item: Candidate = .{ .did = did_copy, .host = host_copy };
        if (!self.queue.put(self.retry.io, item)) {
            item.deinit(self.retry.allocator);
            return error.RetryPassAborted;
        }
    }

    fn gateFor(self: *RetryWork, host: []const u8) !*HostGate {
        self.gates_mu.lockUncancelable(self.retry.io);
        defer self.gates_mu.unlock(self.retry.io);
        if (self.gates.get(host)) |gate| return gate;
        const key = try self.retry.allocator.dupe(u8, host);
        errdefer self.retry.allocator.free(key);
        const gate = try self.retry.allocator.create(HostGate);
        errdefer self.retry.allocator.destroy(gate);
        gate.* = .{};
        try self.gates.put(self.retry.allocator, key, gate);
        return gate;
    }

    fn deinitGates(self: *RetryWork, allocator: Allocator) void {
        var it = self.gates.iterator();
        while (it.next()) |entry| {
            allocator.free(entry.key_ptr.*);
            allocator.destroy(entry.value_ptr.*);
        }
        self.gates.deinit(allocator);
    }

    fn runWorker(self: *RetryWork) void {
        while (self.queue.pop(self.retry.io)) |candidate| {
            defer candidate.deinit(self.retry.allocator);
            if (self.retry.stop_flag.load(.acquire) or self.fatal() != null) continue;
            self.processCandidate(candidate) catch |err| self.recordFatal(err);
        }
    }

    fn processCandidate(self: *RetryWork, candidate: Candidate) !void {
        const did = candidate.did;
        const now_us: i64 = Io.Timestamp.now(self.retry.io, .real).toMicroseconds();
        // Re-read under the worker: the scan's snapshot may be stale by the
        // time a slot frees, and the durable row is the authority.
        const state = (try self.store.get(self.retry.allocator, did)) orelse return;
        defer self.store.freeState(self.retry.allocator, state);
        if (!state.active or state.next_attempt_us > now_us) {
            _ = self.deferred.fetchAdd(1, .monotonic);
            return;
        }
        _ = self.candidates.fetchAdd(1, .monotonic);
        if (self.retry.stats) |s| _ = s.retry_candidates_total.fetchAdd(1, .monotonic);
        const candidate_host = if (state.host.len > 0) state.host else "unknown";
        if (try self.retry.loadHostPark(candidate_host) > Io.Timestamp.now(self.retry.io, .real).toMicroseconds()) {
            _ = self.deferred.fetchAdd(1, .monotonic);
            if (self.retry.stats) |s| _ = s.retry_skipped_host_parked_total.fetchAdd(1, .monotonic);
            return;
        }
        const gate = try self.gateFor(candidate_host);
        gate.acquire(self.retry.io, self.retry.effectiveHostWorkers());
        defer gate.release(self.retry.io);

        // Recheck after waiting: a sibling on this host may have received a
        // 429 and parked the bucket while this job was queued at the gate.
        if (try self.retry.loadHostPark(candidate_host) > Io.Timestamp.now(self.retry.io, .real).toMicroseconds()) {
            _ = self.deferred.fetchAdd(1, .monotonic);
            if (self.retry.stats) |s| _ = s.retry_skipped_host_parked_total.fetchAdd(1, .monotonic);
            return;
        }

        var drops: repos.DropCounts = .{};
        var details: resync.AttemptDetails = .{};
        var scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
        const scratch_dir = try std.fmt.bufPrint(&scratch_buf, "{s}/repair-scratch/failed-repo", .{self.retry.data_dir});
        if (self.retry.stats) |s| _ = s.retry_attempts_total.fetchAdd(1, .monotonic);
        _ = resync.resyncRepo(self.retry.allocator, self.retry.io, scratch_dir, self.retry.relay_http, state.pds, did, self.retry.archive, self.store, &drops, &details, self.retry.trace_context) catch |err| {
            if (err == error.InvalidCommitRev) {
                if (self.retry.stats) |s| _ = s.backfill_drops.getPtr(.invalid_rev).fetchAdd(1, .monotonic);
            }
            if (details.local_failure) return err;
            switch (err) {
                error.OutOfMemory, error.ArchiveAppendFailed => return err,
                else => {},
            }
            const count = state.retry_count + 1;
            const retry_delay_us = if (err == error.RateLimited and details.retry_after_s != null)
                @min(details.retry_after_s.? *| std.time.ns_per_s, self.retry.effectiveMaxDelayNs()) / std.time.ns_per_us
            else
                self.retry.backoffDelayUs(count);
            const next_attempt = now_us + @as(i64, @intCast(retry_delay_us));
            const final_host = if (details.final_host.len > 0) details.final_host.slice() else candidate_host;
            self.store.put(did, .{
                .status = .failed,
                .active = state.active,
                .rev = state.rev,
                .latest_rev = state.latest_rev,
                .host = final_host,
                .handle = state.handle,
                .pds = state.pds,
                .last_error = @errorName(err),
                .error_class = details.error_class,
                .attempts = state.attempts +| 1,
                .last_attempt_us = now_us,
                .started_us = state.started_us,
                .retry_count = count,
                .next_attempt_us = next_attempt,
                .completed_us = state.completed_us,
                .updated_us = state.updated_us,
                .record_count = state.record_count,
                .total_bytes = state.total_bytes,
            }) catch |store_err| {
                if (self.retry.stats) |s| _ = s.backfill_on_fail_store_errors_total.fetchAdd(1, .monotonic);
                return store_err;
            };
            if (err == error.RateLimited) try self.retry.saveHostPark(final_host, next_attempt);
            if (self.retry.emit_failure_logs) {
                log.warn("failed-repo retry {s} via {s}: {s} (attempt {d}, next in {d}s)", .{
                    did, final_host, @errorName(err), count, @divTrunc(next_attempt - now_us, std.time.us_per_s),
                });
            }
            _ = self.failed.fetchAdd(1, .monotonic);
            if (self.retry.stats) |s| _ = s.retry_failed_total.fetchAdd(1, .monotonic);
            return;
        };
        _ = self.succeeded.fetchAdd(1, .monotonic);
        if (self.retry.stats) |s| {
            _ = s.retry_resynced_total.fetchAdd(1, .monotonic);
            if (details.via_fallback)
                _ = s.retry_relay_fallback_total.fetchAdd(1, .monotonic)
            else
                _ = s.retry_pds_direct_total.fetchAdd(1, .monotonic);
            _ = s.backfill_drops.getPtr(.invalid_collection).fetchAdd(drops.invalid_collection, .monotonic);
            _ = s.backfill_drops.getPtr(.invalid_rkey).fetchAdd(drops.invalid_rkey, .monotonic);
            _ = s.backfill_drops.getPtr(.field_too_long).fetchAdd(drops.field_too_long, .monotonic);
        }
    }

    fn fatal(self: *RetryWork) ?anyerror {
        self.fatal_mu.lockUncancelable(self.retry.io);
        defer self.fatal_mu.unlock(self.retry.io);
        return self.fatal_error;
    }

    fn recordFatal(self: *RetryWork, err: anyerror) void {
        self.fatal_mu.lockUncancelable(self.retry.io);
        defer self.fatal_mu.unlock(self.retry.io);
        if (self.fatal_error == null) self.fatal_error = err;
    }
};

// === tests ===

const testing = std.testing;

test "backoff delay doubles from the interval and caps" {
    var r: Retry = .{
        .allocator = testing.allocator,
        .io = undefined,
        .archive = undefined,
        .meta = undefined,
        .data_dir = "",
        .relay_http = "",
        .interval_ns = 4 * std.time.ns_per_hour,
        .jitter = struct {
            fn zero(_: ?*anyopaque, _: u64) u64 {
                return 0;
            }
        }.zero,
    };
    try testing.expectEqual(@as(u64, 4 * 3600 * std.time.us_per_s), r.backoffDelayUs(1));
    try testing.expectEqual(@as(u64, 8 * 3600 * std.time.us_per_s), r.backoffDelayUs(2));
    try testing.expectEqual(@as(u64, 7 * 24 * 3600 * std.time.us_per_s), r.backoffDelayUs(30));
}

test "backoff adds upstream half-window jitter and clamps to max delay" {
    const max_jitter = struct {
        fn call(_: ?*anyopaque, upper: u64) u64 {
            return upper - 1;
        }
    }.call;
    var r: Retry = .{
        .allocator = testing.allocator,
        .io = undefined,
        .archive = undefined,
        .meta = undefined,
        .data_dir = "",
        .relay_http = "",
        .interval_ns = std.time.ns_per_s,
        .max_delay_ns = 1500 * std.time.ns_per_ms,
        .jitter = max_jitter,
    };
    try testing.expectEqual(@as(u64, 1_499_999), r.backoffDelayUs(1));
    try testing.expectEqual(@as(u64, 1_500_000), r.backoffDelayUs(2));
}

test "runPass with no failed repos is a no-op" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &path_buf);
    var data_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const data_dir = try std.fmt.bufPrint(&data_dir_buf, "{s}/data", .{path_buf[0..n]});

    var a = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer a.deinit();
    var meta = try meta_store.Store.open(testing.allocator, data_dir);
    defer meta.deinit();
    var r = Retry.init(testing.allocator, io, &a, &meta, data_dir, "http://127.0.0.1:9");
    defer r.deinit();
    var instrumentation: metrics.Stats = .{};
    r.stats = &instrumentation;
    const stats = try r.runPass();
    try testing.expectEqual(@as(u64, 0), stats.candidates);
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_passes_total.load(.monotonic));
    try testing.expectEqual(@as(u64, 0), instrumentation.retry_candidates_total.load(.monotonic));
}

// Upstream runs this loop in an errgroup: an error out of RunFailedRepoRetry
// cancels steady state and the process goes down. Logging and continuing would
// leave failed repositories permanently unhealed while health stayed green --
// the loud-and-small failure turned silent and large.
test "a terminal retry pass failure stops the service instead of looping quietly" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &path_buf);
    var data_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const data_dir = try std.fmt.bufPrint(&data_dir_buf, "{s}/data", .{path_buf[0..n]});

    var a = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer a.deinit();
    var meta = try meta_store.Store.open(testing.allocator, data_dir);
    defer meta.deinit();

    var seed = try repo_store.Store.init(testing.allocator, io, &meta);
    defer seed.deinit();
    try seed.put("did:plc:retryfatal", .{ .status = .failed, .active = true });

    var instrumentation: metrics.Stats = .{};
    var shutdown: std.atomic.Value(bool) = .init(false);
    var r = Retry.init(testing.allocator, io, &a, &meta, data_dir, "http://127.0.0.1:9");
    defer r.deinit();
    r.stats = &instrumentation;
    r.shutdown = &shutdown;
    r.interval_ns = std.time.ns_per_ms;
    r.emit_failure_logs = false; // the terminal log is asserted by the metric

    // Our own store read fails: not a remote's fault, so the pass must not
    // simply be retried next interval.
    try testing.expect(meta_store.armReadFault("repo/", 1));
    defer meta_store.disarmReadFault();

    // With the old log-and-continue behavior this call never returns: the pass
    // fails, the loop sleeps, and the subsystem stays dead while health is green.
    r.run();

    try testing.expect(r.failed());
    try testing.expect(shutdown.load(.acquire));
    try testing.expectEqual(
        @as(u64, 1),
        instrumentation.retry_terminal_failures_total.load(.monotonic),
    );
}

// Upstream's scan yields into a Workers*2 channel and creates host gates on
// demand. Materializing every failed DID and every host gate up front is a
// whole-network memory hazard, so the pass must stay bounded no matter how
// many repositories are failed.
test "a retry pass stays bounded and reaches every due repository" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &path_buf);
    var data_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const data_dir = try std.fmt.bufPrint(&data_dir_buf, "{s}/data", .{path_buf[0..n]});

    var a = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer a.deinit();
    var meta = try meta_store.Store.open(testing.allocator, data_dir);
    defer meta.deinit();

    var seed = try repo_store.Store.init(testing.allocator, io, &meta);
    defer seed.deinit();
    const total = 6;
    for (0..total) |i| {
        var did_buf: [64]u8 = undefined;
        var host_buf: [64]u8 = undefined;
        const did = try std.fmt.bufPrint(&did_buf, "did:plc:bounded{d:0>4}", .{i});
        // Many distinct hosts: gates must not be pre-allocated for all of them.
        const host = try std.fmt.bufPrint(&host_buf, "pds-{d}.example", .{i});
        try seed.put(did, .{ .status = .failed, .active = true, .host = host });
    }
    // A deferred repository must be filtered by the scan, never queued.
    try seed.put("did:plc:deferred", .{
        .status = .failed,
        .active = true,
        .host = "pds-parked.example",
        .next_attempt_us = std.math.maxInt(i64),
    });

    var instrumentation: metrics.Stats = .{};
    var r = Retry.init(testing.allocator, io, &a, &meta, data_dir, "http://127.0.0.1:9");
    defer r.deinit();
    r.stats = &instrumentation;
    r.emit_failure_logs = false;
    r.workers = 1; // queue holds 2; the failed set is 3x that

    const stats = try r.runPass();

    // Every due repository was attempted despite the queue being far smaller
    // than the working set, and the undue one never became a candidate.
    try testing.expectEqual(@as(u64, total), stats.candidates);
    try testing.expectEqual(@as(u64, total), instrumentation.retry_attempts_total.load(.monotonic));
    try testing.expect(stats.deferred >= 1);
}

// Upstream keeps parking in the runner's memory (retryRunner.hostParked) and
// never shortens a park. Stream persisted it instead, for no recorded reason —
// it was swept into a commit about durability gaps — which made a restart
// honour a rate limit upstream would have forgotten. Matching upstream removes
// the divergence and picks up the monotonic rule we were missing.
test "host parking is per-host, in memory, and never shortens" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var r: Retry = .{
        .allocator = testing.allocator,
        .io = io,
        .archive = undefined,
        .meta = undefined,
        .data_dir = "",
        .relay_http = "",
    };
    defer r.deinit();

    try r.saveHostPark("pds-a.example", 1234);
    try r.saveHostPark("pds-b.example", 5678);
    try testing.expectEqual(@as(i64, 1234), try r.loadHostPark("pds-a.example"));
    try testing.expectEqual(@as(i64, 5678), try r.loadHostPark("pds-b.example"));
    // Isolation: one host's park says nothing about another's.
    try testing.expectEqual(@as(i64, 0), try r.loadHostPark("pds-c.example"));

    // A park never shortens, so a second rate limit cannot un-park a host
    // early — upstream's `if old.After(until) { return }`.
    try r.saveHostPark("pds-a.example", 900);
    try testing.expectEqual(@as(i64, 1234), try r.loadHostPark("pds-a.example"));
    try r.saveHostPark("pds-a.example", 4321);
    try testing.expectEqual(@as(i64, 4321), try r.loadHostPark("pds-a.example"));

    // It is runner-scoped, not durable: a fresh runner starts unparked, which
    // is what upstream does after a restart.
    var fresh: Retry = .{
        .allocator = testing.allocator,
        .io = io,
        .archive = undefined,
        .meta = undefined,
        .data_dir = "",
        .relay_http = "",
    };
    defer fresh.deinit();
    try testing.expectEqual(@as(i64, 0), try fresh.loadHostPark("pds-a.example"));
}

test "redirected 429 persists and parks only the final PDS host" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    var target = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer target.deinit(io);
    var origin = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer origin.deinit(io);
    var location_buf: [96]u8 = undefined;
    const location = try std.fmt.bufPrint(
        &location_buf,
        "http://127.0.0.1:{d}/xrpc/com.atproto.sync.getRepo?did=did:plc:park-fixture",
        .{target.socket.address.getPort()},
    );

    const Fixture = struct {
        fn originServer(server: *Io.net.Server, task_io: Io, redirect_to: []const u8) !void {
            var stream = try server.accept(task_io);
            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 = try http_server.receiveHead();
            try request.respond("", .{
                .status = .temporary_redirect,
                .keep_alive = false,
                .extra_headers = &.{.{ .name = "location", .value = redirect_to }},
            });
        }

        fn targetServer(server: *Io.net.Server, task_io: Io) !void {
            var stream = try server.accept(task_io);
            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 = try http_server.receiveHead();
            try request.respond("", .{
                .status = .too_many_requests,
                .keep_alive = false,
                .extra_headers = &.{.{ .name = "retry-after", .value = "1" }},
            });
        }
    };
    var origin_future = try io.concurrent(Fixture.originServer, .{ &origin, io, location });
    defer _ = origin_future.cancel(io) catch {};
    var target_future = try io.concurrent(Fixture.targetServer, .{ &target, io });
    defer _ = target_future.cancel(io) catch {};

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &path_buf);
    var data_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const data_dir = try std.fmt.bufPrint(&data_dir_buf, "{s}/data", .{path_buf[0..n]});
    var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer archive.deinit();
    var meta = try meta_store.Store.open(testing.allocator, data_dir);
    defer meta.deinit();
    var store = try repo_store.Store.init(testing.allocator, io, &meta);
    defer store.deinit();
    try store.put("did:plc:park-fixture", .{
        .status = .failed,
        .host = "predicted-pds.example",
        .attempts = 7,
    });
    var origin_url_buf: [96]u8 = undefined;
    const origin_url = try std.fmt.bufPrint(&origin_url_buf, "http://127.0.0.1:{d}", .{origin.socket.address.getPort()});
    var retry = Retry.init(testing.allocator, io, &archive, &meta, data_dir, origin_url);
    defer retry.deinit();
    retry.emit_failure_logs = false;
    var instrumentation: metrics.Stats = .{};
    retry.stats = &instrumentation;

    const pass = try retry.runPass();
    try testing.expectEqual(@as(u64, 1), pass.candidates);
    try testing.expectEqual(@as(u64, 1), pass.failed);
    try testing.expectEqual(@as(u64, 0), pass.succeeded);
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_passes_total.load(.monotonic));
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_candidates_total.load(.monotonic));
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_attempts_total.load(.monotonic));
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_failed_total.load(.monotonic));

    const state = (try store.get(testing.allocator, "did:plc:park-fixture")).?;
    defer store.freeState(testing.allocator, state);
    var final_host_buf: [64]u8 = undefined;
    const final_host = try std.fmt.bufPrint(&final_host_buf, "127.0.0.1:{d}", .{target.socket.address.getPort()});
    try testing.expectEqualStrings(final_host, state.host);
    try testing.expectEqual(repo_store.ErrorClass.http_429, state.error_class);
    try testing.expectEqual(@as(u32, 8), state.attempts);
    try testing.expectEqual(@as(u32, 1), state.retry_count);
    try testing.expect(try retry.loadHostPark(final_host) > 0);
    try testing.expectEqual(@as(i64, 0), try retry.loadHostPark("predicted-pds.example"));

    // A later due row for that exact final host is rejected from the real
    // retry path without issuing another request. The park survives in
    // RocksDB, so this also proves the restart-safe half of the contract.
    try store.put("did:plc:parked-sibling", .{ .status = .failed, .host = final_host });
    const parked_pass = try retry.runPass();
    try testing.expectEqual(@as(u64, 1), parked_pass.candidates);
    try testing.expectEqual(@as(u64, 2), parked_pass.deferred);
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_skipped_host_parked_total.load(.monotonic));
    try testing.expectEqual(@as(u64, 1), instrumentation.retry_attempts_total.load(.monotonic));
    try origin_future.await(io);
    try target_future.await(io);
}

// Upstream's pending pass is this same runner with eligibleStatus flipped, so
// a pending repository that fails must get the identical durable bookkeeping a
// failed one does: status failed, attempts and retry_count incremented, and a
// computed next attempt. The merge's old hand-rolled loop wrote status=failed
// with retry_count and next_attempt_us untouched, which left the repo waiting
// on the steady loop's cadence instead of a backoff.
test "a pending pass records upstream's retry bookkeeping, not a bare failure" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &path_buf);
    var data_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const data_dir = try std.fmt.bufPrint(&data_dir_buf, "{s}/data", .{path_buf[0..n]});

    var a = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer a.deinit();
    var meta = try meta_store.Store.open(testing.allocator, data_dir);
    defer meta.deinit();
    var seed = try repo_store.Store.init(testing.allocator, io, &meta);
    defer seed.deinit();
    try seed.put("did:plc:pendingbookkeeping", .{
        .status = .pending,
        .active = true,
        .host = "pds-pending.example",
    });
    // A failed sibling must not be touched by a pending pass.
    try seed.put("did:plc:failedsibling", .{ .status = .failed, .active = true });

    var instrumentation: metrics.Stats = .{};
    var r = Retry.init(testing.allocator, io, &a, &meta, data_dir, "http://127.0.0.1:9");
    defer r.deinit();
    r.stats = &instrumentation;
    r.emit_failure_logs = false;
    r.eligible_status = .pending;
    r.workers = 1;

    const before_us: i64 = Io.Timestamp.now(io, .real).toMicroseconds();
    const result = try r.runPass();
    try testing.expectEqual(@as(u64, 1), result.candidates);

    const state = (try seed.get(testing.allocator, "did:plc:pendingbookkeeping")).?;
    defer seed.freeState(testing.allocator, state);
    try testing.expectEqual(repo_store.Status.failed, state.status);
    try testing.expectEqual(@as(u32, 1), state.attempts);
    // The two the hand-rolled loop left untouched.
    try testing.expectEqual(@as(u32, 1), state.retry_count);
    try testing.expect(state.next_attempt_us > before_us);

    // Selection really was by status: the failed sibling was never attempted.
    const sibling = (try seed.get(testing.allocator, "did:plc:failedsibling")).?;
    defer seed.freeState(testing.allocator, sibling);
    try testing.expectEqual(@as(u32, 0), sibling.attempts);
}