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

zat.dev/stream

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

0
0
985 lines · 46.0 KB Raw History
//! Per-repository backfill state in the shared metadata database.
//!
//! `repo/<did>` is the point-read keyspace used by bootstrap and merge.
//! Aggregate status counts live at `backfill/counts`; a status transition
//! updates the row and counts in one synced RocksDB batch.

const std = @import("std");
const rocksdb = @import("rocksdb");
const host_store = @import("host_store.zig");
const meta_store = @import("../../storage/meta_store.zig");

const Io = std.Io;
const Allocator = std.mem.Allocator;

const repo_prefix = "repo/";
const counts_key = "backfill/counts";
const host_prefix = "host/";
const handle_prefix = "handle/";
const hosts_version_key = "backfill/host-status-version";
const hosts_version: u8 = 1;
const handles_version_key = "backfill/handle-index-version";
const handles_version: u8 = 1;
const encoding_version: u8 = 5;
const header_len = 84;
const v4_header_len = 52;
const legacy_header_len = 14;

pub const Status = host_store.RepoStatus;
pub const ErrorClass = host_store.ErrorClass;
pub const HostStatus = host_store.Status;
pub const HostErrorSample = host_store.ErrorSample;

pub fn classifyAttemptError(err: anyerror) ErrorClass {
    return switch (err) {
        error.AttemptTimeout, error.TransferTooSlow => .timeout,
        error.MissingBlock, error.IncompleteCar, error.InvalidCar, error.InvalidCommit, error.InvalidCommitRev, error.EmptyCar => .car,
        error.SignatureVerificationFailed => .verification,
        error.ArchiveAppendFailed => .local_write,
        else => .unknown,
    };
}

/// Convert a resolved PDS service endpoint to upstream's durable host bucket.
/// Malformed or non-HTTP endpoints are retained in the explicit invalid-pds
/// bucket so selected-backfill diagnostics never silently lose the account.
pub fn hostFromPDS(allocator: Allocator, endpoint: []const u8) ![]u8 {
    const uri = std.Uri.parse(std.mem.trim(u8, endpoint, " \t\r\n")) catch
        return allocator.dupe(u8, "invalid-pds");
    if (!std.ascii.eqlIgnoreCase(uri.scheme, "http") and !std.ascii.eqlIgnoreCase(uri.scheme, "https"))
        return allocator.dupe(u8, "invalid-pds");
    var host_buf: [std.Io.net.HostName.max_len]u8 = undefined;
    const host_component = uri.host orelse return allocator.dupe(u8, "invalid-pds");
    const host = host_component.toRaw(&host_buf) catch return allocator.dupe(u8, "invalid-pds");
    if (host.len == 0) return allocator.dupe(u8, "invalid-pds");
    const bare_host = if (host.len >= 2 and host[0] == '[' and host[host.len - 1] == ']')
        host[1 .. host.len - 1]
    else
        host;
    const default_port: ?u16 = if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else 80;
    const raw = if (uri.port != null and uri.port != default_port)
        if (std.mem.indexOfScalar(u8, bare_host, ':') != null)
            try std.fmt.allocPrint(allocator, "[{s}]:{d}", .{ bare_host, uri.port.? })
        else
            try std.fmt.allocPrint(allocator, "{s}:{d}", .{ bare_host, uri.port.? })
    else
        try allocator.dupe(u8, bare_host);
    defer allocator.free(raw);
    return host_store.normalizeAuthority(allocator, raw);
}

pub const RepoState = struct {
    status: Status,
    active: bool = true,
    /// Owned by the caller when returned from `get`; literals passed to put
    /// remain caller-owned.
    rev: []const u8 = "",
    /// Latest known repo revision. This equals `rev` at initial backfill and
    /// advances independently as captured live events are merged.
    latest_rev: []const u8 = "",
    host: []const u8 = "",
    handle: []const u8 = "",
    pds: []const u8 = "",
    last_error: []const u8 = "",
    error_class: ErrorClass = .unknown,
    attempts: u32 = 0,
    last_attempt_us: i64 = 0,
    started_us: i64 = 0,
    completed_us: i64 = 0,
    retry_count: u32 = 0,
    next_attempt_us: i64 = 0,
    updated_us: i64 = 0,
    record_count: i64 = 0,
    total_bytes: i64 = 0,
};

pub const Transition = struct { did: []const u8, state: RepoState };
pub const RevUpdate = struct { did: []const u8, rev: []const u8 };

pub const Store = struct {
    allocator: Allocator,
    io: Io,
    meta: *meta_store.Store,
    mu: Io.Mutex = .init,

    pub fn init(allocator: Allocator, io: Io, meta: *meta_store.Store) !Store {
        var self: Store = .{ .allocator = allocator, .io = io, .meta = meta };
        if (try meta.getAlloc(allocator, counts_key)) |bytes| {
            allocator.free(bytes);
        } else {
            try self.rebuildCounts();
        }
        try self.ensureHostStatuses();
        try self.ensureHandleIndex();
        // A durable not_started row means the previous process died after
        // dispatch and before completion. Defer it to the merge pending pass;
        // never re-download it into the low bootstrap sequence range.
        const interrupted = try self.collectByStatus(allocator, .not_started);
        defer self.freeDids(allocator, interrupted);
        if (interrupted.len > 0) {
            const transitions = try allocator.alloc(Transition, interrupted.len);
            defer allocator.free(transitions);
            var n: usize = 0;
            for (interrupted) |did| {
                const state = (try self.get(allocator, did)).?;
                defer self.freeState(allocator, state);
                // Inactive repos are deliberately discovered as not_started
                // but never dispatched. Only active not_started rows can be
                // crash-interrupted downloads that need merge-time repair.
                if (!state.active) continue;
                transitions[n] = .{ .did = did, .state = .{
                    .status = .pending,
                    .active = true,
                    .rev = state.rev,
                    .latest_rev = state.latest_rev,
                    .host = state.host,
                    .handle = state.handle,
                    .pds = state.pds,
                    .last_error = state.last_error,
                    .error_class = state.error_class,
                    .attempts = state.attempts,
                    .last_attempt_us = state.last_attempt_us,
                    .started_us = state.started_us,
                    .completed_us = state.completed_us,
                    .retry_count = state.retry_count,
                    .next_attempt_us = state.next_attempt_us,
                    .updated_us = state.updated_us,
                    .record_count = state.record_count,
                    .total_bytes = state.total_bytes,
                } };
                n += 1;
            }
            try self.putMany(transitions[0..n]);
        }
        return self;
    }

    pub fn deinit(_: *Store) void {}

    pub fn get(self: *Store, allocator: Allocator, did: []const u8) !?RepoState {
        const key = try repoKey(self.allocator, did);
        defer self.allocator.free(key);
        const bytes = try self.meta.getAlloc(allocator, key) orelse return null;
        errdefer allocator.free(bytes);
        const state = try decode(bytes);
        const rev = if (state.rev.len > 0) try allocator.dupe(u8, state.rev) else "";
        errdefer if (rev.len > 0) allocator.free(@constCast(rev));
        const latest_rev = if (state.latest_rev.len > 0) try allocator.dupe(u8, state.latest_rev) else "";
        errdefer if (latest_rev.len > 0) allocator.free(@constCast(latest_rev));
        const host = if (state.host.len > 0) try allocator.dupe(u8, state.host) else "";
        errdefer if (host.len > 0) allocator.free(@constCast(host));
        const handle = if (state.handle.len > 0) try allocator.dupe(u8, state.handle) else "";
        errdefer if (handle.len > 0) allocator.free(@constCast(handle));
        const pds = if (state.pds.len > 0) try allocator.dupe(u8, state.pds) else "";
        errdefer if (pds.len > 0) allocator.free(@constCast(pds));
        const last_error = if (state.last_error.len > 0) try allocator.dupe(u8, state.last_error) else "";
        allocator.free(bytes);
        return .{
            .status = state.status,
            .active = state.active,
            .rev = rev,
            .latest_rev = latest_rev,
            .host = host,
            .handle = handle,
            .pds = pds,
            .last_error = last_error,
            .error_class = state.error_class,
            .attempts = state.attempts,
            .last_attempt_us = state.last_attempt_us,
            .started_us = state.started_us,
            .completed_us = state.completed_us,
            .retry_count = state.retry_count,
            .next_attempt_us = state.next_attempt_us,
            .updated_us = state.updated_us,
            .record_count = state.record_count,
            .total_bytes = state.total_bytes,
        };
    }

    pub fn freeState(_: *Store, allocator: Allocator, state: RepoState) void {
        if (state.rev.len > 0) allocator.free(@constCast(state.rev));
        if (state.latest_rev.len > 0) allocator.free(@constCast(state.latest_rev));
        if (state.host.len > 0) allocator.free(@constCast(state.host));
        if (state.handle.len > 0) allocator.free(@constCast(state.handle));
        if (state.pds.len > 0) allocator.free(@constCast(state.pds));
        if (state.last_error.len > 0) allocator.free(@constCast(state.last_error));
    }

    /// A repository row and its aggregate count transition commit together.
    pub fn put(self: *Store, did: []const u8, state: RepoState) !void {
        try self.putMany(&.{.{ .did = did, .state = state }});
    }

    /// Commit multiple repository transitions and aggregate counts in one
    /// synced batch. Used by the archive durable-batch boundary.
    pub fn putMany(self: *Store, transitions: []const Transition) !void {
        if (transitions.len == 0) return;
        self.mu.lockUncancelable(self.io);
        defer self.mu.unlock(self.io);

        var counts = try self.loadCounts();
        var writes = self.meta.batch();
        defer writes.deinit();
        var hosts = std.StringHashMap(HostStatus).init(self.allocator);
        defer {
            var values = hosts.valueIterator();
            while (values.next()) |status| status.deinit(self.allocator);
            hosts.deinit();
        }
        for (transitions) |transition| {
            const row_key = try repoKey(self.allocator, transition.did);
            defer self.allocator.free(row_key);
            const old_bytes = try self.meta.getAlloc(self.allocator, row_key);
            defer if (old_bytes) |b| self.allocator.free(b);
            var had_old = false;
            var old: RepoState = .{ .status = .not_started };
            if (old_bytes) |bytes| {
                old = try decode(bytes);
                had_old = true;
                if (counts[@backingInt(old.status)] > 0) counts[@backingInt(old.status)] -= 1;
            }
            counts[@backingInt(transition.state.status)] += 1;

            const old_host = if (had_old) try host_store.normalizeAuthority(self.allocator, old.host) else "";
            defer if (old_host.len > 0) self.allocator.free(old_host);
            const new_host = try host_store.normalizeAuthority(self.allocator, transition.state.host);
            defer if (new_host.len > 0) self.allocator.free(new_host);
            if (old_host.len > 0 and !std.mem.eql(u8, old_host, new_host)) {
                const old_status = try self.cachedHost(&hosts, old_host);
                host_store.remove(old_status, old.active, old.status);
            }
            if (new_host.len > 0) {
                const diagnostic = try self.cachedHost(&hosts, new_host);
                const first = !had_old or !std.mem.eql(u8, old_host, new_host);
                host_store.applyTransition(
                    diagnostic,
                    first,
                    if (had_old) old.active else false,
                    transition.state.active,
                    if (had_old) old.status else transition.state.status,
                    transition.state.status,
                );
                if (transition.state.last_attempt_us != 0)
                    diagnostic.last_attempt_us = transition.state.last_attempt_us;
                const new_failure = transition.state.status == .failed and transition.state.last_error.len > 0 and
                    (!had_old or old.last_attempt_us != transition.state.last_attempt_us or old.attempts != transition.state.attempts or
                        !std.mem.eql(u8, old.last_error, transition.state.last_error));
                if (new_failure)
                    try host_store.recordError(diagnostic, self.allocator, transition.did, transition.state.last_attempt_us, transition.state.error_class, transition.state.last_error);
            }

            if (!had_old or !handlesEqual(old.handle, transition.state.handle)) {
                if (had_old) try self.stageHandleDeleteIfMatches(&writes, old.handle, transition.did);
                try stageHandleSet(self.allocator, &writes, transition.state.handle, transition.did);
            }

            var canonical = transition.state;
            canonical.host = new_host;
            const value = try encode(self.allocator, canonical);
            defer self.allocator.free(value);
            writes.put(row_key, value);
        }
        var counts_bytes: [@sizeOf(Counts)]u8 = undefined;
        encodeCounts(&counts_bytes, counts);
        writes.put(counts_key, &counts_bytes);
        var host_values = hosts.valueIterator();
        while (host_values.next()) |status| {
            const key = try hostKey(self.allocator, status.host);
            defer self.allocator.free(key);
            const value = try host_store.encode(self.allocator, status.*);
            defer self.allocator.free(value);
            writes.put(key, value);
        }
        try writes.commitDurable();
    }

    /// Bounded by PDS hosts, not network accounts. Returned rows own all
    /// strings and must be released with `freeHostStatuses`.
    pub fn listHostStatuses(self: *Store, allocator: Allocator) ![]HostStatus {
        var out: std.ArrayList(HostStatus) = .empty;
        errdefer {
            for (out.items) |*status| status.deinit(allocator);
            out.deinit(allocator);
        }
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(host_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            const key = entry[0].data;
            if (!std.mem.startsWith(u8, key, host_prefix)) break;
            try out.append(allocator, try host_store.decode(allocator, key[host_prefix.len..], entry[1].data));
        }
        return out.toOwnedSlice(allocator);
    }

    pub fn freeHostStatuses(_: *Store, allocator: Allocator, statuses: []HostStatus) void {
        for (statuses) |*status| status.deinit(allocator);
        allocator.free(statuses);
    }

    /// Lookup through the durable declared-handle index. Like upstream, this
    /// operator convenience is normalized but is not bidirectionally verified.
    pub fn lookupDIDByHandle(self: *Store, allocator: Allocator, handle: []const u8) !?[]u8 {
        const key = try handleKey(self.allocator, handle) orelse return null;
        defer self.allocator.free(key);
        return self.meta.getAlloc(allocator, key);
    }

    /// Upstream's per-source merge commit: advance the source cursor and
    /// refresh only top-level latest revision/time in one synced metadata
    /// batch. Backfill `rev` and every lifecycle/identity field are preserved.
    pub fn commitMergeSource(self: *Store, cursor_key: []const u8, next_idx: u64, updates: []const RevUpdate, updated_us: i64) !void {
        self.mu.lockUncancelable(self.io);
        defer self.mu.unlock(self.io);

        var writes = self.meta.batch();
        defer writes.deinit();
        var cursor_bytes: [9]u8 = undefined;
        cursor_bytes[0] = 1;
        std.mem.writeInt(u64, cursor_bytes[1..9], next_idx, .little);
        writes.put(cursor_key, &cursor_bytes);
        for (updates) |update| {
            const key = try repoKey(self.allocator, update.did);
            defer self.allocator.free(key);
            const bytes = try self.meta.getAlloc(self.allocator, key) orelse continue;
            defer self.allocator.free(bytes);
            var state = try decode(bytes);
            state.latest_rev = update.rev;
            state.updated_us = updated_us;
            const encoded = try encode(self.allocator, state);
            defer self.allocator.free(encoded);
            writes.put(key, encoded);
        }
        try writes.commitDurable();
    }

    /// Compatibility with the former buffered store. Writes are already
    /// synchronously durable, so there is nothing left to flush.
    pub fn flush(_: *Store) !void {}

    pub fn count(self: *Store) u32 {
        const counts = self.loadCounts() catch return 0;
        var total: u64 = 0;
        for (counts) |n| total += n;
        return @intCast(@min(total, std.math.maxInt(u32)));
    }

    pub fn collectByStatus(self: *Store, allocator: Allocator, status: Status) ![][]const u8 {
        var out: std.ArrayList([]const u8) = .empty;
        errdefer {
            for (out.items) |did| allocator.free(did);
            out.deinit(allocator);
        }
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(repo_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            const key = entry[0].data;
            if (!std.mem.startsWith(u8, key, repo_prefix)) break;
            if ((try decode(entry[1].data)).status == status)
                try out.append(allocator, try allocator.dupe(u8, key[repo_prefix.len..]));
        }
        return out.toOwnedSlice(allocator);
    }

    /// Stream repositories with `status` without materializing the set.
    /// Upstream's retry scan yields one candidate at a time straight off the
    /// store iterator; collecting every failed DID first is a whole-network
    /// memory hazard. `did` and `state` borrow the iterator's buffers and are
    /// only valid for the duration of the call.
    pub fn streamByStatus(
        self: *Store,
        status: Status,
        ctx: anytype,
        comptime yield: fn (@TypeOf(ctx), []const u8, RepoState) anyerror!void,
    ) !void {
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(repo_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            const key = entry[0].data;
            if (!std.mem.startsWith(u8, key, repo_prefix)) break;
            const state = try decode(entry[1].data);
            if (state.status != status) continue;
            try yield(ctx, key[repo_prefix.len..], state);
        }
    }

    pub fn freeDids(_: *Store, allocator: Allocator, dids: []const []const u8) void {
        for (dids) |did| allocator.free(did);
        allocator.free(dids);
    }

    pub fn countByStatus(self: *Store, status: Status) u32 {
        const counts = self.loadCounts() catch return 0;
        return @intCast(@min(counts[@backingInt(status)], std.math.maxInt(u32)));
    }

    fn rebuildCounts(self: *Store) !void {
        var counts: Counts = @splat(0);
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(repo_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
            const state = try decode(entry[1].data);
            counts[@backingInt(state.status)] += 1;
        }
        var bytes: [@sizeOf(Counts)]u8 = undefined;
        encodeCounts(&bytes, counts);
        try self.meta.putDurable(counts_key, &bytes);
    }

    fn ensureHostStatuses(self: *Store) !void {
        if (try self.meta.getAlloc(self.allocator, hosts_version_key)) |version| {
            defer self.allocator.free(version);
            if (version.len == 1 and version[0] == hosts_version) return;
            return error.UnsupportedHostStatusVersion;
        }

        var hosts = std.StringHashMap(HostStatus).init(self.allocator);
        defer {
            var values = hosts.valueIterator();
            while (values.next()) |status| status.deinit(self.allocator);
            hosts.deinit();
        }
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(repo_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
            const state = try decode(entry[1].data);
            const host = try host_store.normalizeAuthority(self.allocator, state.host);
            defer if (host.len > 0) self.allocator.free(host);
            if (host.len == 0) continue;
            const status = try self.cachedHost(&hosts, host);
            host_store.applyTransition(status, true, false, state.active, state.status, state.status);
            if (state.last_attempt_us != 0) status.last_attempt_us = @max(status.last_attempt_us, state.last_attempt_us);
            if (state.status == .failed and state.last_error.len > 0)
                try host_store.recordError(status, self.allocator, entry[0].data[repo_prefix.len..], state.last_attempt_us, state.error_class, state.last_error);
        }

        var writes = self.meta.batch();
        defer writes.deinit();
        var values = hosts.valueIterator();
        while (values.next()) |status| {
            const key = try hostKey(self.allocator, status.host);
            defer self.allocator.free(key);
            const value = try host_store.encode(self.allocator, status.*);
            defer self.allocator.free(value);
            writes.put(key, value);
        }
        writes.put(hosts_version_key, &.{hosts_version});
        try writes.commitDurable();
    }

    fn ensureHandleIndex(self: *Store) !void {
        if (try self.meta.getAlloc(self.allocator, handles_version_key)) |version| {
            defer self.allocator.free(version);
            if (version.len == 1 and version[0] == handles_version) return;
            return error.UnsupportedHandleIndexVersion;
        }

        var writes = self.meta.batch();
        defer writes.deinit();
        var err_data: ?rocksdb.Data = null;
        defer if (err_data) |e| e.deinit();
        var it = self.meta.iterator(repo_prefix);
        defer it.deinit();
        while (try it.next(&err_data)) |entry| {
            if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
            const state = try decode(entry[1].data);
            try stageHandleSet(self.allocator, &writes, state.handle, entry[0].data[repo_prefix.len..]);
        }
        writes.put(handles_version_key, &.{handles_version});
        try writes.commitDurable();
    }

    fn stageHandleDeleteIfMatches(self: *Store, writes: *meta_store.Batch, handle: []const u8, did: []const u8) !void {
        const key = try handleKey(self.allocator, handle) orelse return;
        defer self.allocator.free(key);
        const indexed = try self.meta.getAlloc(self.allocator, key) orelse return;
        defer self.allocator.free(indexed);
        if (std.mem.eql(u8, indexed, did)) writes.delete(key);
    }

    fn cachedHost(self: *Store, cache: *std.StringHashMap(HostStatus), normalized_host: []const u8) !*HostStatus {
        if (cache.getPtr(normalized_host)) |status| return status;
        const key = try hostKey(self.allocator, normalized_host);
        defer self.allocator.free(key);
        const bytes = try self.meta.getAlloc(self.allocator, key);
        defer if (bytes) |value| self.allocator.free(value);
        var status = if (bytes) |value|
            try host_store.decode(self.allocator, normalized_host, value)
        else
            HostStatus{ .host = try self.allocator.dupe(u8, normalized_host) };
        errdefer status.deinit(self.allocator);
        const result = try cache.getOrPut(status.host);
        std.debug.assert(!result.found_existing);
        result.value_ptr.* = status;
        return result.value_ptr;
    }

    fn loadCounts(self: *Store) !Counts {
        const bytes = try self.meta.getAlloc(self.allocator, counts_key) orelse return error.MissingCounts;
        defer self.allocator.free(bytes);
        if (bytes.len != @sizeOf(Counts)) return error.InvalidCounts;
        var counts: Counts = undefined;
        for (&counts, 0..) |*n, i| n.* = std.mem.readInt(u64, bytes[i * 8 ..][0..8], .little);
        return counts;
    }
};

const Counts = [@typeInfo(Status).@"enum".field_names.len]u64;

fn encodeCounts(out: *[@sizeOf(Counts)]u8, counts: Counts) void {
    for (counts, 0..) |n, i| std.mem.writeInt(u64, out[i * 8 ..][0..8], n, .little);
}

fn repoKey(allocator: Allocator, did: []const u8) ![]u8 {
    return std.mem.concat(allocator, u8, &.{ repo_prefix, did });
}

fn hostKey(allocator: Allocator, host: []const u8) ![]u8 {
    return std.mem.concat(allocator, u8, &.{ host_prefix, host });
}

fn handleKey(allocator: Allocator, handle: []const u8) !?[]u8 {
    const normalized = std.mem.trim(u8, handle, " \t\r\n");
    if (normalized.len == 0) return null;
    const out = try allocator.alloc(u8, handle_prefix.len + normalized.len);
    @memcpy(out[0..handle_prefix.len], handle_prefix);
    for (normalized, out[handle_prefix.len..]) |byte, *dst| dst.* = std.ascii.toLower(byte);
    return out;
}

fn handlesEqual(a: []const u8, b: []const u8) bool {
    return std.ascii.eqlIgnoreCase(std.mem.trim(u8, a, " \t\r\n"), std.mem.trim(u8, b, " \t\r\n"));
}

fn stageHandleSet(allocator: Allocator, writes: *meta_store.Batch, handle: []const u8, did: []const u8) !void {
    const key = try handleKey(allocator, handle) orelse return;
    defer allocator.free(key);
    writes.put(key, did);
}

fn encode(allocator: Allocator, state: RepoState) ![]u8 {
    if (state.host.len > std.math.maxInt(u16) or state.handle.len > std.math.maxInt(u16) or
        state.pds.len > std.math.maxInt(u16) or state.last_error.len > std.math.maxInt(u16) or
        state.rev.len > std.math.maxInt(u32) or state.latest_rev.len > std.math.maxInt(u32))
        return error.RepoStateFieldTooLong;
    const out = try allocator.alloc(u8, header_len + state.rev.len + state.latest_rev.len + state.host.len + state.handle.len + state.pds.len + state.last_error.len);
    out[0] = encoding_version;
    out[1] = @backingInt(state.status);
    out[2] = @intFromBool(state.active);
    std.mem.writeInt(u32, out[3..7], state.retry_count, .little);
    std.mem.writeInt(i64, out[7..15], state.next_attempt_us, .little);
    std.mem.writeInt(u32, out[15..19], state.attempts, .little);
    std.mem.writeInt(i64, out[19..27], state.last_attempt_us, .little);
    std.mem.writeInt(i64, out[27..35], state.started_us, .little);
    std.mem.writeInt(i64, out[35..43], state.completed_us, .little);
    std.mem.writeInt(i64, out[43..51], state.updated_us, .little);
    std.mem.writeInt(i64, out[51..59], state.record_count, .little);
    std.mem.writeInt(i64, out[59..67], state.total_bytes, .little);
    std.mem.writeInt(u32, out[67..71], @intCast(state.rev.len), .little);
    std.mem.writeInt(u32, out[71..75], @intCast(state.latest_rev.len), .little);
    std.mem.writeInt(u16, out[75..77], @intCast(state.host.len), .little);
    std.mem.writeInt(u16, out[77..79], @intCast(state.handle.len), .little);
    std.mem.writeInt(u16, out[79..81], @intCast(state.pds.len), .little);
    std.mem.writeInt(u16, out[81..83], @intCast(state.last_error.len), .little);
    out[83] = @backingInt(state.error_class);
    var offset: usize = header_len;
    @memcpy(out[offset..][0..state.rev.len], state.rev);
    offset += state.rev.len;
    @memcpy(out[offset..][0..state.latest_rev.len], state.latest_rev);
    offset += state.latest_rev.len;
    @memcpy(out[offset..][0..state.host.len], state.host);
    offset += state.host.len;
    @memcpy(out[offset..][0..state.handle.len], state.handle);
    offset += state.handle.len;
    @memcpy(out[offset..][0..state.pds.len], state.pds);
    offset += state.pds.len;
    @memcpy(out[offset..][0..state.last_error.len], state.last_error);
    return out;
}

fn decode(bytes: []const u8) !RepoState {
    if (bytes.len >= legacy_header_len and bytes[0] == 2) {
        if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
        return .{
            .status = @fromBackingInt(@intCast(bytes[1])),
            .active = true,
            .retry_count = std.mem.readInt(u32, bytes[2..6], .little),
            .next_attempt_us = std.mem.readInt(i64, bytes[6..14], .little),
            .rev = bytes[legacy_header_len..],
            .latest_rev = bytes[legacy_header_len..],
        };
    }
    if (bytes.len >= 15 and bytes[0] == 3) {
        if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
        return .{
            .status = @fromBackingInt(@intCast(bytes[1])),
            .active = bytes[2] != 0,
            .retry_count = std.mem.readInt(u32, bytes[3..7], .little),
            .next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
            .rev = bytes[15..],
            .latest_rev = bytes[15..],
        };
    }
    if (bytes.len >= v4_header_len and bytes[0] == 4) {
        if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
        if (bytes[51] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidRepoState;
        const rev_len = std.mem.readInt(u32, bytes[43..47], .little);
        const host_len = std.mem.readInt(u16, bytes[47..49], .little);
        const error_len = std.mem.readInt(u16, bytes[49..51], .little);
        const total = v4_header_len + @as(usize, rev_len) + @as(usize, host_len) + @as(usize, error_len);
        if (total != bytes.len) return error.InvalidRepoState;
        const rev_end = v4_header_len + rev_len;
        const host_end = rev_end + host_len;
        return .{
            .status = @fromBackingInt(@intCast(bytes[1])),
            .active = bytes[2] != 0,
            .rev = bytes[v4_header_len..rev_end],
            .latest_rev = bytes[v4_header_len..rev_end],
            .host = bytes[rev_end..host_end],
            .last_error = bytes[host_end..total],
            .error_class = @fromBackingInt(@intCast(bytes[51])),
            .retry_count = std.mem.readInt(u32, bytes[3..7], .little),
            .next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
            .attempts = std.mem.readInt(u32, bytes[15..19], .little),
            .last_attempt_us = std.mem.readInt(i64, bytes[19..27], .little),
            .started_us = std.mem.readInt(i64, bytes[27..35], .little),
            .completed_us = std.mem.readInt(i64, bytes[35..43], .little),
        };
    }
    if (bytes.len < header_len or bytes[0] != encoding_version) return error.InvalidRepoState;
    if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
    if (bytes[83] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidRepoState;
    const rev_len = std.mem.readInt(u32, bytes[67..71], .little);
    const latest_rev_len = std.mem.readInt(u32, bytes[71..75], .little);
    const host_len = std.mem.readInt(u16, bytes[75..77], .little);
    const handle_len = std.mem.readInt(u16, bytes[77..79], .little);
    const pds_len = std.mem.readInt(u16, bytes[79..81], .little);
    const error_len = std.mem.readInt(u16, bytes[81..83], .little);
    const total = header_len + @as(usize, rev_len) + @as(usize, latest_rev_len) + @as(usize, host_len) + @as(usize, handle_len) + @as(usize, pds_len) + @as(usize, error_len);
    if (total != bytes.len) return error.InvalidRepoState;
    const rev_end = header_len + rev_len;
    const latest_rev_end = rev_end + latest_rev_len;
    const host_end = latest_rev_end + host_len;
    const handle_end = host_end + handle_len;
    const pds_end = handle_end + pds_len;
    return .{
        .status = @fromBackingInt(@intCast(bytes[1])),
        .active = bytes[2] != 0,
        .rev = bytes[header_len..rev_end],
        .latest_rev = bytes[rev_end..latest_rev_end],
        .host = bytes[latest_rev_end..host_end],
        .handle = bytes[host_end..handle_end],
        .pds = bytes[handle_end..pds_end],
        .last_error = bytes[pds_end..total],
        .error_class = @fromBackingInt(@intCast(bytes[83])),
        .retry_count = std.mem.readInt(u32, bytes[3..7], .little),
        .next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
        .attempts = std.mem.readInt(u32, bytes[15..19], .little),
        .last_attempt_us = std.mem.readInt(i64, bytes[19..27], .little),
        .started_us = std.mem.readInt(i64, bytes[27..35], .little),
        .completed_us = std.mem.readInt(i64, bytes[35..43], .little),
        .updated_us = std.mem.readInt(i64, bytes[43..51], .little),
        .record_count = std.mem.readInt(i64, bytes[51..59], .little),
        .total_bytes = std.mem.readInt(i64, bytes[59..67], .little),
    };
}

test "rows and counts are durable and atomically updated" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);

    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();

    try store.put("did:plc:aaa", .{ .status = .not_started });
    try store.put("did:plc:bbb", .{
        .status = .complete,
        .active = false,
        .rev = "3lrev",
        .latest_rev = "3llatest",
        .host = "pds.example",
        .handle = "Alice.Test",
        .pds = "https://pds.example",
        .last_error = "previous timeout",
        .error_class = .timeout,
        .attempts = 2,
        .last_attempt_us = 17,
        .updated_us = 18,
        .record_count = 42,
        .total_bytes = 1024,
    });
    try store.put("did:plc:aaa", .{ .status = .failed });
    try testing.expectEqual(@as(u32, 2), store.count());
    try testing.expectEqual(@as(u32, 1), store.countByStatus(.complete));
    try testing.expectEqual(@as(u32, 1), store.countByStatus(.failed));

    const bbb = (try store.get(testing.allocator, "did:plc:bbb")).?;
    defer store.freeState(testing.allocator, bbb);
    try testing.expectEqual(Status.complete, bbb.status);
    try testing.expect(!bbb.active);
    try testing.expectEqualStrings("3lrev", bbb.rev);
    try testing.expectEqualStrings("3llatest", bbb.latest_rev);
    try testing.expectEqualStrings("pds.example", bbb.host);
    try testing.expectEqualStrings("Alice.Test", bbb.handle);
    try testing.expectEqualStrings("https://pds.example", bbb.pds);
    try testing.expectEqualStrings("previous timeout", bbb.last_error);
    try testing.expectEqual(ErrorClass.timeout, bbb.error_class);
    try testing.expectEqual(@as(u32, 2), bbb.attempts);
    try testing.expectEqual(@as(i64, 17), bbb.last_attempt_us);
    try testing.expectEqual(@as(i64, 18), bbb.updated_us);
    try testing.expectEqual(@as(i64, 42), bbb.record_count);
    try testing.expectEqual(@as(i64, 1024), bbb.total_bytes);
    const indexed = (try store.lookupDIDByHandle(testing.allocator, " @ignored "));
    try testing.expect(indexed == null);
    const alice = (try store.lookupDIDByHandle(testing.allocator, " alice.TEST ")).?;
    defer testing.allocator.free(alice);
    try testing.expectEqualStrings("did:plc:bbb", alice);

    const failed = try store.collectByStatus(testing.allocator, .failed);
    defer store.freeDids(testing.allocator, failed);
    try testing.expectEqual(@as(usize, 1), failed.len);
    try testing.expectEqualStrings("did:plc:aaa", failed[0]);

    try store.put("did:plc:interrupted", .{ .status = .not_started });
    try store.put("did:plc:inactive", .{ .status = .not_started, .active = false });
    var reopened = try Store.init(testing.allocator, testing.io, &meta);
    defer reopened.deinit();
    const interrupted = (try reopened.get(testing.allocator, "did:plc:interrupted")).?;
    defer reopened.freeState(testing.allocator, interrupted);
    try testing.expectEqual(Status.pending, interrupted.status);
    const inactive = (try reopened.get(testing.allocator, "did:plc:inactive")).?;
    defer reopened.freeState(testing.allocator, inactive);
    try testing.expectEqual(Status.not_started, inactive.status);
    try testing.expect(!inactive.active);
}

test "repo transitions atomically maintain durable upstream-shaped host diagnostics" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);

    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();

    try store.put("did:plc:hosted", .{
        .status = .failed,
        .host = " PDS-A.EXAMPLE:443 ",
        .last_error = "HTTP 503 first",
        .error_class = .http_5xx,
        .attempts = 1,
        .last_attempt_us = 10,
    });
    try store.put("did:plc:hosted", .{
        .status = .failed,
        .host = "pds-a.example",
        .last_error = "HTTP 503 second",
        .error_class = .http_5xx,
        .attempts = 2,
        .last_attempt_us = 20,
    });
    try store.put("did:plc:hosted", .{
        .status = .complete,
        .active = false,
        .host = "pds-a.example",
        .attempts = 0,
        .last_attempt_us = 30,
    });

    var hosts = try store.listHostStatuses(testing.allocator);
    defer store.freeHostStatuses(testing.allocator, hosts);
    try testing.expectEqual(@as(usize, 1), hosts.len);
    try testing.expectEqualStrings("pds-a.example", hosts[0].host);
    try testing.expectEqual(@as(u64, 1), hosts[0].total);
    try testing.expectEqual(@as(u64, 0), hosts[0].active);
    try testing.expectEqual(@as(u64, 1), hosts[0].count(.complete));
    try testing.expectEqual(@as(u64, 0), hosts[0].count(.failed));
    try testing.expectEqual(@as(u64, 2), hosts[0].error_counts[@backingInt(ErrorClass.http_5xx)]);
    try testing.expectEqual(@as(usize, 2), hosts[0].recent_errors.len);
    try testing.expectEqualStrings("HTTP 503 second", hosts[0].recent_errors[0].message);

    try store.put("did:plc:hosted", .{
        .status = .complete,
        .active = false,
        .host = "pds-b.example:8443",
        .last_attempt_us = 40,
    });
    store.freeHostStatuses(testing.allocator, hosts);
    hosts = try store.listHostStatuses(testing.allocator);
    const a = for (hosts) |*host| {
        if (std.mem.eql(u8, host.host, "pds-a.example")) break host;
    } else return error.MissingOldHost;
    const b = for (hosts) |*host| {
        if (std.mem.eql(u8, host.host, "pds-b.example:8443")) break host;
    } else return error.MissingNewHost;
    try testing.expectEqual(@as(u64, 0), a.total);
    try testing.expectEqual(@as(u64, 0), a.count(.complete));
    try testing.expectEqual(@as(u64, 2), a.error_counts[@backingInt(ErrorClass.http_5xx)]);
    try testing.expectEqual(@as(u64, 1), b.total);
    try testing.expectEqual(@as(u64, 1), b.count(.complete));

    // Simulate upgrading a pre-host-aggregate database. The migration rebuilds
    // current counts from repo rows in one synced batch; historical samples
    // cannot be invented and begin accumulating from this point forward.
    try meta.deleteDurable(hosts_version_key);
    try meta.deleteDurable("host/pds-a.example");
    try meta.deleteDurable("host/pds-b.example:8443");
    var migrated = try Store.init(testing.allocator, testing.io, &meta);
    defer migrated.deinit();
    const rebuilt = try migrated.listHostStatuses(testing.allocator);
    defer migrated.freeHostStatuses(testing.allocator, rebuilt);
    try testing.expectEqual(@as(usize, 1), rebuilt.len);
    try testing.expectEqualStrings("pds-b.example:8443", rebuilt[0].host);
    try testing.expectEqual(@as(u64, 1), rebuilt[0].total);
    try testing.expectEqual(@as(u64, 1), rebuilt[0].count(.complete));
}

test "repo transitions atomically maintain the normalized declared-handle index" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);

    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();

    try store.put("did:plc:alice", .{ .status = .complete, .handle = " Alice.Test " });
    var did = (try store.lookupDIDByHandle(testing.allocator, "ALICE.test")).?;
    try testing.expectEqualStrings("did:plc:alice", did);
    testing.allocator.free(did);

    // Moving a DID removes its old index only when that index still names it.
    try store.put("did:plc:bob", .{ .status = .complete, .handle = "alice.test" });
    try store.put("did:plc:alice", .{ .status = .complete, .handle = "alice.new" });
    did = (try store.lookupDIDByHandle(testing.allocator, "alice.test")).?;
    try testing.expectEqualStrings("did:plc:bob", did);
    testing.allocator.free(did);
    did = (try store.lookupDIDByHandle(testing.allocator, "alice.new")).?;
    try testing.expectEqualStrings("did:plc:alice", did);
    testing.allocator.free(did);

    try store.put("did:plc:alice", .{ .status = .complete, .handle = "" });
    try testing.expect(try store.lookupDIDByHandle(testing.allocator, "alice.new") == null);

    // Rebuilding from repo/<did> rows is deterministic and survives restart.
    try meta.deleteDurable(handles_version_key);
    try meta.deleteDurable("handle/alice.test");
    var rebuilt = try Store.init(testing.allocator, testing.io, &meta);
    defer rebuilt.deinit();
    did = (try rebuilt.lookupDIDByHandle(testing.allocator, "alice.test")).?;
    defer testing.allocator.free(did);
    try testing.expectEqualStrings("did:plc:bob", did);
}

test "merge source commit refreshes only latest repo state with its cursor" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);
    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();

    try store.put("did:plc:known", .{
        .status = .complete,
        .rev = "backfill-rev",
        .latest_rev = "old-live-rev",
        .handle = "known.test",
        .pds = "https://pds.example",
        .record_count = 9,
    });
    try store.commitMergeSource("merge/next_source_idx", 7, &.{
        .{ .did = "did:plc:known", .rev = "new-live-rev" },
        // Upstream deliberately does not synthesize malformed lifecycle rows
        // for accounts absent from the bootstrap status map.
        .{ .did = "did:plc:unknown", .rev = "ignored" },
    }, 1234);

    const cursor = (try meta.getAlloc(testing.allocator, "merge/next_source_idx")).?;
    defer testing.allocator.free(cursor);
    try testing.expectEqual(@as(usize, 9), cursor.len);
    try testing.expectEqual(@as(u8, 1), cursor[0]);
    try testing.expectEqual(@as(u64, 7), std.mem.readInt(u64, cursor[1..9], .little));
    const known = (try store.get(testing.allocator, "did:plc:known")).?;
    defer store.freeState(testing.allocator, known);
    try testing.expectEqualStrings("backfill-rev", known.rev);
    try testing.expectEqualStrings("new-live-rev", known.latest_rev);
    try testing.expectEqual(@as(i64, 1234), known.updated_us);
    try testing.expectEqualStrings("known.test", known.handle);
    try testing.expectEqualStrings("https://pds.example", known.pds);
    try testing.expectEqual(@as(i64, 9), known.record_count);
    try testing.expect(try store.get(testing.allocator, "did:plc:unknown") == null);
}

test "v4 rows migrate latest revision without losing lifecycle state" {
    const testing = std.testing;
    var bytes: [v4_header_len + 3 + 4 + 5]u8 = @splat(0);
    bytes[0] = 4;
    bytes[1] = @backingInt(Status.complete);
    bytes[2] = 1;
    std.mem.writeInt(u32, bytes[43..47], 3, .little);
    std.mem.writeInt(u16, bytes[47..49], 4, .little);
    std.mem.writeInt(u16, bytes[49..51], 5, .little);
    bytes[51] = @backingInt(ErrorClass.timeout);
    @memcpy(bytes[52..55], "rev");
    @memcpy(bytes[55..59], "host");
    @memcpy(bytes[59..64], "error");
    const state = try decode(&bytes);
    try testing.expectEqualStrings("rev", state.rev);
    try testing.expectEqualStrings("rev", state.latest_rev);
    try testing.expectEqualStrings("host", state.host);
    try testing.expectEqualStrings("error", state.last_error);
    try testing.expectEqual(ErrorClass.timeout, state.error_class);
}

test "failure classes match upstream diagnostic buckets" {
    const testing = std.testing;
    try testing.expectEqual(ErrorClass.timeout, classifyAttemptError(error.TransferTooSlow));
    try testing.expectEqual(ErrorClass.car, classifyAttemptError(error.InvalidCommit));
    try testing.expectEqual(ErrorClass.verification, classifyAttemptError(error.SignatureVerificationFailed));
    try testing.expectEqual(ErrorClass.local_write, classifyAttemptError(error.ArchiveAppendFailed));
    try testing.expectEqual(ErrorClass.unknown, classifyAttemptError(error.ConnectionResetByPeer));
}

test "resolved PDS endpoints produce upstream host buckets" {
    const testing = std.testing;
    const default_https = try hostFromPDS(testing.allocator, "HTTPS://PDS.EXAMPLE:443");
    defer testing.allocator.free(default_https);
    try testing.expectEqualStrings("pds.example", default_https);
    const custom = try hostFromPDS(testing.allocator, "http://PDS.EXAMPLE:8080/path");
    defer testing.allocator.free(custom);
    try testing.expectEqualStrings("pds.example:8080", custom);
    const ipv6 = try hostFromPDS(testing.allocator, "https://[2001:DB8::1]:8443");
    defer testing.allocator.free(ipv6);
    try testing.expectEqualStrings("[2001:db8::1]:8443", ipv6);
    const default_ipv6 = try hostFromPDS(testing.allocator, "https://[2001:DB8::1]:443");
    defer testing.allocator.free(default_ipv6);
    try testing.expectEqualStrings("2001:db8::1", default_ipv6);
    const invalid = try hostFromPDS(testing.allocator, "javascript:wat");
    defer testing.allocator.free(invalid);
    try testing.expectEqualStrings("invalid-pds", invalid);
}