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

zat.dev/stream

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

0
0
645 lines · 29.9 KB Raw History
//! Reconstruct and verify one repository from Stream's real JSS archive.
//!
//! This is the Zig equivalent of upstream `internal/repoexport`: candidate
//! sealed segments are pruned by their resident-format DID blooms, the active
//! writer and its pending block are snapshotted under the archive lock before
//! sealed selection (closing the rotation race), and repository records are
//! folded last-writer-wins into a canonical AT Protocol MST.

const std = @import("std");
const zat = @import("zat");
const archive_mod = @import("../storage/archive.zig");
const gloom = @import("../storage/gloom.zig");
const segment = @import("../storage/segment.zig");
const writer_mod = @import("../storage/segment_writer.zig");
const cli = @import("../runtime/cli.zig");

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

pub const no_local_repo_message = "repoexport: no local commit events for DID";
pub const root_mismatch_message = "local reconstructed MST root does not match authoritative repo root";

pub const Snapshot = struct {
    did: []const u8,
    latest_rev: []const u8,
    root: zat.cbor.Cid,
    record_count: usize,
};

pub const VerifyReport = struct {
    did: []const u8,
    match: bool = false,
    authoritative_rev: []const u8 = "",
    authoritative_root: []const u8 = "",
    local_latest_rev: []const u8 = "",
    local_root: []const u8 = "",
    local_record_count: usize = 0,
    message: []const u8 = "",
};

/// Compare the PDS's signed commit data root with a reconstruction from the
/// local event archive. The authoritative side deliberately uses the same
/// two PDS-only Sync 1.1 calls as upstream: getLatestCommit, then getBlocks
/// for that commit CID. Only the matching, hash-valid commit block among the
/// first eight CAR blocks is accepted.
pub fn verify(
    allocator: Allocator,
    io: Io,
    archive: *archive_mod.Archive,
    data_dir: []const u8,
    plc_url: []const u8,
    did: []const u8,
) !VerifyReport {
    const parsed_did = zat.Did.parse(did) orelse return error.InvalidDid;
    var resolver = zat.DidResolver.init(io, allocator);
    defer resolver.deinit();
    resolver.plc_url = plc_url;
    var doc = try resolver.resolve(parsed_did);
    defer doc.deinit();
    const endpoint = std.mem.trimEnd(u8, doc.pdsEndpoint() orelse return error.NoAuthoritativePDS, "/");
    if (endpoint.len == 0) return error.NoAuthoritativePDS;

    const latest_url = try xrpcUrlAlloc(allocator, endpoint, "com.atproto.sync.getLatestCommit", &.{.{ .name = "did", .value = did }});
    defer allocator.free(latest_url);
    var transport = zat.HttpTransport.initWithUserAgent(io, allocator, cli.userAgent());
    defer transport.deinit();
    const latest_response = try transport.fetch(.{ .url = latest_url, .max_response_size = 64 * 1024, .on_redirect = .refuse });
    defer allocator.free(latest_response.body);
    if (latest_response.status.class() != .success) return error.GetLatestCommitFailed;
    const latest_json = try std.json.parseFromSlice(std.json.Value, allocator, latest_response.body, .{});
    defer latest_json.deinit();
    const rev_raw = zat.json.getString(latest_json.value, "rev") orelse return error.InvalidLatestCommit;
    const cid_raw = zat.json.getString(latest_json.value, "cid") orelse return error.InvalidLatestCommit;
    const rev = try allocator.dupe(u8, rev_raw);
    const commit_cid_string = try allocator.dupe(u8, cid_raw);
    const commit_cid = try zat.mst.parseCidString(allocator, commit_cid_string);

    const blocks_url = try xrpcUrlAlloc(allocator, endpoint, "com.atproto.sync.getBlocks", &.{
        .{ .name = "did", .value = did },
        .{ .name = "cids", .value = commit_cid_string },
    });
    defer allocator.free(blocks_url);
    const blocks_response = try transport.fetch(.{
        .url = blocks_url,
        .max_response_size = 8 * (1024 * 1024 + 128) + 64 * 1024,
        .on_redirect = .refuse,
    });
    defer allocator.free(blocks_response.body);
    if (blocks_response.status.class() != .success) return error.GetCommitBlockFailed;
    const commit_data = try findAuthoritativeCommitBlock(allocator, blocks_response.body, commit_cid);

    const roots = [_]zat.cbor.Cid{commit_cid};
    const blocks = [_]zat.car.Block{.{ .cid_raw = commit_cid.raw, .data = commit_data }};
    const single_car = try zat.car.writeAlloc(allocator, .{ .roots = &roots, .blocks = &blocks });
    defer allocator.free(single_car);
    const loaded = try zat.loadCommitFromCAR(allocator, single_car);
    if (!std.mem.eql(u8, loaded.commit.did, did)) return error.AuthoritativeCommitDidMismatch;
    if (!std.mem.eql(u8, loaded.commit.rev, rev)) return error.AuthoritativeCommitRevMismatch;
    const authoritative_root = try zat.multibase.base32lower.encode(allocator, loaded.commit.data_cid);

    var report: VerifyReport = .{
        .did = did,
        .authoritative_rev = rev,
        .authoritative_root = authoritative_root,
    };
    const local = reconstruct(allocator, io, archive, data_dir, did) catch |err| switch (err) {
        error.NoLocalRepo => {
            report.message = try std.fmt.allocPrint(allocator, "{s}: {s}", .{ no_local_repo_message, did });
            return report;
        },
        else => return err,
    };
    defer freeSnapshot(allocator, local);
    report.local_latest_rev = try allocator.dupe(u8, local.latest_rev);
    report.local_root = try zat.multibase.base32lower.encode(allocator, local.root.raw);
    report.local_record_count = local.record_count;
    report.match = std.mem.eql(u8, report.authoritative_root, report.local_root);
    if (!report.match) report.message = root_mismatch_message;
    return report;
}

const QueryParam = struct { name: []const u8, value: []const u8 };

fn xrpcUrlAlloc(allocator: Allocator, endpoint: []const u8, nsid: []const u8, params: []const QueryParam) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(allocator);
    try out.print(allocator, "{s}/xrpc/{s}", .{ endpoint, nsid });
    for (params, 0..) |param, index| {
        try out.append(allocator, if (index == 0) '?' else '&');
        try out.appendSlice(allocator, param.name);
        try out.append(allocator, '=');
        for (param.value) |byte| {
            if (std.ascii.isAlphanumeric(byte) or byte == '-' or byte == '_' or byte == '.' or byte == '~')
                try out.append(allocator, byte)
            else
                try out.print(allocator, "%{X:0>2}", .{byte});
        }
    }
    return out.toOwnedSlice(allocator);
}

fn findAuthoritativeCommitBlock(allocator: Allocator, car_bytes: []const u8, wanted: zat.cbor.Cid) ![]const u8 {
    var pos: usize = 0;
    const header_len_u64 = zat.cbor.readUvarint(car_bytes, &pos) orelse return error.InvalidAuthoritativeCar;
    const header_len = std.math.cast(usize, header_len_u64) orelse return error.InvalidAuthoritativeCar;
    if (header_len > 1024 * 1024 or pos + header_len > car_bytes.len) return error.InvalidAuthoritativeCar;
    var header_arena = std.heap.ArenaAllocator.init(allocator);
    defer header_arena.deinit();
    const header = try zat.cbor.decodeAll(header_arena.allocator(), car_bytes[pos..][0..header_len]);
    if (header.getUint("version") != 1) return error.InvalidAuthoritativeCar;
    pos += header_len;
    var blocks_read: usize = 0;
    while (pos < car_bytes.len and blocks_read < 8) : (blocks_read += 1) {
        const block_len_u64 = zat.cbor.readUvarint(car_bytes, &pos) orelse return error.InvalidAuthoritativeCar;
        const block_len = std.math.cast(usize, block_len_u64) orelse return error.InvalidAuthoritativeCar;
        if (block_len == 0 or block_len > 1024 * 1024 or pos + block_len > car_bytes.len) return error.InvalidAuthoritativeCar;
        const raw = car_bytes[pos..][0..block_len];
        const cid_len = cidLength(raw) orelse return error.InvalidAuthoritativeCar;
        if (cid_len > raw.len) return error.InvalidAuthoritativeCar;
        const claimed: zat.cbor.Cid = .{ .raw = raw[0..cid_len] };
        const data = raw[cid_len..];
        if (claimed.version() != 1 or claimed.hashFn() != zat.cbor.HashFn.sha2_256) return error.InvalidAuthoritativeCar;
        const computed = try zat.cbor.Cid.create(header_arena.allocator(), 1, claimed.codec() orelse return error.InvalidAuthoritativeCar, zat.cbor.HashFn.sha2_256, data);
        if (!std.mem.eql(u8, computed.raw, claimed.raw)) return error.AuthoritativeBlockCidMismatch;
        pos += block_len;
        if (std.mem.eql(u8, claimed.raw, wanted.raw)) return data;
    }
    // Upstream classifies any eight non-matching blocks as the bounded-search
    // limit, even when the eighth block is also the end of the response.
    if (blocks_read >= 8) return error.AuthoritativeCommitBlockLimit;
    return error.AuthoritativeCommitBlockNotFound;
}

fn cidLength(data: []const u8) ?usize {
    if (data.len < 2) return null;
    if (data[0] == 0x12 and data[1] == 0x20) return if (data.len >= 34) 34 else null;
    var pos: usize = 0;
    _ = zat.cbor.readUvarint(data, &pos) orelse return null;
    _ = zat.cbor.readUvarint(data, &pos) orelse return null;
    _ = zat.cbor.readUvarint(data, &pos) orelse return null;
    const digest_len = zat.cbor.readUvarint(data, &pos) orelse return null;
    const digest_len_usize = std.math.cast(usize, digest_len) orelse return null;
    if (pos + digest_len_usize > data.len) return null;
    return pos + digest_len_usize;
}

const ReplayState = struct {
    allocator: Allocator,
    did: []const u8,
    records: std.StringHashMap([]const u8),
    latest_rev: []const u8 = "",
    seen_commit: bool = false,

    fn init(allocator: Allocator, did: []const u8) ReplayState {
        return .{ .allocator = allocator, .did = did, .records = std.StringHashMap([]const u8).init(allocator) };
    }

    fn deinit(self: *ReplayState) void {
        var it = self.records.iterator();
        while (it.next()) |entry| {
            self.allocator.free(entry.key_ptr.*);
            self.allocator.free(entry.value_ptr.*);
        }
        self.records.deinit();
        if (self.latest_rev.len > 0) self.allocator.free(@constCast(self.latest_rev));
    }

    fn apply(self: *ReplayState, ev: segment.Event, watermark: []const u8) !void {
        if (!std.mem.eql(u8, ev.did, self.did)) return;
        switch (ev.kind) {
            .create, .update, .create_resync => {
                if (watermark.len > 0 and std.mem.order(u8, ev.rev, watermark) != .gt) return;
                const key = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ ev.collection, ev.rkey });
                errdefer self.allocator.free(key);
                const payload = try self.allocator.dupe(u8, ev.payload);
                errdefer self.allocator.free(payload);
                if (self.records.getPtr(key)) |old_payload| {
                    self.allocator.free(key);
                    self.allocator.free(@constCast(old_payload.*));
                    old_payload.* = payload;
                } else {
                    try self.records.put(key, payload);
                }
            },
            .delete => {
                if (watermark.len > 0 and std.mem.order(u8, ev.rev, watermark) != .gt) return;
                const key = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ ev.collection, ev.rkey });
                defer self.allocator.free(key);
                if (self.records.fetchRemove(key)) |entry| {
                    self.allocator.free(entry.key);
                    self.allocator.free(entry.value);
                }
            },
            else => return,
        }
        self.seen_commit = true;
        if (self.latest_rev.len > 0) self.allocator.free(@constCast(self.latest_rev));
        self.latest_rev = try self.allocator.dupe(u8, ev.rev);
    }
};

const ActiveSnapshot = struct {
    bytes: []u8,
    pending: []segment.Event,

    fn deinit(self: *ActiveSnapshot, allocator: Allocator) void {
        allocator.free(self.bytes);
        for (self.pending) |ev| {
            allocator.free(@constCast(ev.did));
            allocator.free(@constCast(ev.collection));
            allocator.free(@constCast(ev.rkey));
            allocator.free(@constCast(ev.rev));
            allocator.free(@constCast(ev.payload));
        }
        allocator.free(self.pending);
    }
};

/// Reconstruct at a rotation-safe point in time. `data_dir` is used only for
/// the bootstrap live archive, which is absent after steady-state cleanup.
pub fn reconstruct(allocator: Allocator, io: Io, archive: *archive_mod.Archive, data_dir: []const u8, did: []const u8) !Snapshot {
    if (zat.Did.parse(did) == null) return error.InvalidDid;
    var state = ReplayState.init(allocator, did);
    defer state.deinit();

    // Upstream's critical ordering: active paths before sealed selection. We
    // make the boundary stronger by copying the active frames and pending rows
    // together under the writer lock, then scan the sealed directory.
    var active = try snapshotActive(allocator, io, archive);
    defer active.deinit(allocator);

    var names: std.ArrayList([]u8) = .empty;
    defer {
        for (names.items) |name| allocator.free(name);
        names.deinit(allocator);
    }
    var it = archive.dir.iterate();
    while (try it.next(io)) |entry| {
        if (archive_mod.parseSegmentIndex(entry.name) == null) continue;
        try names.append(allocator, try allocator.dupe(u8, entry.name));
    }
    std.mem.sort([]u8, names.items, {}, struct {
        fn less(_: void, a: []u8, b: []u8) bool {
            return std.mem.order(u8, a, b) == .lt;
        }
    }.less);
    for (names.items) |name| try replaySealedCandidate(allocator, io, archive.dir, name, &state);
    try replayActiveBytes(allocator, active.bytes, "", &state);

    const primary_watermark = if (state.latest_rev.len > 0) try allocator.dupe(u8, state.latest_rev) else "";
    defer if (primary_watermark.len > 0) allocator.free(@constCast(primary_watermark));
    try replayBootstrapLive(allocator, io, data_dir, primary_watermark, &state);
    for (active.pending) |ev| try state.apply(ev, "");

    if (!state.seen_commit) return error.NoLocalRepo;
    var tree_arena = std.heap.ArenaAllocator.init(allocator);
    defer tree_arena.deinit();
    const tree_allocator = tree_arena.allocator();
    var tree = zat.mst.Mst.init(tree_allocator);
    var keys: std.ArrayList([]const u8) = .empty;
    defer keys.deinit(allocator);
    var key_it = state.records.keyIterator();
    while (key_it.next()) |key| try keys.append(allocator, key.*);
    std.mem.sort([]const u8, keys.items, {}, struct {
        fn less(_: void, a: []const u8, b: []const u8) bool {
            return std.mem.order(u8, a, b) == .lt;
        }
    }.less);
    for (keys.items) |key| {
        const cid = try zat.cbor.Cid.forDagCbor(tree_allocator, state.records.get(key).?);
        try tree.putBorrowed(key, cid);
    }
    const root = try tree.rootCid();
    return .{
        .did = try allocator.dupe(u8, did),
        .latest_rev = try allocator.dupe(u8, state.latest_rev),
        .root = .{ .raw = try allocator.dupe(u8, root.raw) },
        .record_count = state.records.count(),
    };
}

pub fn freeSnapshot(allocator: Allocator, snapshot: Snapshot) void {
    allocator.free(snapshot.did);
    allocator.free(snapshot.latest_rev);
    allocator.free(snapshot.root.raw);
}

fn snapshotActive(allocator: Allocator, io: Io, archive: *archive_mod.Archive) !ActiveSnapshot {
    archive.mu.lockUncancelable(io);
    defer archive.mu.unlock(io);
    const bytes = try allocator.dupe(u8, archive.writer.bytes());
    errdefer allocator.free(bytes);
    const pending = try allocator.alloc(segment.Event, archive.writer.pending.items.len);
    errdefer allocator.free(pending);
    var copied: usize = 0;
    errdefer for (pending[0..copied]) |ev| {
        allocator.free(@constCast(ev.did));
        allocator.free(@constCast(ev.collection));
        allocator.free(@constCast(ev.rkey));
        allocator.free(@constCast(ev.rev));
        allocator.free(@constCast(ev.payload));
    };
    for (archive.writer.pending.items, 0..) |ev, index| {
        pending[index] = try dupeEvent(allocator, ev);
        copied += 1;
    }
    return .{ .bytes = bytes, .pending = pending };
}

fn dupeEvent(allocator: Allocator, ev: segment.Event) !segment.Event {
    const did = try allocator.dupe(u8, ev.did);
    errdefer allocator.free(did);
    const collection = try allocator.dupe(u8, ev.collection);
    errdefer allocator.free(collection);
    const rkey = try allocator.dupe(u8, ev.rkey);
    errdefer allocator.free(rkey);
    const rev = try allocator.dupe(u8, ev.rev);
    errdefer allocator.free(rev);
    const payload = try allocator.dupe(u8, ev.payload);
    return .{
        .seq = ev.seq,
        .witnessed_at = ev.witnessed_at,
        .indexed_at = ev.indexed_at,
        .kind = ev.kind,
        .did = did,
        .collection = collection,
        .rkey = rkey,
        .rev = rev,
        .payload = payload,
    };
}

fn replaySealedCandidate(allocator: Allocator, io: Io, dir: Io.Dir, name: []const u8, state: *ReplayState) !void {
    var file = try dir.openFile(io, name, .{});
    defer file.close(io);
    var header_bytes: [segment.header_size]u8 = undefined;
    if (try file.readPositionalAll(io, &header_bytes, 0) != header_bytes.len) return error.Truncated;
    const header = segment.Header.decode(&header_bytes) catch |err| switch (err) {
        error.ActiveSegment => return,
        else => return err,
    };
    if (header.block_did_bloom_offset < header.did_bloom_offset) return error.BadFooter;
    const bloom_len = header.block_did_bloom_offset - header.did_bloom_offset;
    if (bloom_len > 1 << 30) return error.LimitExceeded;
    const bloom_bytes = try allocator.alloc(u8, @intCast(bloom_len));
    defer allocator.free(bloom_bytes);
    if (try file.readPositionalAll(io, bloom_bytes, header.did_bloom_offset) != bloom_bytes.len) return error.Truncated;
    var filter = try gloom.unmarshal(allocator, bloom_bytes);
    defer filter.deinit(allocator);
    if (!filter.contains(state.did)) return;

    const bytes = try dir.readFileAlloc(io, name, allocator, .limited(1 << 31));
    defer allocator.free(bytes);
    var sealed = try segment.Sealed.parse(allocator, bytes);
    defer sealed.deinit(allocator);
    const blobs = try sealed.blockBloomBlobs(allocator);
    defer allocator.free(blobs);
    for (blobs, 0..) |blob, index| {
        var block_filter = gloom.unmarshal(allocator, blob) catch null;
        if (block_filter) |*candidate| {
            defer candidate.deinit(allocator);
            if (!candidate.contains(state.did)) continue;
        }
        var block = try sealed.readBlock(allocator, index);
        defer block.deinit(allocator);
        for (block.events) |ev| try state.apply(ev, "");
    }
}

fn replayActiveBytes(allocator: Allocator, bytes: []const u8, watermark: []const u8, state: *ReplayState) !void {
    var it: writer_mod.ActiveIterator = .{ .bytes = bytes };
    while (try it.next(allocator)) |block_value| {
        var block = block_value;
        defer block.deinit(allocator);
        for (block.events) |ev| try state.apply(ev, watermark);
    }
}

fn replayBootstrapLive(allocator: Allocator, io: Io, data_dir: []const u8, watermark: []const u8, state: *ReplayState) !void {
    var path_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const path = std.fmt.bufPrint(&path_buf, "{s}/backfill/live/segments", .{data_dir}) catch return error.NameTooLong;
    var dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch |err| switch (err) {
        error.FileNotFound => return,
        else => return err,
    };
    defer dir.close(io);
    var names: std.ArrayList([]u8) = .empty;
    defer {
        for (names.items) |name| allocator.free(name);
        names.deinit(allocator);
    }
    var it = dir.iterate();
    while (try it.next(io)) |entry| if (archive_mod.parseSegmentIndex(entry.name) != null)
        try names.append(allocator, try allocator.dupe(u8, entry.name));
    std.mem.sort([]u8, names.items, {}, struct {
        fn less(_: void, a: []u8, b: []u8) bool {
            return std.mem.order(u8, a, b) == .lt;
        }
    }.less);
    for (names.items) |name| {
        const bytes = try dir.readFileAlloc(io, name, allocator, .limited(1 << 31));
        defer allocator.free(bytes);
        if (segment.Header.decode(bytes)) |_| {
            var sealed = try segment.Sealed.parse(allocator, bytes);
            defer sealed.deinit(allocator);
            for (sealed.block_index, 0..) |_, index| {
                var block = try sealed.readBlock(allocator, index);
                defer block.deinit(allocator);
                for (block.events) |ev| try state.apply(ev, watermark);
            }
        } else |err| switch (err) {
            error.ActiveSegment => try replayActiveBytes(allocator, bytes, watermark, state),
            else => return err,
        }
    }
}

const testing = std.testing;

fn fixtureEvent(did: []const u8, kind: segment.Kind, rkey: []const u8, rev: []const u8, payload: []const u8) segment.Event {
    return .{
        .seq = 0,
        .witnessed_at = 1_750_000_000_000_000,
        .indexed_at = 0,
        .kind = kind,
        .did = did,
        .collection = "app.bsky.feed.post",
        .rkey = rkey,
        .rev = rev,
        .payload = payload,
    };
}

test "reconstruct prunes real sealed JSS and includes flushed active plus pending events" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    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 data_dir = root_buf[0..root_len];
    var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer archive.deinit();
    archive.max_events_per_block = 2;
    archive.writer.max_events_per_block = 2;

    const did = "did:plc:reconstructfixture";
    const other = "did:plc:otherfixture";
    const first = "\xa1\x64text\x65first";
    const second = "\xa1\x64text\x66second";
    const latest = "\xa1\x64text\x66latest";
    _ = try archive.append(fixtureEvent(did, .create, "one", "3la", first), 1);
    _ = try archive.append(fixtureEvent(other, .create, "other", "3la", second), 1);
    try archive.rotate();
    // This pair flushes into the active file. The final row stays only in the
    // writer's pending block, exercising all three production sources.
    _ = try archive.append(fixtureEvent(did, .update, "one", "3lb", second), 2);
    _ = try archive.append(fixtureEvent(other, .update, "other", "3lb", first), 2);
    _ = try archive.append(fixtureEvent(did, .create, "two", "3lc", latest), 2);
    _ = try archive.append(fixtureEvent(did, .delete, "one", "3ld", ""), 2);

    const snapshot = try reconstruct(testing.allocator, io, &archive, data_dir, did);
    defer freeSnapshot(testing.allocator, snapshot);
    try testing.expectEqualStrings("3ld", snapshot.latest_rev);
    try testing.expectEqual(@as(usize, 1), snapshot.record_count);

    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();
    var expected = zat.mst.Mst.init(alloc);
    const record_cid = try zat.cbor.Cid.forDagCbor(alloc, latest);
    try expected.put("app.bsky.feed.post/two", record_cid);
    const expected_root = try expected.rootCid();
    try testing.expectEqualSlices(u8, expected_root.raw, snapshot.root.raw);
}

test "reconstruct distinguishes an absent DID from an empty repository" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    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 data_dir = root_buf[0..root_len];
    var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer archive.deinit();
    try testing.expectError(error.NoLocalRepo, reconstruct(testing.allocator, io, &archive, data_dir, "did:plc:absentfixture"));

    const did = "did:plc:emptyfixture";
    _ = try archive.append(fixtureEvent(did, .delete, "gone", "3la", ""), 1);
    const snapshot = try reconstruct(testing.allocator, io, &archive, data_dir, did);
    defer freeSnapshot(testing.allocator, snapshot);
    try testing.expectEqual(@as(usize, 0), snapshot.record_count);
    try testing.expectEqualStrings("3la", snapshot.latest_rev);
}

test "verify compares a real JSS reconstruction with real PLC and PDS Sync responses offline" {
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var fixture_arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer fixture_arena.deinit();
    const alloc = fixture_arena.allocator();

    const did = "did:plc:verifyfixture";
    const rev = "3k2abcdefghij";
    const record = try zat.cbor.encodeAlloc(alloc, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
        .{ .key = "text", .value = .{ .text = "offline verification" } },
    } });
    const record_cid = try zat.cbor.Cid.forDagCbor(alloc, record);
    var authoritative_tree = zat.mst.Mst.init(alloc);
    try authoritative_tree.put("app.bsky.feed.post/fixture", record_cid);
    const data_root = try authoritative_tree.rootCid();
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(41));
    const signed = try zat.signCommit(alloc, .{ .did = did, .rev = rev, .data = data_root }, &keypair);
    const commit_cid_string = try zat.multibase.base32lower.encode(alloc, signed.cid.raw);
    const decoy_data = "decoy";
    const decoy_cid = try zat.cbor.Cid.forDagCbor(alloc, decoy_data);
    // PDS getBlocks legitimately uses an empty-roots CAR; put a valid decoy
    // first to prove the verifier searches rather than trusting block zero.
    const get_blocks_car = try zat.car.writeAlloc(alloc, .{
        .roots = &.{},
        .blocks = &.{
            .{ .cid_raw = decoy_cid.raw, .data = decoy_data },
            .{ .cid_raw = signed.cid.raw, .data = signed.bytes },
        },
    });

    var listener = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer listener.deinit(io);
    var endpoint_buf: [96]u8 = undefined;
    const endpoint = try std.fmt.bufPrint(&endpoint_buf, "http://127.0.0.1:{d}", .{listener.socket.address.getPort()});
    const did_doc = try std.fmt.allocPrint(alloc,
        \\{{"id":"{s}","alsoKnownAs":["at://verify.example"],"verificationMethod":[],"service":[{{"id":"#atproto_pds","type":"AtprotoPersonalDataServer","serviceEndpoint":"{s}"}}]}}
    , .{ did, endpoint });
    const latest_json = try std.fmt.allocPrint(alloc, "{{\"cid\":\"{s}\",\"rev\":\"{s}\"}}", .{ commit_cid_string, rev });
    const Fixture = struct {
        fn run(server: *Io.net.Server, task_io: Io, doc: []const u8, latest: []const u8, blocks_car: []const u8) !void {
            for (0..3) |_| {
                var stream = try server.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 = std.http.Server.init(&reader.interface, &writer.interface);
                var request = try http.receiveHead();
                const target = request.head.target;
                const body, const content_type = if (std.mem.indexOf(u8, target, "getLatestCommit") != null)
                    .{ latest, "application/json" }
                else if (std.mem.indexOf(u8, target, "getBlocks") != null)
                    .{ blocks_car, "application/vnd.ipld.car" }
                else
                    .{ doc, "application/json" };
                try request.respond(body, .{
                    .status = .ok,
                    .keep_alive = false,
                    .extra_headers = &.{.{ .name = "content-type", .value = content_type }},
                });
            }
        }
    };
    var server_future = try io.concurrent(Fixture.run, .{ &listener, io, did_doc, latest_json, get_blocks_car });
    defer _ = server_future.cancel(io) catch {};

    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 data_dir = root_buf[0..root_len];
    var archive = try archive_mod.Archive.init(testing.allocator, io, data_dir);
    defer archive.deinit();
    _ = try archive.append(fixtureEvent(did, .create, "fixture", rev, record), 1);

    var verify_arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer verify_arena.deinit();
    const report = try verify(verify_arena.allocator(), io, &archive, data_dir, endpoint, did);
    try testing.expect(report.match);
    try testing.expectEqualStrings(rev, report.authoritative_rev);
    try testing.expectEqualStrings(rev, report.local_latest_rev);
    try testing.expectEqual(@as(usize, 1), report.local_record_count);
    try testing.expectEqualStrings(report.authoritative_root, report.local_root);
    try testing.expectEqualStrings("", report.message);
    _ = try server_future.await(io);
}

test "authoritative commit search matches upstream eight-block boundary" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();
    var blocks: [8]zat.car.Block = undefined;
    for (&blocks, 0..) |*block, index| {
        const data = try std.fmt.allocPrint(alloc, "decoy-{d}", .{index});
        const cid = try zat.cbor.Cid.forDagCbor(alloc, data);
        block.* = .{ .cid_raw = cid.raw, .data = data };
    }
    const wanted = try zat.cbor.Cid.forDagCbor(alloc, "wanted");
    const seven = try zat.car.writeAlloc(alloc, .{ .roots = &.{}, .blocks = blocks[0..7] });
    try testing.expectError(error.AuthoritativeCommitBlockNotFound, findAuthoritativeCommitBlock(alloc, seven, wanted));
    const eight = try zat.car.writeAlloc(alloc, .{ .roots = &.{}, .blocks = &blocks });
    try testing.expectError(error.AuthoritativeCommitBlockLimit, findAuthoritativeCommitBlock(alloc, eight, wanted));
}