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

zat.dev/stream

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

0
0
1957 lines · 84.4 KB Raw History
//! backfill XRPC API — network.bsky.jetstream.{listSegments,getSegment,getBlock}
//!
//! serves the archive's sealed segments per upstream's lexicons: listSegments
//! returns JSON metadata (checksum hex == the getSegment ETag), getSegment
//! streams the raw .jss bytes, getBlock returns one block's raw stored zstd
//! frame (located via the footer's block index with positional reads — the
//! file is never loaded whole). the segment format is wire-visible contract;
//! upstream's client parses these bytes with its own segment package.
//!
//! getSegment and getBlock match upstream's http.ServeContent byte-range
//! contract, including multipart/byteranges and mixed overlap handling.

const std = @import("std");
const api_keys = @import("api_keys.zig");
const archive_mod = @import("../storage/archive.zig");
const segment = @import("../storage/segment.zig");
const import_manager = @import("../timestamp/manager.zig");
const import_jobs = @import("../timestamp/jobs.zig");
const http_time = @import("http_time.zig");
const metrics = @import("../runtime/metrics.zig");
const observability = @import("../runtime/observability.zig");
const time_format = @import("../ingest/backfill/resync.zig");
const zstd = @import("../storage/zstd.zig");

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

pub const Preconditions = struct {
    range: ?[]const u8 = null,
    if_match: ?[]const u8 = null,
    if_unmodified_since: ?[]const u8 = null,
    if_none_match: ?[]const u8 = null,
    if_modified_since: ?[]const u8 = null,
    if_range: ?[]const u8 = null,
};

pub const PlanConfig = struct {
    max_dids: usize = 1000,
    max_collections: usize = 25,
    max_entries: usize = 100_000,
    whole_segment_threshold: f64 = 0.75,
};

pub const Api = struct {
    allocator: Allocator,
    io: Io,
    archive: *archive_mod.Archive,
    segment_cache_max_age_s: u64 = 0,
    plan: PlanConfig = .{},
    import: ?*import_manager.Manager = null,
    import_token: []const u8 = "",
    /// Gates the archive endpoints when non-empty, mirroring the hosted
    /// Bluesky instances (Jetstream v2, 2026-08-13): live tail and
    /// getZstdDictionary stay open, archive requests need a bearer key.
    /// Empty = open archive — the operator's opt-in, since gating an
    /// already-public surface must be a deliberate flip, not a default.
    archive_api_key: []const u8 = "",
    /// named, revocable, per-key-metered archive keys (api_keys.zig).
    /// checked when the fleet key above does not match; null = ring
    /// disabled and the single key is the only credential.
    key_ring: ?*api_keys.KeyRing = null,
    /// Keep one manifest planning pass in flight so public callers cannot
    /// multiply CPU and response allocation with concurrent requests.
    plan_mutex: Io.Mutex = .init,

    /// route an /xrpc/network.bsky.jetstream.* request. returns false when
    /// the path isn't ours (caller 404s).
    pub fn handle(self: *Api, respond: anytype, http_method: []const u8, path: []const u8, query: []const u8, body: []const u8, authorization: ?[]const u8, preconditions: Preconditions) bool {
        const prefix = "/xrpc/network.bsky.jetstream.";
        if (!std.mem.startsWith(u8, path, prefix)) return false;
        const method = path[prefix.len..];
        const is_post = std.mem.eql(u8, http_method, "POST");
        const is_get = std.mem.eql(u8, http_method, "GET");
        if (std.mem.eql(u8, method, "importTimestamps")) {
            if (!authorized(self.import_token, authorization)) {
                respond.err(401, "AuthRequired", "invalid or missing bearer token");
                return true;
            }
            if (!is_post) {
                respond.err(405, "InvalidRequest", "importTimestamps is a procedure (POST)");
                return true;
            }
            self.importTimestamps(respond, body);
            return true;
        }
        if (std.mem.eql(u8, method, "getImportStatus")) {
            if (!authorized(self.import_token, authorization)) {
                respond.err(401, "AuthRequired", "invalid or missing bearer token");
                return true;
            }
            if (!is_get) {
                respond.err(405, "InvalidRequest", "getImportStatus is a query (GET)");
                return true;
            }
            self.getImportStatus(respond, query);
            return true;
        }
        const archive_method = std.mem.eql(u8, method, "planSnapshot") or
            std.mem.eql(u8, method, "listSegments") or
            std.mem.eql(u8, method, "getSegment") or
            std.mem.eql(u8, method, "getBlock");
        var metered: ?*api_keys.Entry = null;
        var key_name: []const u8 = "open";
        if (archive_method) {
            const fleet_ok = self.archive_api_key.len > 0 and authorized(self.archive_api_key, authorization);
            if (fleet_ok) key_name = "fleet";
            const gated = self.archive_api_key.len > 0 or self.key_ring != null;
            if (gated and !fleet_ok) {
                const ring = self.key_ring orelse {
                    respond.unauthorized();
                    return true;
                };
                const now_us = nowUs(self.io);
                metered = ring.authorize(self.io, authorization, now_us) orelse {
                    respond.unauthorized();
                    return true;
                };
                key_name = metered.?.name;
                if (ring.precheck(self.io, metered.?, now_us)) |_| {
                    // the SDK's fetchWithRetry backs off on 429 (1s/2s/4s)
                    respond.err(429, "RateLimitExceeded", "per-key byte budget exhausted; retry shortly");
                    return true;
                }
            }
        }
        if (std.mem.eql(u8, method, "planSnapshot")) {
            if (!is_post) {
                respond.err(405, "InvalidRequest", "planSnapshot is a procedure (POST)");
                return true;
            }
            planSnapshot(self, respond, body, key_name);
            self.chargeMetered(respond, metered);
            return true;
        }
        if (std.mem.eql(u8, method, "planBackfill")) {
            // renamed upstream (655ecc5); a hard 400 naming the successor
            // beats a silent 501 for the handful of pre-rename consumers
            respond.err(400, "InvalidRequest", "planBackfill was renamed; call network.bsky.jetstream.planSnapshot");
            return true;
        }
        if (!is_get) {
            respond.err(405, "InvalidRequest", "queries are GET");
            return true;
        }
        if (std.mem.eql(u8, method, "getZstdDictionary")) {
            self.getZstdDictionary(respond, query, preconditions.if_none_match);
        } else if (std.mem.eql(u8, method, "listSegments")) {
            self.listSegments(respond, query);
        } else if (std.mem.eql(u8, method, "getSegment")) {
            self.getSegment(respond, query, preconditions);
        } else if (std.mem.eql(u8, method, "getBlock")) {
            self.getBlock(respond, query, preconditions);
        } else {
            respond.err(501, "MethodNotImplemented", method);
        }
        self.chargeMetered(respond, metered);
        return true;
    }

    /// charge a metered key for the bytes the responder actually served.
    /// post-hoc by design: the bucket may go negative and gates the NEXT
    /// request, so one oversized response is always allowed through.
    fn chargeMetered(self: *Api, respond: anytype, metered: ?*api_keys.Entry) void {
        const entry = metered orelse return;
        const ring = self.key_ring orelse return;
        const bytes: u64 = if (comptime @hasDecl(@TypeOf(respond.*), "servedBytes")) respond.servedBytes() else 0;
        ring.charge(self.io, entry, bytes, nowUs(self.io));
    }

    fn nowUs(io: Io) i64 {
        return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_us));
    }

    fn getZstdDictionary(_: *Api, respond: anytype, query: []const u8, if_none_match: ?[]const u8) void {
        if (queryParam(query, "id")) |raw| {
            const parsed = std.fmt.parseInt(i64, raw, 10) catch
                return respond.err(400, "InvalidRequest", "id must be an integer zstd dictionary ID");
            if (parsed <= 0 or parsed > std.math.maxInt(u32) or @as(u32, @intCast(parsed)) != zstd.v2_dictionary_id) {
                var message: [160]u8 = undefined;
                const out = std.fmt.bufPrint(&message, "no dictionary with id {d}; current dictionary id is {d}", .{ parsed, zstd.v2_dictionary_id }) catch unreachable;
                return respond.err(404, "DictionaryNotFound", out);
            }
        }
        var etag_buf: [48]u8 = undefined;
        const etag = std.fmt.bufPrint(&etag_buf, "\"zstd-dict-{d}\"", .{zstd.v2_dictionary_id}) catch unreachable;
        respond.dictionary(&zstd.v2_dictionary, zstd.v2_dictionary_id, etag, if_none_match != null and std.mem.eql(u8, if_none_match.?, etag));
    }

    fn importTimestamps(self: *Api, respond: anytype, body: []const u8) void {
        const manager = self.import orelse return respond.err(503, "ImportNotReady", "timestamp import is not configured");
        var parsed = std.json.parseFromSlice(std.json.Value, self.allocator, body, .{}) catch
            return respond.err(400, "InvalidRequest", "malformed request body");
        defer parsed.deinit();
        if (parsed.value != .object) return respond.err(400, "InvalidRequest", "request body must be an object");
        const path = parsed.value.object.get("path") orelse
            return respond.err(400, "InvalidRequest", "missing path");
        if (path != .string) return respond.err(400, "InvalidRequest", "path must be a string");
        const id = manager.submit(path.string) catch |err| return switch (err) {
            error.ImportJobInProgress => respond.err(409, "ImportInProgress", @errorName(err)),
            error.ImportNotReady => respond.err(503, "ImportNotReady", @errorName(err)),
            error.ImportPathRequired,
            error.ImportPathEscape,
            error.ImportPathNotFound,
            error.ImportPathNotRegularFile,
            => respond.err(400, "InvalidPath", @errorName(err)),
            else => respond.err(500, "InternalError", "failed to submit import"),
        };
        defer self.allocator.free(id);
        var output: Io.Writer.Allocating = .init(self.allocator);
        defer output.deinit();
        var json: std.json.Stringify = .{ .writer = &output.writer };
        json.write(.{ .job = id }) catch return respond.err(500, "InternalError", "failed to encode response");
        respond.json(200, output.written());
    }

    fn getImportStatus(self: *Api, respond: anytype, query: []const u8) void {
        const manager = self.import orelse return respond.err(503, "ImportNotReady", "timestamp import is not configured");
        const requested = queryParam(query, "job");
        var parsed = if (requested != null and requested.?.len > 0)
            manager.status(requested.?) catch |err| return switch (err) {
                error.ImportJobNotFound => respond.err(404, "JobNotFound", "job not found"),
                else => respond.err(500, "InternalError", "failed to read import status"),
            }
        else
            (manager.current() catch return respond.err(500, "InternalError", "failed to read import status")) orelse
                return respond.err(404, "JobNotFound", "no import job has run");
        defer parsed.deinit();
        writeImportStatus(self.allocator, respond, parsed.value);
    }

    fn listSegments(self: *Api, respond: anytype, query: []const u8) void {
        const limit = blk: {
            const raw = queryParam(query, "limit") orelse break :blk 100;
            const v = std.fmt.parseInt(usize, raw, 10) catch
                return respond.err(400, "InvalidRequest", "limit must be an integer");
            if (v < 1)
                return respond.err(400, "InvalidRequest", "limit must be positive");
            break :blk @min(v, 1000);
        };
        // cursor = last segment index already returned, as decimal text
        const after: ?u64 = blk: {
            const raw = queryParam(query, "cursor") orelse break :blk null;
            break :blk std.fmt.parseInt(u64, raw, 10) catch
                return respond.err(400, "InvalidRequest", "invalid cursor");
        };

        var arena = std.heap.ArenaAllocator.init(self.allocator);
        defer arena.deinit();
        const alloc = arena.allocator();

        const summaries = self.archive.manifest.all(alloc) catch
            return respond.err(500, "InternalError", "oom");

        var out: Io.Writer.Allocating = .init(alloc);
        renderSegments(summaries, limit, after, &out) catch
            return respond.err(500, "InternalError", "oom");
        respond.json(200, out.written());
    }

    fn getSegment(self: *Api, respond: anytype, query: []const u8, preconditions: Preconditions) void {
        const name = queryParam(query, "name") orelse
            return respond.err(400, "InvalidRequest", "missing name");
        const idx = archive_mod.parseSegmentIndex(name) orelse
            return respond.err(400, "InvalidRequest", "bad segment name");
        _ = self.archive.manifest.segmentByIndex(idx) orelse
            return respond.err(404, "SegmentNotFound", name);
        // Validators, size, and bytes all come from this one freshly-opened
        // descriptor. A compaction rename between manifest lookup and open
        // can otherwise pair an old ETag with a new generation's bytes.
        var file = self.archive.dir.openFile(self.io, name, .{}) catch
            return respond.err(500, "InternalError", "failed to open segment");
        defer file.close(self.io);
        const stat = file.stat(self.io) catch
            return respond.err(500, "InternalError", "failed to stat segment");
        const header = segment.readHeaderFile(self.io, &file) catch
            return respond.err(500, "InternalError", "failed to read segment header");
        var hex_buf: [16]u8 = undefined;
        const etag = checksumHex(&hex_buf, header.checksum);
        const modified_s = stat.mtime.toSeconds();
        respond.archiveModified(modified_s);
        respond.archiveCacheMaxAge(self.segment_cache_max_age_s);
        switch (checkPreconditions(preconditions, etag, modified_s)) {
            .proceed => {},
            .not_modified => return respond.notModified(etag),
            .failed => return respond.preconditionFailed(etag),
        }

        // ServeContent-style single and multipart ranges. If-Range accepts
        // either the strong ETag or the representation's exact mtime.
        if (preconditions.range) |raw| range: {
            if (preconditions.if_range) |candidate| {
                if (!ifRangeMatches(candidate, etag, modified_s)) break :range;
            }
            const ranges = parseRanges(self.allocator, raw, stat.size) catch |err| switch (err) {
                error.OutOfMemory => return respond.err(500, "InternalError", "oom"),
                error.InvalidRange => return respond.rangeNotSatisfiable(stat.size, false),
                error.NoOverlap => return respond.rangeNotSatisfiable(stat.size, true),
            };
            defer self.allocator.free(ranges);
            if (sumRangeLengths(ranges) <= stat.size) switch (ranges.len) {
                0 => break :range,
                1 => {
                    const r = ranges[0];
                    respond.file(self.io, file, etag, r.start, r.end(), stat.size, true);
                    return;
                },
                else => {
                    var entropy: [30]u8 = undefined;
                    self.io.randomSecure(&entropy) catch
                        return respond.err(500, "InternalError", "failed to generate multipart boundary");
                    const boundary = std.fmt.bytesToHex(entropy, .lower);
                    respond.multipartFile(self.io, file, etag, &boundary, ranges, stat.size);
                    return;
                },
            };
        }

        respond.file(self.io, file, etag, 0, stat.size - 1, stat.size, false);
    }

    fn getBlock(self: *Api, respond: anytype, query: []const u8, preconditions: Preconditions) void {
        var trace = GetBlockTrace.init(self.allocator);
        defer trace.deinit();
        const name = queryParam(query, "segment") orelse {
            trace.fail(.bad_request, error.MissingSegment);
            return respond.err(400, "InvalidRequest", "missing segment");
        };
        const block_idx = blk: {
            const raw = queryParam(query, "blockIndex") orelse {
                trace.fail(.bad_request, error.MissingBlockIndex);
                return respond.err(400, "InvalidRequest", "missing blockIndex");
            };
            break :blk std.fmt.parseInt(u32, raw, 10) catch {
                trace.fail(.bad_request, error.InvalidBlockIndex);
                return respond.err(400, "InvalidRequest", "bad blockIndex");
            };
        };
        const segment_idx = archive_mod.parseSegmentIndex(name) orelse {
            trace.fail(.bad_request, error.InvalidSegmentName);
            return respond.err(400, "InvalidRequest", "bad segment name");
        };
        trace.span.setAttribute(.{ .key = "segment.idx", .value = .{ .int = @intCast(segment_idx) } });
        trace.span.setAttribute(.{ .key = "block.index", .value = .{ .int = @intCast(block_idx) } });
        const manifest_ref = self.archive.manifest.segmentByIndex(segment_idx) orelse {
            trace.fail(.not_found, error.SegmentNotFound);
            return respond.err(404, "SegmentNotFound", name);
        };

        var file = self.archive.dir.openFile(self.io, name, .{}) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "failed to open segment");
        };
        defer file.close(self.io);

        const header = segment.readHeaderFile(self.io, &file) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "failed to read segment header");
        };
        if (block_idx >= header.block_count) {
            trace.fail(.not_found, error.BlockNotFound);
            return respond.err(404, "BlockNotFound", "blockIndex out of range");
        }

        const entry = segment.readBlockIndexFile(self.io, &file, header, block_idx) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "failed to read block");
        };

        const frame = self.allocator.alloc(u8, entry.compressed_size) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "oom");
        };
        defer self.allocator.free(frame);
        var frame_len_bytes: [8]u8 = undefined;
        const frame_len_read = file.readPositionalAll(self.io, &frame_len_bytes, entry.offset) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "failed to read block");
        };
        if (frame_len_read != frame_len_bytes.len or std.mem.readInt(u64, &frame_len_bytes, .little) != entry.compressed_size) {
            trace.fail(.error_result, error.InvalidBlockFrameLength);
            return respond.err(500, "InternalError", "failed to read block");
        }
        const frame_read = file.readPositionalAll(self.io, frame, entry.offset + 8) catch |err| {
            trace.fail(.error_result, err);
            return respond.err(500, "InternalError", "failed to read block");
        };
        if (frame_read != frame.len) {
            trace.fail(.error_result, error.ShortBlockFrame);
            return respond.err(500, "InternalError", "failed to read block");
        }
        trace.span.setAttribute(.{ .key = "block.compressed_size", .value = .{ .int = @intCast(frame.len) } });
        var checksum_buf: [16]u8 = undefined;
        var etag_buf: [32]u8 = undefined;
        const etag = std.fmt.bufPrint(&etag_buf, "{s}:{d}", .{ checksumHex(&checksum_buf, header.checksum), block_idx }) catch unreachable;
        const modified_s = manifest_ref.mtime.toSeconds();
        respond.archiveModified(modified_s);
        respond.archiveCacheMaxAge(self.segment_cache_max_age_s);
        switch (checkPreconditions(preconditions, etag, modified_s)) {
            .proceed => {},
            .not_modified => {
                trace.ok();
                return respond.notModified(etag);
            },
            .failed => {
                trace.fail(.error_result, error.PreconditionFailed);
                return respond.preconditionFailed(etag);
            },
        }
        if (preconditions.range) |raw| range: {
            if (preconditions.if_range) |candidate| {
                if (!ifRangeMatches(candidate, etag, modified_s)) break :range;
            }
            const ranges = parseRanges(self.allocator, raw, frame.len) catch |err| switch (err) {
                error.OutOfMemory => {
                    trace.fail(.error_result, err);
                    return respond.err(500, "InternalError", "oom");
                },
                error.InvalidRange => {
                    trace.fail(.error_result, err);
                    return respond.rangeNotSatisfiable(frame.len, false);
                },
                error.NoOverlap => {
                    trace.fail(.error_result, err);
                    return respond.rangeNotSatisfiable(frame.len, true);
                },
            };
            defer self.allocator.free(ranges);
            if (sumRangeLengths(ranges) <= frame.len) switch (ranges.len) {
                0 => break :range,
                1 => {
                    const r = ranges[0];
                    trace.ok();
                    respond.partial(frame[@intCast(r.start)..@intCast(r.start + r.length)], etag, r.start, r.end(), frame.len);
                    return;
                },
                else => {
                    var entropy: [30]u8 = undefined;
                    self.io.randomSecure(&entropy) catch |err| {
                        trace.fail(.error_result, err);
                        return respond.err(500, "InternalError", "failed to generate multipart boundary");
                    };
                    const boundary = std.fmt.bytesToHex(entropy, .lower);
                    trace.ok();
                    respond.multipartBytes(frame, etag, &boundary, ranges);
                    return;
                },
            };
        }
        trace.ok();
        respond.raw(200, frame, etag);
    }
};

const GetBlockTrace = struct {
    span: observability.Span,
    finished: bool = false,

    fn init(allocator: Allocator) GetBlockTrace {
        return .{ .span = observability.Span.start(allocator, "xrpcapi", "getBlock", observability.root_context, &.{}) };
    }

    fn resultLabel(result: metrics.GetBlockResult) []const u8 {
        return switch (result) {
            .ok => "ok",
            .not_found => "not_found",
            .bad_request => "bad_request",
            .error_result => "error",
        };
    }

    fn setResult(self: *GetBlockTrace, result: metrics.GetBlockResult) void {
        self.span.setAttribute(.{ .key = "result", .value = .{ .string = resultLabel(result) } });
    }

    fn ok(self: *GetBlockTrace) void {
        if (self.finished) return;
        self.setResult(.ok);
        self.span.succeed();
        self.finished = true;
    }

    fn fail(self: *GetBlockTrace, result: metrics.GetBlockResult, err: anyerror) void {
        if (self.finished) return;
        self.setResult(result);
        self.span.fail(err);
        self.finished = true;
    }

    fn deinit(self: *GetBlockTrace) void {
        if (!self.finished) self.fail(.error_result, error.GetBlockIncomplete);
        self.span.deinit();
    }
};

pub fn checksumHex(buf: *[16]u8, checksum: u64) []const u8 {
    return std.fmt.bufPrint(buf, "{x:0>16}", .{checksum}) catch unreachable;
}

const ByteRange = struct {
    start: u64,
    length: u64,

    fn end(self: ByteRange) u64 {
        // Go's ServeContent preserves a zero-length suffix range as
        // `bytes=size-(size-1)/size` with an empty body.
        return if (self.length == 0) self.start - 1 else self.start + self.length - 1;
    }
};

const RangeParseError = error{ InvalidRange, NoOverlap, OutOfMemory };

const TraceCapture = struct {
    body: [64 * 1024]u8 = undefined,
    len: usize = 0,
};

const TraceCollector = struct {
    fn receive(listener: *Io.net.Server, io: Io, capture: *TraceCapture) !void {
        var stream = try listener.accept(io);
        defer stream.close(io);
        var read_buffer: [4096]u8 = undefined;
        var write_buffer: [4096]u8 = undefined;
        var reader = stream.reader(io, &read_buffer);
        var writer = stream.writer(io, &write_buffer);
        var server = std.http.Server.init(&reader.interface, &writer.interface);
        var request = try server.receiveHead();
        var body_buffer: [4096]u8 = undefined;
        const body_reader = request.readerExpectNone(&body_buffer);
        var body_writer = std.Io.Writer.fixed(&capture.body);
        _ = try body_reader.streamRemaining(&body_writer);
        capture.len = body_writer.buffered().len;
        try request.respond("", .{ .status = .ok, .keep_alive = false });
    }
};

const TraceResponder = struct {
    code: u16 = 500,
    body_len: usize = 0,

    fn err(self: *TraceResponder, code: u16, _: []const u8, _: []const u8) void {
        self.code = code;
    }
    fn archiveModified(_: *TraceResponder, _: i64) void {}
    fn archiveCacheMaxAge(_: *TraceResponder, _: u64) void {}
    fn unauthorized(self: *TraceResponder) void {
        self.code = 401;
    }
    fn notModified(self: *TraceResponder, _: []const u8) void {
        self.code = 304;
    }
    fn preconditionFailed(self: *TraceResponder, _: []const u8) void {
        self.code = 412;
    }
    fn rangeNotSatisfiable(self: *TraceResponder, _: usize, _: bool) void {
        self.code = 416;
    }
    fn partial(self: *TraceResponder, body: []const u8, _: []const u8, _: u64, _: u64, _: usize) void {
        self.code = 206;
        self.body_len = body.len;
    }
    fn multipartBytes(self: *TraceResponder, body: []const u8, _: []const u8, _: []const u8, _: []const ByteRange) void {
        self.code = 206;
        self.body_len = body.len;
    }
    fn raw(self: *TraceResponder, code: u16, body: []const u8, _: []const u8) void {
        self.code = code;
        self.body_len = body.len;
    }
};

test "getBlock exports canonical success and failure spans to a real offline collector" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var listener = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
    defer listener.deinit(io);
    var capture: TraceCapture = .{};
    var collector = try io.concurrent(TraceCollector.receive, .{ &listener, io, &capture });
    defer _ = collector.cancel(io) catch {};
    var endpoint_buffer: [128]u8 = undefined;
    const endpoint = try std.fmt.bufPrint(
        &endpoint_buffer,
        "OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:{d}",
        .{listener.socket.address.getPort()},
    );
    var runtime = try observability.Runtime.init(testing.allocator, .{
        .io = io,
        .environment = &.{ endpoint, "OTEL_BSP_SCHEDULE_DELAY=60000" },
        .service_name = "stream-getblock-contract",
        .service_version = "offline",
    });
    defer runtime.deinit();

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(io, &path_buffer);
    var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
    defer archive.deinit();
    _ = try archive.append(.{
        .seq = 0,
        .witnessed_at = 1,
        .indexed_at = 0,
        .kind = .create,
        .did = "did:plc:getblocktrace",
        .collection = "app.bsky.feed.post",
        .rkey = "3l3qo2vuowo2b",
        .rev = "3l3qo2vutsw2b",
        .payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
    }, 1);
    try archive.rotate();
    var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
    var ok_response: TraceResponder = .{};
    api.getBlock(&ok_response, "segment=seg_0000000000.jss&blockIndex=0", .{});
    try testing.expectEqual(@as(u16, 200), ok_response.code);
    try testing.expect(ok_response.body_len > 0);
    var bad_response: TraceResponder = .{};
    api.getBlock(&bad_response, "blockIndex=0", .{});
    try testing.expectEqual(@as(u16, 400), bad_response.code);

    try testing.expectEqual(@import("otel-api").common.ProcessResult.success, runtime.shutdown(2_000));
    try collector.await(io);
    const body = capture.body[0..capture.len];
    for ([_][]const u8{
        "getBlock",
        "jetstream/xrpcapi",
        "segment.idx",
        "block.index",
        "block.compressed_size",
        "result",
        "bad_request",
        "MissingSegment",
    }) |needle| try testing.expect(std.mem.indexOf(u8, body, needle) != null);
}

/// Exact shape of Go net/http's parseRange, which pinned upstream calls for
/// both getSegment and getBlock. Non-overlapping members are discarded when
/// another member overlaps; malformed syntax rejects the complete request.
fn parseRanges(allocator: Allocator, raw: []const u8, size: u64) RangeParseError![]ByteRange {
    if (!std.mem.startsWith(u8, raw, "bytes=")) return error.InvalidRange;
    var ranges: std.ArrayList(ByteRange) = .empty;
    errdefer ranges.deinit(allocator);
    var no_overlap = false;
    var specs = std.mem.splitScalar(u8, raw["bytes=".len..], ',');
    while (specs.next()) |spec_raw| {
        const spec = std.mem.trim(u8, spec_raw, " \t");
        if (spec.len == 0) continue;
        const dash = std.mem.indexOfScalar(u8, spec, '-') orelse return error.InvalidRange;
        const start_raw = std.mem.trim(u8, spec[0..dash], " \t");
        const end_raw = std.mem.trim(u8, spec[dash + 1 ..], " \t");
        if (start_raw.len == 0) {
            if (end_raw.len == 0 or end_raw[0] == '-') return error.InvalidRange;
            const suffix_signed = std.fmt.parseInt(i64, end_raw, 10) catch return error.InvalidRange;
            if (suffix_signed < 0) return error.InvalidRange;
            const suffix: u64 = @intCast(suffix_signed);
            const length = @min(suffix, size);
            try ranges.append(allocator, .{ .start = size - length, .length = length });
            continue;
        }
        const start_signed = std.fmt.parseInt(i64, start_raw, 10) catch return error.InvalidRange;
        if (start_signed < 0) return error.InvalidRange;
        const start: u64 = @intCast(start_signed);
        if (start >= size) {
            no_overlap = true;
            continue;
        }
        const length = if (end_raw.len == 0)
            size - start
        else length: {
            const requested_end_signed = std.fmt.parseInt(i64, end_raw, 10) catch return error.InvalidRange;
            if (requested_end_signed < 0) return error.InvalidRange;
            const requested_end: u64 = @intCast(requested_end_signed);
            if (requested_end < start) return error.InvalidRange;
            break :length @min(requested_end, size - 1) - start + 1;
        };
        try ranges.append(allocator, .{ .start = start, .length = length });
    }
    if (no_overlap and ranges.items.len == 0) return error.NoOverlap;
    return ranges.toOwnedSlice(allocator);
}

fn sumRangeLengths(ranges: []const ByteRange) u64 {
    var total: u64 = 0;
    for (ranges) |range| total +|= range.length;
    return total;
}

const EtagToken = struct {
    value: []const u8,
    weak: bool,
    rest: []const u8,
};

/// Exact scanner shape used by Go net/http: trim leading MIME whitespace,
/// accept W/ only with that casing, and stop the list at malformed syntax.
fn scanEtag(raw: []const u8) ?EtagToken {
    const trimmed = std.mem.trim(u8, raw, " \t\r\n");
    const weak = std.mem.startsWith(u8, trimmed, "W/");
    const start: usize = if (weak) 2 else 0;
    if (trimmed.len < start + 2 or trimmed[start] != '"') return null;
    var i = start + 1;
    while (i < trimmed.len) : (i += 1) switch (trimmed[i]) {
        0x21, 0x23...0x7e, 0x80...0xff => {},
        '"' => return .{
            .value = trimmed[start + 1 .. i],
            .weak = weak,
            .rest = trimmed[i + 1 ..],
        },
        else => return null,
    };
    return null;
}

fn ifMatchMatches(raw: []const u8, etag: []const u8) bool {
    var remaining = raw;
    while (true) {
        remaining = std.mem.trim(u8, remaining, " \t\r\n");
        if (remaining.len == 0) return false;
        if (remaining[0] == ',') {
            remaining = remaining[1..];
            continue;
        }
        if (remaining[0] == '*') return true;
        const token = scanEtag(remaining) orelse return false;
        if (!token.weak and std.mem.eql(u8, token.value, etag)) return true;
        remaining = token.rest;
    }
}

/// If-None-Match uses weak comparison, but otherwise retains Go's scanning
/// behavior: malformed syntax stops evaluation and cannot expose later tags.
fn ifNoneMatchMatches(raw: []const u8, etag: []const u8) bool {
    var remaining = raw;
    while (true) {
        remaining = std.mem.trim(u8, remaining, " \t\r\n");
        if (remaining.len == 0) return false;
        if (remaining[0] == ',') {
            remaining = remaining[1..];
            continue;
        }
        if (remaining[0] == '*') return true;
        const token = scanEtag(remaining) orelse return false;
        if (std.mem.eql(u8, token.value, etag)) return true;
        remaining = token.rest;
    }
}

const PreconditionResult = enum { proceed, not_modified, failed };

fn checkPreconditions(headers: Preconditions, etag: []const u8, modified_s: i64) PreconditionResult {
    // RFC 7232 section 6, in the same precedence order as net/http.
    const if_match = headers.if_match orelse "";
    if (if_match.len > 0) {
        if (!ifMatchMatches(if_match, etag)) return .failed;
    } else if (modified_s != 0) {
        if (headers.if_unmodified_since) |raw| {
            if (http_time.parse(raw)) |date_s| if (modified_s > date_s) return .failed;
        }
    }

    const if_none_match = headers.if_none_match orelse "";
    if (if_none_match.len > 0) {
        if (ifNoneMatchMatches(if_none_match, etag)) return .not_modified;
    } else if (modified_s != 0) {
        if (headers.if_modified_since) |raw| {
            if (http_time.parse(raw)) |date_s| if (modified_s <= date_s) return .not_modified;
        }
    }
    return .proceed;
}

fn ifRangeMatches(raw: []const u8, etag: []const u8, modified_s: i64) bool {
    if (scanEtag(raw)) |token|
        return !token.weak and std.mem.eql(u8, token.value, etag);
    if (modified_s == 0) return false;
    return if (http_time.parse(raw)) |date_s| date_s == modified_s else false;
}

test "parseRanges matches ServeContent forms" {
    const allocator = std.testing.allocator;
    const Case = struct { raw: []const u8, want: []const ByteRange };
    const cases = [_]Case{
        .{ .raw = "bytes=0-99", .want = &.{.{ .start = 0, .length = 100 }} },
        .{ .raw = "bytes=500-", .want = &.{.{ .start = 500, .length = 500 }} },
        .{ .raw = "bytes=-100", .want = &.{.{ .start = 900, .length = 100 }} },
        .{ .raw = "bytes=-0", .want = &.{.{ .start = 1000, .length = 0 }} },
        .{ .raw = "bytes=0-5000", .want = &.{.{ .start = 0, .length = 1000 }} },
        .{ .raw = "bytes=0-1, 5-9", .want = &.{ .{ .start = 0, .length = 2 }, .{ .start = 5, .length = 5 } } },
        .{ .raw = "bytes=0-1, 1000-", .want = &.{.{ .start = 0, .length = 2 }} },
        .{ .raw = "bytes=", .want = &.{} },
    };
    for (cases) |case| {
        const got = try parseRanges(allocator, case.raw, 1000);
        defer allocator.free(got);
        try std.testing.expectEqualSlices(ByteRange, case.want, got);
    }
    try std.testing.expectError(error.NoOverlap, parseRanges(allocator, "bytes=1000-", 1000));
    try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "items=0-1", 1000));
    try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "bytes=4-2", 1000));
    try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "bytes=9223372036854775808-", 1000));
}

test "strong etag matching" {
    try std.testing.expect(ifRangeMatches("\"abc:0\"", "abc:0", 123));
    try std.testing.expect(ifRangeMatches("\"abc:0\", \"other\"", "abc:0", 123));
    try std.testing.expect(!ifRangeMatches("\"other\", \"abc:0\"", "abc:0", 123));
    try std.testing.expect(!ifRangeMatches("*", "abc:0", 123));
    try std.testing.expect(!ifRangeMatches("W/\"abc:0\"", "abc:0", 123));
    try std.testing.expect(ifRangeMatches("Thu, 01 Jan 1970 00:02:03 GMT", "abc:0", 123));
}

test "If-None-Match accepts weak validators" {
    try std.testing.expect(ifNoneMatchMatches("W/\"abc:0\"", "abc:0"));
    try std.testing.expect(ifNoneMatchMatches("\"other\", W/\"abc:0\"", "abc:0"));
    try std.testing.expect(!ifNoneMatchMatches("W/\"other\"", "abc:0"));
    try std.testing.expect(!ifNoneMatchMatches("bad, W/\"abc:0\"", "abc:0"));
}

test "If-Match requires a strong matching validator" {
    try std.testing.expect(ifMatchMatches("\"other\", \"abc:0\"", "abc:0"));
    try std.testing.expect(ifMatchMatches("*", "abc:0"));
    try std.testing.expect(!ifMatchMatches("W/\"abc:0\"", "abc:0"));
    try std.testing.expect(!ifMatchMatches("bad, \"abc:0\"", "abc:0"));
}

test "ServeContent precondition precedence" {
    try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_match = "*", .if_unmodified_since = "Thu, 01 Jan 1970 00:00:00 GMT" }, "abc", 123));
    try std.testing.expectEqual(PreconditionResult.failed, checkPreconditions(.{ .if_unmodified_since = "Thu, 01 Jan 1970 00:00:00 GMT" }, "abc", 123));
    try std.testing.expectEqual(PreconditionResult.not_modified, checkPreconditions(.{ .if_none_match = "W/\"abc\"" }, "abc", 123));
    try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_none_match = "\"other\"", .if_modified_since = "Thu, 01 Jan 1970 00:10:00 GMT" }, "abc", 123));
    try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_modified_since = "Thu, 01 Jan 1970 00:10:00 GMT" }, "abc", 0));
}

fn queryParam(query: []const u8, name: []const u8) ?[]const u8 {
    var it = std.mem.splitScalar(u8, query, '&');
    while (it.next()) |pair| {
        const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
        if (std.mem.eql(u8, pair[0..eq], name)) return pair[eq + 1 ..];
    }
    return null;
}

fn authorized(configured: []const u8, header: ?[]const u8) bool {
    const raw = header orelse "";
    const prefix = "Bearer ";
    const valid_scheme = raw.len >= prefix.len and std.ascii.eqlIgnoreCase(raw[0..prefix.len], prefix);
    const presented = if (valid_scheme) raw[prefix.len..] else "";
    var expected_hash: [32]u8 = undefined;
    var presented_hash: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(configured, &expected_hash, .{});
    std.crypto.hash.sha2.Sha256.hash(presented, &presented_hash, .{});
    return configured.len > 0 and valid_scheme and
        std.crypto.timing_safe.eql([32]u8, expected_hash, presented_hash);
}

fn writeImportStatus(allocator: Allocator, respond: anytype, record: import_jobs.Record) void {
    var output: Io.Writer.Allocating = .init(allocator);
    defer output.deinit();
    var json: std.json.Stringify = .{ .writer = &output.writer };
    json.beginObject() catch return respond.err(500, "InternalError", "failed to encode response");
    json.objectField("job") catch return;
    json.write(record.id) catch return;
    json.objectField("state") catch return;
    json.write(@tagName(record.state)) catch return;
    json.objectField("phase") catch return;
    json.write(@tagName(record.phase)) catch return;
    if (record.error_message.len > 0) {
        json.objectField("error") catch return;
        json.write(record.error_message) catch return;
    }
    if (record.submitted_at_us != 0) {
        var time_buffer: [40]u8 = undefined;
        json.objectField("submittedAt") catch return;
        json.write(formatMillis(&time_buffer, record.submitted_at_us)) catch return;
    }
    if (record.finished_at_us != 0) {
        var time_buffer: [40]u8 = undefined;
        json.objectField("finishedAt") catch return;
        json.write(formatMillis(&time_buffer, record.finished_at_us)) catch return;
    }
    inline for (.{
        .{ "bucketed", record.bucketed },
        .{ "segmentsToApply", record.segments_to_apply },
        .{ "segmentsApplied", record.segments_applied },
        .{ "rowsTotal", record.rows_total },
        .{ "rowsValid", record.rows_valid },
        .{ "rowsRejected", record.rows_rejected },
        .{ "segmentsExamined", record.segments_examined },
        .{ "segmentsPatched", record.segments_patched },
        .{ "rowsMutated", record.rows_mutated },
        .{ "rowsMatchedAllVersions", record.rows_matched_all_versions },
        .{ "rowsMatchedSpecific", record.rows_matched_specific },
        .{ "specificCidsUnmatched", record.specific_cids_unmatched },
        .{ "rowsCorruptOffset", record.rows_corrupt_offset },
    }) |field| {
        json.objectField(field[0]) catch return;
        json.write(field[1]) catch return;
    }
    json.endObject() catch return respond.err(500, "InternalError", "failed to encode response");
    respond.json(200, output.written());
}

fn formatMillis(buffer: *[40]u8, micros: i64) []const u8 {
    var full_buffer: [40]u8 = undefined;
    const full = time_format.formatRfc3339(&full_buffer, micros);
    @memcpy(buffer[0..23], full[0..23]);
    buffer[23] = 'Z';
    return buffer[0..24];
}

test "timestamp import bearer auth is fixed-width and exact" {
    try std.testing.expect(authorized("secret", "Bearer secret"));
    try std.testing.expect(authorized("secret", "bearer secret"));
    try std.testing.expect(!authorized("", "Bearer "));
    try std.testing.expect(!authorized("secret", null));
    try std.testing.expect(!authorized("secret", "Basic secret"));
    try std.testing.expect(!authorized("secret", "Bearer  secret"));
    try std.testing.expect(!authorized("secret", "Bearer SECRET"));
}

test "timestamp import status uses canonical millisecond datetime" {
    var buffer: [40]u8 = undefined;
    try std.testing.expectEqualStrings("2026-07-13T00:00:01.500Z", formatMillis(
        &buffer,
        (1783900800 + 1) * std.time.us_per_s + 500_999,
    ));
}

test "checksumHex is 16 lowercase hex chars" {
    var buf: [16]u8 = undefined;
    try std.testing.expectEqualStrings("356b4de698e8df94", checksumHex(&buf, 0x356b4de698e8df94));
    try std.testing.expectEqualStrings("0000000000000001", checksumHex(&buf, 1));
}

// === planSnapshot (procedure: POST, JSON body) ===

const gloom = @import("../storage/gloom.zig");
const zstd_mod = @import("../storage/zstd.zig");

pub const PlanRequest = struct {
    dids: []const []const u8 = &.{},
    collections: []const []const u8 = &.{},
    /// kind mask, upstream's manifest.KindMask: zero means omitted/match-all,
    /// preserving the pre-kind-filter contract (v0.2.0, PR #336)
    kinds: u8 = 0,
    after_seq: u64 = 0,
    before_seq: u64 = std.math.maxInt(u64),
};

pub const kind_commit: u8 = 1;
pub const kind_identity: u8 = 2;
pub const kind_account: u8 = 4;
pub const kind_sync: u8 = 8;

fn kindsAdmit(mask: u8, kind: u8) bool {
    return mask == 0 or mask & kind != 0;
}

/// upstream manifest.sentinelKind: which public kind a DID-marker sentinel
/// collection carries (0 = a real record collection)
fn sentinelKindMask(nsid: []const u8) u8 {
    if (std.mem.eql(u8, nsid, "$account")) return kind_account;
    if (std.mem.eql(u8, nsid, "$identity")) return kind_identity;
    if (std.mem.eql(u8, nsid, "$sync")) return kind_sync;
    return 0;
}

/// Render the listSegments body. Failures propagate so the caller answers
/// 500; returning without responding would drop the request entirely.
fn renderSegments(
    summaries: []const @import("../storage/manifest.zig").Summary,
    limit: usize,
    after: ?u64,
    out: *Io.Writer.Allocating,
) !void {
    var s: std.json.Stringify = .{ .writer = &out.writer };
    try s.beginObject();
    try s.objectField("segments");
    try s.beginArray();
    var emitted: usize = 0;
    var last_idx: u64 = 0;
    var remaining = false;
    for (summaries) |meta| {
        const idx = meta.idx;
        if (after != null and idx <= after.?) continue;
        if (emitted >= limit) {
            remaining = true;
            break;
        }
        var name_buf: [64]u8 = undefined;
        const name = archive_mod.formatSegmentName(&name_buf, idx);
        try s.beginObject();
        try s.objectField("name");
        try s.write(name);
        try s.objectField("index");
        try s.write(idx);
        try s.objectField("sizeBytes");
        try s.write(meta.size);
        try s.objectField("checksum");
        var hex_buf: [16]u8 = undefined;
        try s.write(checksumHex(&hex_buf, meta.header.checksum));
        try s.objectField("eventCount");
        try s.write(meta.header.event_count);
        try s.objectField("minSeq");
        try s.write(meta.header.min_seq);
        try s.objectField("maxSeq");
        try s.write(meta.header.max_seq);
        try s.objectField("minWitnessedAt");
        try s.write(meta.header.min_witnessed_at);
        try s.objectField("maxWitnessedAt");
        try s.write(meta.header.max_witnessed_at);
        try s.objectField("blockCount");
        try s.write(meta.header.block_count);
        try s.endObject();
        emitted += 1;
        last_idx = idx;
    }
    try s.endArray();
    if (remaining) {
        try s.objectField("cursor");
        var cur_buf: [24]u8 = undefined;
        try s.write(try std.fmt.bufPrint(&cur_buf, "{d}", .{last_idx}));
    }
    try s.endObject();
}

pub fn planSnapshot(self: *Api, respond: anytype, body: []const u8, key_name: []const u8) void {
    var arena = std.heap.ArenaAllocator.init(self.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    // Exhaustion is ours, not the caller's: a 400 tells a client its valid
    // request is permanently bad and it will never retry the range.
    const req = parsePlanRequest(alloc, body, self.plan) catch |err| switch (err) {
        error.OutOfMemory => return respond.err(500, "InternalError", "oom"),
        // upstream's exact message: the request is well-formed but the
        // combination can never match anything, which the caller must learn
        error.NeverApplies => return respond.err(400, "InvalidRequest", "collections filter can never apply: kinds excludes commit"),
        else => return respond.err(400, "InvalidRequest", "malformed plan request"),
    };

    self.plan_mutex.lockUncancelable(self.io);
    var plan_locked = true;
    defer if (plan_locked) self.plan_mutex.unlock(self.io);

    const resident = self.archive.manifest.planningSegments(alloc) catch
        return respond.err(500, "InternalError", "oom");
    defer for (resident) |*item| item.deinit();

    var out: Io.Writer.Allocating = .init(alloc);
    const summary = renderPlan(self.plan, alloc, req, resident, &out) catch
        return respond.err(500, "InternalError", "oom");
    // Do not let a slow HTTP reader hold the planner lock while the
    // already-materialized JSON is written.
    plan_locked = false;
    self.plan_mutex.unlock(self.io);
    // one structured line per plan: the consumption ledger says how many
    // bytes a key moved; this says what they were (credit-system audit
    // trail). collections are query metadata in operator-private logs.
    var line_buf: [512]u8 = undefined;
    log.info("{s}", .{formatPlanLog(&line_buf, key_name, req, summary)});
    respond.json(200, out.written());
}

/// what a plan admitted — one structured log line per plan is the audit
/// trail the consumption ledger can't carry (which collections, what
/// range, how much was planned)
pub const PlanSummary = struct {
    segments: u64 = 0,
    whole_segments: u64 = 0,
    blocks: u64 = 0,
    planned_through: u64 = 0,
    sealed_tip: u64 = 0,
    truncated: bool = false,
};

/// render the per-plan audit line: who asked, for what slice, and what
/// the planner admitted. bounded: at most 4 collection NSIDs are named.
pub fn formatPlanLog(buf: []u8, key_name: []const u8, req: PlanRequest, summary: PlanSummary) []const u8 {
    var w: Io.Writer = .fixed(buf);
    w.print("plan: key={s}", .{key_name}) catch return w.buffered();
    w.print(" kinds=", .{}) catch return w.buffered();
    if (req.kinds == 0) {
        w.print("all", .{}) catch return w.buffered();
    } else {
        if (req.kinds & kind_commit != 0) w.print("c", .{}) catch return w.buffered();
        if (req.kinds & kind_identity != 0) w.print("i", .{}) catch return w.buffered();
        if (req.kinds & kind_account != 0) w.print("a", .{}) catch return w.buffered();
        if (req.kinds & kind_sync != 0) w.print("s", .{}) catch return w.buffered();
    }
    w.print(" collections=", .{}) catch return w.buffered();
    if (req.collections.len == 0) {
        w.print("all", .{}) catch return w.buffered();
    } else {
        for (req.collections[0..@min(req.collections.len, 4)], 0..) |c, i| {
            w.print("{s}{s}", .{ if (i == 0) "" else ",", c }) catch return w.buffered();
        }
        if (req.collections.len > 4) w.print(",+{d}", .{req.collections.len - 4}) catch return w.buffered();
    }
    w.print(" dids={d} afterSeq={d}", .{ req.dids.len, req.after_seq }) catch return w.buffered();
    if (req.before_seq != std.math.maxInt(u64)) w.print(" beforeSeq={d}", .{req.before_seq}) catch return w.buffered();
    w.print(" segments={d} whole={d} blocks={d} plannedThrough={d}{s}", .{
        summary.segments,                            summary.whole_segments, summary.blocks, summary.planned_through,
        if (summary.truncated) " truncated" else "",
    }) catch return w.buffered();
    return w.buffered();
}

/// Render the planSnapshot body. Every failure is propagated so the caller
/// answers 500; returning without responding would leave the request dropped.
fn renderPlan(
    plan: PlanConfig,
    alloc: Allocator,
    req: PlanRequest,
    resident: []@import("../storage/manifest.zig").PlanningSegment,
    out: *Io.Writer.Allocating,
) !PlanSummary {
    var s: std.json.Stringify = .{ .writer = &out.writer };
    var segments_json: Io.Writer.Allocating = .init(alloc);
    var sj: std.json.Stringify = .{ .writer = &segments_json.writer };
    try sj.beginArray();

    var sealed_tip: u64 = 0;
    var planned_through: u64 = 0;
    var entries: u64 = 0;
    var segs_examined: u64 = 0;
    var segs_matched: u64 = 0;
    var blocks_matched: u64 = 0;
    var truncated = false;
    var whole_count: u64 = 0;
    var last_unit_max_seq: u64 = 0;

    for (resident) |*sealed| {
        const idx = sealed.summary.idx;
        var name_buf: [64]u8 = undefined;
        const name = archive_mod.formatSegmentName(&name_buf, idx);
        const header = sealed.summary.header;
        const capped_max = @min(header.max_seq, req.before_seq);
        sealed_tip = @max(sealed_tip, capped_max);
        segs_examined += 1;
        if (sealed.blocks.len == 0 or header.event_count == 0) continue;
        if (header.max_seq <= req.after_seq) continue;
        if (header.min_seq > req.before_seq) continue;
        if (truncated) continue; // still walk for sealed_tip, plan nothing more

        const matched = try matchBlocks(alloc, sealed, req);
        var match_count: usize = 0;
        for (matched) |m| {
            if (m) match_count += 1;
        }
        if (match_count == 0) continue;

        const density = @as(f64, @floatFromInt(match_count)) / @as(f64, @floatFromInt(matched.len));
        const whole = density >= plan.whole_segment_threshold;
        var admitted = matched;
        if (whole) {
            if (plan.max_entries > 0 and entries >= plan.max_entries and entries > 0) {
                truncated = true;
                continue;
            }
            entries += 1;
            whole_count += 1;
            last_unit_max_seq = header.max_seq;
        } else {
            admitted = try alloc.alloc(bool, matched.len);
            @memset(admitted, false);
            var at: usize = 0;
            while (at < matched.len) {
                if (!matched[at]) {
                    at += 1;
                    continue;
                }
                var last = at;
                while (last + 1 < matched.len and matched[last + 1]) last += 1;
                if (plan.max_entries > 0 and entries >= plan.max_entries and entries > 0) {
                    truncated = true;
                    break;
                }
                @memset(admitted[at .. last + 1], true);
                entries += 1;
                blocks_matched += last - at + 1;
                last_unit_max_seq = sealed.blocks[last].max_seq;
                at = last + 1;
            }
            if (countRanges(admitted) == 0) continue;
        }

        try sj.beginObject();
        try sj.objectField("name");
        try sj.write(name);
        try sj.objectField("index");
        try sj.write(idx);
        try sj.objectField("checksum");
        var hex_buf: [16]u8 = undefined;
        try sj.write(checksumHex(&hex_buf, header.checksum));
        try sj.objectField("minSeq");
        try sj.write(header.min_seq);
        try sj.objectField("maxSeq");
        try sj.write(header.max_seq);
        try sj.objectField("mode");
        try sj.write(if (whole) "segment" else "blocks");
        if (!whole) {
            try sj.objectField("blocks");
            try writeBlockRanges(&sj, admitted);
        }
        try sj.endObject();
        segs_matched += 1;
        if (whole) blocks_matched += match_count;
    }
    try sj.endArray();
    planned_through = if (truncated) last_unit_max_seq else sealed_tip;

    try s.beginObject();
    try s.objectField("plannedThroughSeq");
    try s.write(planned_through);
    try s.objectField("sealedTipSeq");
    try s.write(sealed_tip);
    try s.objectField("segments");
    try s.beginWriteRaw();
    try s.writer.writeAll(segments_json.written());
    s.endWriteRaw();
    try s.objectField("stats");
    try s.beginObject();
    try s.objectField("segmentsExamined");
    try s.write(segs_examined);
    try s.objectField("segmentsMatched");
    try s.write(segs_matched);
    try s.objectField("blocksMatched");
    try s.write(blocks_matched);
    try s.objectField("entries");
    try s.write(entries);
    try s.endObject();
    try s.endObject();
    return .{
        .segments = segs_matched,
        .whole_segments = whole_count,
        .blocks = blocks_matched,
        .planned_through = planned_through,
        .sealed_tip = sealed_tip,
        .truncated = truncated,
    };
}

/// which blocks of `sealed` may contain matching rows: seq-window pruned,
/// collection-bitmask intersected, per-block DID blooms consulted (a "no"
/// skips for certain — the no-false-negative contract at work)
fn matchBlocks(alloc: Allocator, sealed: *const @import("../storage/manifest.zig").PlanningSegment, req: PlanRequest) ![]bool {
    const matched = try alloc.alloc(bool, sealed.blocks.len);
    @memset(matched, true);

    for (sealed.blocks, 0..) |info, i| {
        if (info.event_count == 0 or info.max_seq <= req.after_seq or info.min_seq > req.before_seq) matched[i] = false;
    }

    // Upstream collectionCandidatesForSegment (v0.2.0, PR #336): the
    // kinds/collections axes prune blocks together. A sentinel $-collection
    // is admitted only when its kind is (previously: always) — kinds=commit
    // now skips marker-only blocks; the marker-safe default (kinds omitted)
    // still selects them. Real collections are admitted only while commit
    // is; a collections filter that excludes commit is rejected at parse.
    // A segment with no collection index at all (sealed before the index
    // existed) fails open, as before: kind/collection pruning needs the
    // metadata to prune soundly.
    if ((req.kinds != 0 or req.collections.len > 0) and sealed.collection_index.entries.len > 0) {
        const ci = sealed.collection_index;
        const collection_match_all = req.collections.len == 0;
        const all_real = collection_match_all and kindsAdmit(req.kinds, kind_commit);
        const included = try alloc.alloc(bool, ci.entries.len);
        const real = try alloc.alloc(bool, ci.entries.len);
        var has_real = false;
        var any_included = false;
        for (ci.entries, 0..) |entry, id| {
            included[id] = false;
            const smask = sentinelKindMask(entry.nsid);
            real[id] = smask == 0;
            if (smask != 0) {
                included[id] = kindsAdmit(req.kinds, smask);
            } else if (kindsAdmit(req.kinds, kind_commit)) {
                has_real = true;
                if (!collection_match_all) {
                    for (req.collections) |c| {
                        if (std.mem.endsWith(u8, c, ".*")) {
                            if (std.mem.startsWith(u8, entry.nsid, c[0 .. c.len - 1])) included[id] = true;
                        } else if (std.mem.eql(u8, entry.nsid, c)) included[id] = true;
                    }
                }
            }
            if (included[id]) any_included = true;
        }
        // upstream candidates.empty(): nothing this segment holds can match
        const empty = !any_included and (!all_real or !has_real);
        for (matched, 0..) |*m, block| {
            if (!m.*) continue;
            if (empty) {
                m.* = false;
                continue;
            }
            if (ci.blockRow(block) == null) continue; // missing bitmask row fails open
            m.* = false;
            for (included, 0..) |inc, id| {
                const admit = inc or (all_real and real[id]);
                if (admit and ci.blockHasCollection(block, id)) {
                    m.* = true;
                    break;
                }
            }
        }
    }

    if (req.dids.len > 0) {
        var segment_may_match = !sealed.segment_bloom_valid;
        if (sealed.segment_bloom_valid) {
            for (req.dids) |did| {
                if (gloom.containsMarshaled(sealed.segment_bloom, did) catch true) {
                    segment_may_match = true;
                    break;
                }
            }
        }
        if (!segment_may_match) {
            @memset(matched, false);
            return matched;
        }
        for (matched, 0..) |*m, block| {
            if (!m.*) continue;
            const blob = sealed.blockBloom(block) orelse continue; // missing metadata fails open
            var may_match = false;
            for (req.dids) |did| {
                if (gloom.containsMarshaled(blob, did) catch true) {
                    may_match = true;
                    m.* = true;
                    break;
                }
            }
            m.* = may_match;
        }
    }
    return matched;
}

fn countRanges(matched: []const bool) u64 {
    var ranges: u64 = 0;
    var in_range = false;
    for (matched) |m| {
        if (m and !in_range) ranges += 1;
        in_range = m;
    }
    return ranges;
}

/// Write the planSnapshot blockRange lexicon exactly. These field names are
/// wire contract: upstream clients decode `first`/`last`; using different
/// names silently turns every range into block zero in permissive decoders.
fn writeBlockRanges(s: *std.json.Stringify, matched: []const bool) !void {
    try s.beginArray();
    var i: usize = 0;
    while (i < matched.len) {
        if (!matched[i]) {
            i += 1;
            continue;
        }
        var j = i;
        while (j + 1 < matched.len and matched[j + 1]) j += 1;
        try s.beginObject();
        try s.objectField("first");
        try s.write(i);
        try s.objectField("last");
        try s.write(j);
        try s.endObject();
        i = j + 1;
    }
    try s.endArray();
}

fn parsePlanRequest(alloc: Allocator, body: []const u8, config: PlanConfig) !PlanRequest {
    var req: PlanRequest = .{};
    if (body.len == 0) return req;
    const parsed = try std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{});
    if (parsed != .object) return error.Bad;
    var has_after = false;
    var has_before = false;
    if (parsed.object.get("afterSeq")) |v| {
        if (v != .integer or v.integer < 0) return error.Bad;
        req.after_seq = @intCast(v.integer);
        has_after = true;
    }
    if (parsed.object.get("beforeSeq")) |v| {
        if (v != .integer or v.integer < 0) return error.Bad;
        req.before_seq = @intCast(v.integer);
        has_before = true;
    }
    req.dids = try parseStringArray(alloc, parsed.object.get("dids"));
    req.collections = try parseStringArray(alloc, parsed.object.get("collections"));
    req.kinds = try parsePlanKinds(try parseStringArray(alloc, parsed.object.get("kinds")));
    if (has_after and has_before and req.before_seq <= req.after_seq) return error.Bad;
    try validatePlanDids(alloc, req.dids, config.max_dids);
    try validatePlanCollections(alloc, req.collections, config.max_collections);
    // upstream plansnapshot.go: a collections filter that can never apply
    // (kinds set and excluding commit) is a request error, not an empty plan
    if (req.collections.len > 0 and req.kinds != 0 and req.kinds & kind_commit == 0)
        return error.NeverApplies;
    return req;
}

/// upstream validatePlanKinds: at most 4 values (the enum's size), each one
/// of commit/identity/account/sync; empty means match-all (mask 0)
fn parsePlanKinds(values: []const []const u8) !u8 {
    if (values.len > 4) return error.Bad;
    var mask: u8 = 0;
    for (values) |v| {
        if (std.mem.eql(u8, v, "commit")) {
            mask |= kind_commit;
        } else if (std.mem.eql(u8, v, "identity")) {
            mask |= kind_identity;
        } else if (std.mem.eql(u8, v, "account")) {
            mask |= kind_account;
        } else if (std.mem.eql(u8, v, "sync")) {
            mask |= kind_sync;
        } else return error.Bad;
    }
    return mask;
}

fn validatePlanDids(alloc: Allocator, dids: []const []const u8, max_dids: usize) !void {
    var seen: std.StringHashMapUnmanaged(void) = .empty;
    for (dids) |did| {
        if (seen.contains(did)) continue;
        if (seen.count() == max_dids) return error.Bad;
        if (@import("zat").Did.parse(did) == null) return error.Bad;
        try seen.put(alloc, did, {});
    }
}

fn validatePlanCollections(alloc: Allocator, collections: []const []const u8, max_collections: usize) !void {
    var seen: std.StringHashMapUnmanaged(void) = .empty;
    for (collections) |collection| {
        if (seen.contains(collection)) continue;
        if (seen.count() == max_collections) return error.Bad;
        if (std.mem.endsWith(u8, collection, ".*")) {
            const head = collection[0 .. collection.len - 2];
            const probe = try std.fmt.allocPrint(alloc, "{s}.wildcard", .{head});
            if (@import("zat").Nsid.parse(probe) == null) return error.Bad;
        } else if (@import("zat").Nsid.parse(collection) == null) return error.Bad;
        try seen.put(alloc, collection, {});
    }
}

fn parseStringArray(alloc: Allocator, v: ?std.json.Value) ![]const []const u8 {
    const arr = v orelse return &.{};
    if (arr != .array) return error.Bad;
    var out = try alloc.alloc([]const u8, arr.array.items.len);
    for (arr.array.items, 0..) |item, i| {
        if (item != .string) return error.Bad;
        out[i] = item.string;
    }
    return out;
}

test "plan block ranges use lexicon first and last fields" {
    var out: Io.Writer.Allocating = .init(std.testing.allocator);
    defer out.deinit();
    var s: std.json.Stringify = .{ .writer = &out.writer };
    try writeBlockRanges(&s, &.{ false, true, true, false, true });
    try std.testing.expectEqualStrings(
        "[{\"first\":1,\"last\":2},{\"first\":4,\"last\":4}]",
        out.written(),
    );
}

// Upstream's planner is one-sided: degraded resident metadata must include a
// block (`blockHasAnyCollection` returns true past the slice), never prune it.
// Pruning here is a silent false negative in a collection-filtered backfill.
// `.resident` is untouched because these requests carry no DIDs.
fn planFixture(
    blocks: []const segment.BlockIndexEntry,
    ci: *const segment.CollectionIndex,
) @import("../storage/manifest.zig").PlanningSegment {
    return .{
        .resident = undefined,
        .summary = .{ .idx = 0, .size = 0, .mtime = undefined, .header = undefined },
        .blocks = blocks,
        .segment_bloom = &.{},
        .segment_bloom_valid = false,
        .collection_index = ci,
    };
}

fn oneBlock(seq: u64) segment.BlockIndexEntry {
    return .{
        .offset = 0,
        .compressed_size = 1,
        .uncompressed_size = 1,
        .event_count = 1,
        .min_seq = seq,
        .max_seq = seq,
        .min_witnessed_at = 0,
        .max_witnessed_at = 0,
    };
}

test "collection filter fails open when a block has no resident bitmask row" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2) };
    var entries = [_]segment.CollectionEntry{.{ .nsid = "app.bsky.feed.post", .count = 1 }};
    // one row of bitmasks for two blocks: block 1 has no resident row.
    var bitmasks = [_]u8{0};
    const ci: segment.CollectionIndex = .{
        .entries = &entries,
        .bitmasks = &bitmasks,
        .bitmask_len = 1,
        .buffer = &.{},
    };
    const sealed = planFixture(&blocks, &ci);

    const matched = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
    try std.testing.expect(!matched[0]); // resident row says the collection is absent
    try std.testing.expect(matched[1]); // no resident row must not prune
}

test "collection filter fails open when a segment carries no collection index" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2) };
    const ci: segment.CollectionIndex = .{
        .entries = &.{},
        .bitmasks = &.{},
        .bitmask_len = 0,
        .buffer = &.{},
    };
    const sealed = planFixture(&blocks, &ci);

    const matched = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
    for (matched) |m| try std.testing.expect(m);
}

test "exact collection reporting does not fail open" {
    var entries = [_]segment.CollectionEntry{.{ .nsid = "app.bsky.feed.post", .count = 1 }};
    var bitmasks = [_]u8{0};
    const ci: segment.CollectionIndex = .{
        .entries = &entries,
        .bitmasks = &bitmasks,
        .bitmask_len = 1,
        .buffer = &.{},
    };
    // inspect-segment reports membership as fact; a missing row is not a hit.
    try std.testing.expect(!ci.blockHasCollection(1, 0));
    try std.testing.expect(ci.blockRow(1) == null);
}

// Mirrors upstream plan_test.go's kind-mask cases (v0.2.0, PR #336): the
// kinds axis prunes blocks through the same collection index, sentinels are
// admitted per-kind instead of unconditionally, and the marker-safe default
// (kinds omitted) keeps its pre-#336 meaning.
test "plan kinds axis prunes sentinel and real blocks like upstream" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2), oneBlock(3) };
    var entries = [_]segment.CollectionEntry{
        .{ .nsid = "$account", .count = 0 },
        .{ .nsid = "$sync", .count = 0 },
        .{ .nsid = "app.bsky.feed.post", .count = 2 },
    };
    // block0: $account only; block1: post only; block2: $sync + post
    var bitmasks = [_]u8{ 0b001, 0b100, 0b110 };
    const ci: segment.CollectionIndex = .{
        .entries = &entries,
        .bitmasks = &bitmasks,
        .bitmask_len = 1,
        .buffer = &.{},
    };
    const sealed = planFixture(&blocks, &ci);

    // kinds=commit skips marker-only blocks (the new capability)
    const commits = try matchBlocks(alloc, &sealed, .{ .kinds = kind_commit });
    try std.testing.expectEqualSlices(bool, &.{ false, true, true }, commits);

    // kinds=account selects only the account-marker block
    const accounts = try matchBlocks(alloc, &sealed, .{ .kinds = kind_account });
    try std.testing.expectEqualSlices(bool, &.{ true, false, false }, accounts);

    // kinds omitted + collections: marker-safe default still admits every
    // sentinel (pre-#336 behavior preserved bit-for-bit)
    const legacy = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
    try std.testing.expectEqualSlices(bool, &.{ true, true, true }, legacy);

    // kinds=commit,account + a collections filter that matches nothing:
    // only the admitted sentinel's block survives ($sync stays excluded)
    const narrow = try matchBlocks(alloc, &sealed, .{
        .kinds = kind_commit | kind_account,
        .collections = &.{"other.example.thing"},
    });
    try std.testing.expectEqualSlices(bool, &.{ true, false, false }, narrow);
}

test "plan kinds validation mirrors upstream plansnapshot.go" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();
    const config: PlanConfig = .{};

    // collections + kinds excluding commit can never apply — request error
    try std.testing.expectError(error.NeverApplies, parsePlanRequest(alloc,
        \\{"collections":["app.bsky.feed.post"],"kinds":["account"]}
    , config));
    // unknown kind value
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc,
        \\{"kinds":["bogus"]}
    , config));
    // more values than the enum holds
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc,
        \\{"kinds":["commit","commit","commit","commit","commit"]}
    , config));
    // valid: kinds with commit alongside collections; duplicates fold
    const ok = try parsePlanRequest(alloc,
        \\{"collections":["app.bsky.feed.post"],"kinds":["commit","commit","sync"]}
    , config);
    try std.testing.expectEqual(@as(u8, kind_commit | kind_sync), ok.kinds);
}

test "matchBlocks propagates allocation failure instead of planning a false negative" {
    const blocks = [_]segment.BlockIndexEntry{oneBlock(1)};
    const ci: segment.CollectionIndex = .{
        .entries = &.{},
        .bitmasks = &.{},
        .bitmask_len = 0,
        .buffer = &.{},
    };
    const sealed = planFixture(&blocks, &ci);

    var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
    try std.testing.expectError(
        error.OutOfMemory,
        matchBlocks(failing.allocator(), &sealed, .{ .dids = &.{"did:plc:abc"} }),
    );
}

const PlanResponder = struct {
    code: u16 = 0,
    body: [8192]u8 = undefined,
    body_len: usize = 0,

    fn err(self: *PlanResponder, code: u16, _: []const u8, _: []const u8) void {
        self.code = code;
    }
    fn json(self: *PlanResponder, code: u16, body: []const u8) void {
        self.code = code;
        self.body_len = @min(body.len, self.body.len);
        @memcpy(self.body[0..self.body_len], body[0..self.body_len]);
    }
    fn written(self: *const PlanResponder) []const u8 {
        return self.body[0..self.body_len];
    }
    // full-route tests reach the dictionary/archive paths; record the code
    fn dictionary(self: *PlanResponder, _: []const u8, _: u32, _: []const u8, not_modified: bool) void {
        self.code = if (not_modified) 304 else 200;
    }
    fn archiveModified(_: *PlanResponder, _: i64) void {}
    fn archiveCacheMaxAge(_: *PlanResponder, _: u64) void {}
    fn notModified(self: *PlanResponder, _: []const u8) void {
        self.code = 304;
    }
    fn preconditionFailed(self: *PlanResponder, _: []const u8) void {
        self.code = 412;
    }
    fn rangeNotSatisfiable(self: *PlanResponder, _: usize, _: bool) void {
        self.code = 416;
    }
    fn partial(self: *PlanResponder, _: []const u8, _: []const u8, _: u64, _: u64, _: usize) void {
        self.code = 206;
    }
    fn multipartBytes(self: *PlanResponder, _: []const u8, _: []const u8, _: []const u8, _: []const ByteRange) void {
        self.code = 206;
    }
    fn raw(self: *PlanResponder, code: u16, _: []const u8, _: []const u8) void {
        self.code = code;
    }
    fn unauthorized(self: *PlanResponder) void {
        self.code = 401;
        const body = "{\"error\":\"invalid bearer credential\"}";
        self.body_len = body.len;
        @memcpy(self.body[0..body.len], body);
    }
    fn file(self: *PlanResponder, _: Io, _: Io.File, _: []const u8, _: u64, _: u64, _: u64, _: bool) void {
        self.code = 200;
    }
    fn multipartFile(self: *PlanResponder, _: Io, _: Io.File, _: []const u8, _: []const u8, _: []const ByteRange, _: u64) void {
        self.code = 206;
    }
};

// An allocation failure anywhere inside planning must never surface as a 200
// carrying a smaller plan. A client cannot distinguish that from "no matching
// data" and would skip the missing range forever. Sweeping the fail index
// keeps this honest as the allocation sequence changes.
// Mirrors the hosted Bluesky instances' edge contract (Jetstream v2,
// 2026-08-13): archive endpoints 401 without the configured bearer key;
// the live tail and the dictionary stay open. An EMPTY key leaves the
// archive open — gating a public surface is the operator's deliberate flip,
// the opposite default from the import token's secure-by-default 401.
test "archive api key gates plan/list/segment/block and nothing else" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(io, &path_buffer);
    var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
    defer archive.deinit();

    var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive, .archive_api_key = "sekrit" };

    const gated = [_]struct { m: []const u8, p: []const u8 }{
        .{ .m = "POST", .p = "/xrpc/network.bsky.jetstream.planSnapshot" },
        .{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.listSegments" },
        .{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.getSegment" },
        .{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.getBlock" },
    };
    for (gated) |g| {
        var no_auth: PlanResponder = .{};
        _ = api.handle(&no_auth, g.m, g.p, "", "{}", null, .{});
        try testing.expectEqual(@as(u16, 401), no_auth.code);
        var bad: PlanResponder = .{};
        _ = api.handle(&bad, g.m, g.p, "", "{}", "Bearer wrong", .{});
        try testing.expectEqual(@as(u16, 401), bad.code);
        // the hosted edge's exact body: bare error field, no XRPC envelope
        try testing.expectEqualStrings("{\"error\":\"invalid bearer credential\"}", bad.written());
        var good: PlanResponder = .{};
        _ = api.handle(&good, g.m, g.p, "", "{}", "Bearer sekrit", .{});
        try testing.expect(good.code != 401);
    }

    // the dictionary stays open, exactly like upstream's hosted edge
    var dict: PlanResponder = .{};
    _ = api.handle(&dict, "GET", "/xrpc/network.bsky.jetstream.getZstdDictionary", "", "", null, .{});
    try testing.expectEqual(@as(u16, 200), dict.code);

    // empty key = open archive (today's public contract, unchanged)
    var open_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
    var open: PlanResponder = .{};
    _ = open_api.handle(&open, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", null, .{});
    try testing.expect(open.code != 401);
}

test "key ring: named keys authorize, meter with 429, and revoke on reload" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(io, &path_buffer);
    var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
    defer archive.deinit();

    // a real key file: the ring reloads on mtime, so revocation below is
    // exercised the way an operator does it — by editing the file
    var key_path_buf: [Io.Dir.max_path_bytes + 32]u8 = undefined;
    const key_path = try std.fmt.bufPrint(&key_path_buf, "{s}/keys.conf", .{path_buffer[0..path_len]});
    {
        var f = try tmp.dir.createFile(io, "keys.conf", .{});
        defer f.close(io);
        try f.writeStreamingAll(io, "consumer:ring-key:1\n");
    }
    var ring = api_keys.KeyRing.init(testing.allocator, key_path);
    defer ring.deinit();

    var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive, .archive_api_key = "fleet", .key_ring = &ring };

    // ring key authorizes where the fleet key would too
    var ok: PlanResponder = .{};
    _ = api.handle(&ok, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
    try testing.expect(ok.code != 401 and ok.code != 429);

    // unknown key still 401s
    var bad: PlanResponder = .{};
    _ = api.handle(&bad, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer nope", .{});
    try testing.expectEqual(@as(u16, 401), bad.code);

    // drive the key into deficit: the next request is a 429; the fleet
    // key is unmetered and keeps working
    ring.charge(io, &ring.entries.items[0], 500_000_000, Api.nowUs(io));
    var throttled: PlanResponder = .{};
    _ = api.handle(&throttled, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
    try testing.expectEqual(@as(u16, 429), throttled.code);
    var fleet: PlanResponder = .{};
    _ = api.handle(&fleet, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer fleet", .{});
    try testing.expect(fleet.code != 429 and fleet.code != 401);

    // revocation: rewrite the file without the key; the next authorize
    // reloads (mtime changed, check throttle bypassed via last_check)
    {
        var f = try tmp.dir.createFile(io, "keys.conf", .{ .truncate = true });
        defer f.close(io);
        try f.writeStreamingAll(io, "other:different-key\n");
    }
    ring.last_check_us = std.math.minInt(i64);
    ring.loaded_mtime_us = std.math.minInt(i64);
    var revoked: PlanResponder = .{};
    _ = api.handle(&revoked, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
    try testing.expectEqual(@as(u16, 401), revoked.code);
}

test "planBackfill never answers 200 with a short plan under allocation failure" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(io, &path_buffer);
    var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
    defer archive.deinit();

    for (0..6) |i| {
        _ = try archive.append(.{
            .seq = i,
            .witnessed_at = @intCast(i + 1),
            .indexed_at = 0,
            .kind = .create,
            .did = "did:plc:planfault",
            .collection = "app.bsky.feed.post",
            .rkey = "3l3qo2vuowo2b",
            .rev = "3l3qo2vutsw2b",
            .payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
        }, 1);
        if (i == 2) try archive.rotate();
    }
    try archive.rotate();

    const request = "{\"collections\":[\"app.bsky.feed.post\"]}";

    var baseline_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
    var baseline: PlanResponder = .{};
    planSnapshot(&baseline_api, &baseline, request, "test");
    try testing.expectEqual(@as(u16, 200), baseline.code);
    try testing.expect(std.mem.indexOf(u8, baseline.written(), "\"segmentsMatched\":2") != null);

    var unanswered: usize = 0;
    for (0..256) |fail_index| {
        var failing = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = fail_index });
        var api: Api = .{ .allocator = failing.allocator(), .io = io, .archive = &archive };
        var response: PlanResponder = .{};
        planSnapshot(&api, &response, request, "test");
        if (response.code == 200) {
            try testing.expectEqualStrings(baseline.written(), response.written());
        } else if (response.code == 0) {
            unanswered += 1;
        } else {
            try testing.expect(response.code >= 500);
        }
    }
    // Encoding paths that return without responding are a separate defect;
    // this asserts the planner does not invent a truthful-looking short plan.
    try testing.expect(unanswered == 0);
}

// Same contract as planSnapshot: allocation failure must answer, and must
// never answer 200 with a truncated segment list. A client pages listSegments
// to discover the archive, so a short list silently hides sealed segments.
test "listSegments never answers 200 with a short list under allocation failure" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(io, &path_buffer);
    var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
    defer archive.deinit();

    for (0..6) |i| {
        _ = try archive.append(.{
            .seq = i,
            .witnessed_at = @intCast(i + 1),
            .indexed_at = 0,
            .kind = .create,
            .did = "did:plc:listfault",
            .collection = "app.bsky.feed.post",
            .rkey = "3l3qo2vuowo2b",
            .rev = "3l3qo2vutsw2b",
            .payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
        }, 1);
        if (i == 2) try archive.rotate();
    }
    try archive.rotate();

    var baseline_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
    var baseline: PlanResponder = .{};
    baseline_api.listSegments(&baseline, "");
    try testing.expectEqual(@as(u16, 200), baseline.code);

    var unanswered: usize = 0;
    for (0..256) |fail_index| {
        var failing = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = fail_index });
        var api: Api = .{ .allocator = failing.allocator(), .io = io, .archive = &archive };
        var response: PlanResponder = .{};
        api.listSegments(&response, "");
        if (response.code == 200) {
            try testing.expectEqualStrings(baseline.written(), response.written());
        } else if (response.code == 0) {
            unanswered += 1;
        } else {
            try testing.expect(response.code >= 500);
        }
    }
    try testing.expect(unanswered == 0);
}

test "plan request rejects invalid filters and windows" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"afterSeq\":-1}", .{}));
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"afterSeq\":10,\"beforeSeq\":10}", .{}));
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"dids\":[\"not-a-did\"]}", .{}));
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"collections\":[\"not a collection\"]}", .{}));
    _ = try parsePlanRequest(alloc, "{\"dids\":[\"did:plc:abc\"],\"collections\":[\"app.bsky.feed.*\"]}", .{});
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"dids\":[\"did:plc:a\"]}", .{ .max_dids = 0 }));
    try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"collections\":[\"app.bsky.feed.post\"]}", .{ .max_collections = 0 }));
}

test "formatPlanLog: key, kinds letters, capped collections, plan totals" {
    var buf: [512]u8 = undefined;
    const line = formatPlanLog(&buf, "evelyn", .{
        .collections = &.{ "app.bsky.graph.follow", "a.b.c", "d.e.f", "g.h.i", "j.k.l" },
        .kinds = kind_commit | kind_sync,
        .after_seq = 0,
        .dids = &.{},
    }, .{ .segments = 6000, .whole_segments = 5800, .blocks = 91000, .planned_through = 123456, .truncated = false });
    try std.testing.expectEqualStrings(
        "plan: key=evelyn kinds=cs collections=app.bsky.graph.follow,a.b.c,d.e.f,g.h.i,+1 dids=0 afterSeq=0 segments=6000 whole=5800 blocks=91000 plannedThrough=123456",
        line,
    );
    const open_line = formatPlanLog(&buf, "open", .{}, .{ .truncated = true });
    try std.testing.expectEqualStrings(
        "plan: key=open kinds=all collections=all dids=0 afterSeq=0 segments=0 whole=0 blocks=0 plannedThrough=0 truncated",
        open_line,
    );
}