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

zat.dev/stream

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

0
0
488 lines · 20.0 KB Raw History
//! merge — drain bootstrap-captured live segments into the real archive
//!
//! upstream's State 5 (docs/upstream-bootstrap-spec.md): walk
//! backfill/live/segments in index order, apply the keep/drop predicate
//! per row, re-stamp witnessed_at, append survivors to the destination
//! archive (which re-assigns real seqs — the source seq space is
//! throwaway), and advance a durable per-source cursor AFTER the dst
//! flush so a crash re-drains at-least-once, never skips.
//!
//! keep/drop (upstream merge_filter.go): drop iff the row is
//! commit-shaped or sync (the kinds that carry a repo rev), the DID's
//! backfill is complete, both revs are non-empty, and row.rev <=
//! Backfill.Rev (TIDs sort lexicographically). identity/account rows
//! always survive. Each source commit atomically advances the merge cursor and
//! refreshes top-level latest Rev/UpdatedAt while preserving Backfill.Rev.

const std = @import("std");
const archive_mod = @import("../../storage/archive.zig");
const crashpoint = @import("../../runtime/crashpoint.zig");
const metrics = @import("../../runtime/metrics.zig");
const observability = @import("../../runtime/observability.zig");
const repo_store = @import("repo_store.zig");
const segment = @import("../../storage/segment.zig");

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

pub const Stats = struct {
    kept: u64 = 0,
    dropped: u64 = 0,
    sources: u64 = 0,
};

/// One RocksDB repo-row lookup per DID for the entire merge run, including
/// cached misses. Backfill.Rev is immutable during merge, so cached states
/// remain the authoritative filter watermark while source commits refresh
/// only the separate latest-revision fields.
const RepoStatusCache = struct {
    arena: std.heap.ArenaAllocator,
    states: std.StringHashMapUnmanaged(?repo_store.RepoState) = .empty,
    store: *repo_store.Store,
    stats: *metrics.Stats,

    fn init(allocator: Allocator, store: *repo_store.Store, stats: *metrics.Stats) RepoStatusCache {
        return .{ .arena = .init(allocator), .store = store, .stats = stats };
    }

    fn deinit(self: *RepoStatusCache) void {
        self.arena.deinit();
    }

    fn get(self: *RepoStatusCache, did: []const u8) !?repo_store.RepoState {
        if (self.states.get(did)) |state| return state;
        const allocator = self.arena.allocator();
        const owned_did = try allocator.dupe(u8, did);
        const state = try self.store.get(allocator, did);
        try self.states.put(allocator, owned_did, state);
        _ = self.stats.orchestrator_merge_did_lookups_total.fetchAdd(1, .monotonic);
        return state;
    }
};

/// true unless the row is superseded by the backfill watermark
pub fn shouldKeep(ev: segment.Event, state: ?repo_store.RepoState) bool {
    switch (ev.kind) {
        .create, .update, .delete, .create_resync, .sync => {},
        .identity, .account => return true,
    }
    const st = state orelse return true;
    if (st.status != .complete) return true;
    if (st.rev.len == 0 or ev.rev.len == 0) return true;
    return std.mem.order(u8, ev.rev, st.rev) == .gt;
}

/// drain every sealed source segment with index >= the persisted cursor
/// into `dst`.
pub fn run(
    allocator: Allocator,
    io: Io,
    live_data_dir: []const u8,
    dst: *archive_mod.Archive,
    store: *repo_store.Store,
    metric_stats: *metrics.Stats,
) !Stats {
    return runTraced(allocator, io, live_data_dir, dst, store, metric_stats, observability.root_context);
}

pub fn runTraced(
    allocator: Allocator,
    io: Io,
    live_data_dir: []const u8,
    dst: *archive_mod.Archive,
    store: *repo_store.Store,
    metric_stats: *metrics.Stats,
    trace_context: observability.Context,
) !Stats {
    var trace = observability.Span.start(allocator, "ingest/orchestrator", "run", trace_context, &.{});
    defer trace.deinit();
    defer trace.succeed();
    return trace.recordError(mergeSources(allocator, io, live_data_dir, dst, store, metric_stats, trace.context()));
}

fn mergeSources(
    allocator: Allocator,
    io: Io,
    live_data_dir: []const u8,
    dst: *archive_mod.Archive,
    store: *repo_store.Store,
    metric_stats: *metrics.Stats,
    trace_context: observability.Context,
) !Stats {
    // seal guard: a crash between live-consumer teardown and seal leaves
    // an active trailing source. Archive recovery seals torn actives;
    // sealAndClose then deletes the fresh empty one it opened.
    {
        var src = try archive_mod.Archive.init(allocator, io, live_data_dir);
        try src.sealAndClose();
    }

    var seg_path_buf: [256]u8 = undefined;
    const seg_path = try std.fmt.bufPrint(&seg_path_buf, "{s}/segments", .{live_data_dir});
    var src_dir = try Io.Dir.cwd().openDir(io, seg_path, .{ .iterate = true });
    defer src_dir.close(io);

    var indices: std.ArrayList(u64) = .empty;
    defer indices.deinit(allocator);
    var it = src_dir.iterate();
    while (try it.next(io)) |entry| {
        const idx = archive_mod.parseSegmentIndex(entry.name) orelse continue;
        try indices.append(allocator, idx);
    }
    std.mem.sort(u64, indices.items, {}, std.sort.asc(u64));

    const from_idx = try loadCursor(store);
    var stats: Stats = .{};
    var cache = RepoStatusCache.init(allocator, store, metric_stats);
    defer cache.deinit();
    var expect = from_idx;
    for (indices.items) |idx| {
        if (idx < from_idx) continue;
        if (idx != expect) return error.SourceIndexGap;
        expect += 1;

        var source_arena = std.heap.ArenaAllocator.init(allocator);
        defer source_arena.deinit();
        var source_trace = observability.Span.start(
            allocator,
            "ingest/orchestrator",
            "processSourceSegment",
            trace_context,
            &.{},
        );
        defer source_trace.deinit();
        defer source_trace.succeed();
        try source_trace.recordError(mergeSource(
            source_arena.allocator(),
            io,
            src_dir,
            idx,
            dst,
            store,
            &cache,
            &stats,
            metric_stats,
            &source_trace,
        ));
    }
    return stats;
}

fn mergeSource(
    arena: Allocator,
    io: Io,
    src_dir: Io.Dir,
    idx: u64,
    dst: *archive_mod.Archive,
    store: *repo_store.Store,
    cache: *RepoStatusCache,
    stats: *Stats,
    metric_stats: *metrics.Stats,
    source_trace: *observability.Span,
) !void {
    const revs = try drainOne(
        arena,
        io,
        src_dir,
        idx,
        dst,
        cache,
        stats,
        metric_stats,
        source_trace.context(),
    );
    // durability ordering: dst rows fsynced before the cursor advances
    try dst.flushBlockTraced(source_trace.context());
    source_trace.succeed();
    crashpoint.hit(.after_merge_dst_flush_before_source_commit);
    const updates = try arena.alloc(repo_store.RevUpdate, revs.count());
    var update_it = revs.iterator();
    var update_index: usize = 0;
    while (update_it.next()) |entry| : (update_index += 1)
        updates[update_index] = .{ .did = entry.key_ptr.*, .rev = entry.value_ptr.* };
    try store.commitMergeSource(cursor_key, idx + 1, updates, Io.Timestamp.now(io, .real).toMicroseconds());
    stats.sources += 1;
    _ = metric_stats.orchestrator_merge_segments_consumed_total.fetchAdd(1, .monotonic);
    _ = metric_stats.orchestrator_merge_repo_revs_updated_total.fetchAdd(updates.len, .monotonic);
}

fn drainOne(
    allocator: Allocator,
    io: Io,
    src_dir: Io.Dir,
    idx: u64,
    dst: *archive_mod.Archive,
    cache: *RepoStatusCache,
    stats: *Stats,
    metric_stats: *metrics.Stats,
    trace_context: observability.Context,
) !std.StringHashMapUnmanaged([]const u8) {
    var name_buf: [64]u8 = undefined;
    const name = archive_mod.formatSegmentName(&name_buf, idx);
    const bytes = try src_dir.readFileAlloc(io, name, allocator, .limited(1 << 31));
    defer allocator.free(bytes);
    var sealed = try segment.Sealed.parse(allocator, bytes);
    defer sealed.deinit(allocator);
    var per_did: std.StringHashMapUnmanaged([]const u8) = .empty;

    const now_us: i64 = Io.Timestamp.now(io, .real).toMicroseconds();
    for (0..sealed.block_index.len) |i| {
        var block = try sealed.readBlock(allocator, i);
        defer block.deinit(allocator);
        for (block.events) |ev| {
            const state = try cache.get(ev.did);
            if (!shouldKeep(ev, state)) {
                stats.dropped += 1;
                _ = metric_stats.orchestrator_merge_events_dropped_total.fetchAdd(1, .monotonic);
                continue;
            }
            var stamped = ev;
            stamped.witnessed_at = now_us; // upstream §3.4 re-stamp
            _ = try dst.appendTraced(stamped, now_us, trace_context);
            stats.kept += 1;
            _ = metric_stats.orchestrator_merge_events_kept_total.fetchAdd(1, .monotonic);
            switch (ev.kind) {
                .create, .update, .delete, .create_resync, .sync => if (ev.rev.len > 0) {
                    const result = try per_did.getOrPut(allocator, ev.did);
                    if (!result.found_existing) result.key_ptr.* = try allocator.dupe(u8, ev.did);
                    result.value_ptr.* = try allocator.dupe(u8, ev.rev);
                },
                .identity, .account => {},
            }
        }
    }
    return per_did;
}

const cursor_key = "merge/next_source_idx";
const cursor_version: u8 = 1;

fn loadCursor(store: *repo_store.Store) !u64 {
    const maybe_bytes = try store.meta.getAlloc(store.allocator, cursor_key);
    const bytes = maybe_bytes orelse return 0;
    defer store.allocator.free(bytes);
    if (bytes.len != 9) return error.InvalidMergeCursorLength;
    if (bytes[0] != cursor_version) return error.UnsupportedMergeCursorVersion;
    return std.mem.readInt(u64, bytes[1..9], .little);
}

// === tests ===

const testing = std.testing;

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

test "shouldKeep mirrors upstream merge_filter" {
    const complete: repo_store.RepoState = .{ .status = .complete, .rev = "3l3qo2vutsw2b" };
    // unknown DID → keep
    try testing.expect(shouldKeep(row(.create, "did:plc:x", "3l3qo2vutsw2a"), null));
    // incomplete → keep
    try testing.expect(shouldKeep(row(.create, "did:plc:x", "3l3qo2vutsw2a"), .{ .status = .pending, .rev = "3l3qo2vutsw2b" }));
    // complete, rev <= watermark → drop (commit kinds and sync)
    try testing.expect(!shouldKeep(row(.create, "did:plc:x", "3l3qo2vutsw2a"), complete));
    try testing.expect(!shouldKeep(row(.delete, "did:plc:x", "3l3qo2vutsw2b"), complete));
    try testing.expect(!shouldKeep(row(.sync, "did:plc:x", "3l3qo2vutsw2b"), complete));
    // complete, rev above watermark → keep
    try testing.expect(shouldKeep(row(.update, "did:plc:x", "3l3qo2vutsw2c"), complete));
    // identity/account always survive
    try testing.expect(shouldKeep(row(.identity, "did:plc:x", ""), complete));
    try testing.expect(shouldKeep(row(.account, "did:plc:x", ""), complete));
    // empty revs on either side → keep
    try testing.expect(shouldKeep(row(.create, "did:plc:x", ""), complete));
    try testing.expect(shouldKeep(row(.create, "did:plc:x", "3l3qo2vutsw2a"), .{ .status = .complete, .rev = "" }));
}

test "merge cursor corruption and storage errors fail closed" {
    const meta_store = @import("../../storage/meta_store.zig");
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);
    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try repo_store.Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();

    try testing.expectEqual(@as(u64, 0), try loadCursor(&store));
    try meta.putDurable(cursor_key, &.{ 1, 2, 3 });
    try testing.expectError(error.InvalidMergeCursorLength, loadCursor(&store));
    try meta.putDurable(cursor_key, &.{ 2, 0, 0, 0, 0, 0, 0, 0, 0 });
    try testing.expectError(error.UnsupportedMergeCursorVersion, loadCursor(&store));
    try testing.expect(meta_store.armReadFault(cursor_key, 1));
    defer meta_store.disarmReadFault();
    try testing.expectError(error.InjectedStoreFault, loadCursor(&store));
}

test "legacy bare merge cursor is migrated before strict decoding" {
    const meta_store = @import("../../storage/meta_store.zig");
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);
    const path = path_buf[0..path_len];
    var meta = try meta_store.Store.open(testing.allocator, path);
    defer meta.deinit();
    var legacy: [8]u8 = undefined;
    std.mem.writeInt(u64, &legacy, 73, .little);
    try meta.putDurable(cursor_key, &legacy);
    try meta.migrateLegacy(testing.io, path);
    var store = try repo_store.Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();
    try testing.expectEqual(@as(u64, 73), try loadCursor(&store));
}

test "merge repo status cache performs one real RocksDB lookup per DID including misses" {
    const meta_store = @import("../../storage/meta_store.zig");
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const path_len = try tmp.dir.realPath(testing.io, &path_buf);
    var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
    defer meta.deinit();
    var store = try repo_store.Store.init(testing.allocator, testing.io, &meta);
    defer store.deinit();
    try store.put("did:plc:known", .{ .status = .complete, .rev = "3lknown" });

    var metric_stats: metrics.Stats = .{};
    var cache = RepoStatusCache.init(testing.allocator, &store, &metric_stats);
    defer cache.deinit();
    try testing.expectEqualStrings("3lknown", (try cache.get("did:plc:known")).?.rev);
    try testing.expectEqualStrings("3lknown", (try cache.get("did:plc:known")).?.rev);
    try testing.expectEqual(null, try cache.get("did:plc:missing"));
    try testing.expectEqual(null, try cache.get("did:plc:missing"));
    try testing.expectEqual(2, metric_stats.orchestrator_merge_did_lookups_total.load(.monotonic));
}

test "real merge records canonical counters at durable source boundaries" {
    const meta_store = @import("../../storage/meta_store.zig");
    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 root = root_buf[0..root_len];
    var live_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const live_root = try std.fmt.bufPrint(&live_buf, "{s}/live", .{root});
    var dst_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const dst_root = try std.fmt.bufPrint(&dst_buf, "{s}/dst", .{root});

    var meta = try meta_store.Store.open(testing.allocator, root);
    defer meta.deinit();
    var store = try repo_store.Store.init(testing.allocator, io, &meta);
    defer store.deinit();
    try store.put("did:plc:known", .{ .status = .complete, .rev = "3lmiddle" });

    var source = try archive_mod.Archive.init(testing.allocator, io, live_root);
    _ = try source.append(row(.create, "did:plc:known", "3la"), 1);
    _ = try source.append(row(.update, "did:plc:known", "3lz"), 2);
    _ = try source.append(row(.identity, "did:plc:known", ""), 3);
    _ = try source.append(row(.create, "did:plc:unknown", "3lx"), 4);
    try source.sealAndClose();

    var dst = try archive_mod.Archive.init(testing.allocator, io, dst_root);
    defer {
        dst.close();
        dst.deinit();
    }
    var metric_stats: metrics.Stats = .{};
    const result = try run(testing.allocator, io, live_root, &dst, &store, &metric_stats);
    try testing.expectEqual(@as(u64, 3), result.kept);
    try testing.expectEqual(@as(u64, 1), result.dropped);
    try testing.expectEqual(@as(u64, 1), result.sources);
    try testing.expectEqual(3, metric_stats.orchestrator_merge_events_kept_total.load(.monotonic));
    try testing.expectEqual(1, metric_stats.orchestrator_merge_events_dropped_total.load(.monotonic));
    try testing.expectEqual(1, metric_stats.orchestrator_merge_segments_consumed_total.load(.monotonic));
    try testing.expectEqual(2, metric_stats.orchestrator_merge_did_lookups_total.load(.monotonic));
    try testing.expectEqual(2, metric_stats.orchestrator_merge_repo_revs_updated_total.load(.monotonic));

    const updated = (try store.get(testing.allocator, "did:plc:known")).?;
    defer store.freeState(testing.allocator, updated);
    try testing.expectEqualStrings("3lz", updated.latest_rev);
    try testing.expectEqualStrings("3lmiddle", updated.rev);
    try testing.expectEqual(null, try store.get(testing.allocator, "did:plc:unknown"));
}

// A merge source missing from the middle of the sequence is a hole, not an
// empty range: its events were captured and never drained. Skipping it would
// advance the source cursor past rows that never reached the destination, and
// no later pass revisits them. Upstream enumerates sources contiguously for
// the same reason. This is the merge-side twin of the cold-replay hole.
test "merge refuses a gap in the source segment sequence" {
    const meta_store = @import("../../storage/meta_store.zig");
    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 root = root_buf[0..root_len];
    var live_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const live_root = try std.fmt.bufPrint(&live_buf, "{s}/live", .{root});
    var dst_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const dst_root = try std.fmt.bufPrint(&dst_buf, "{s}/dst", .{root});

    var meta = try meta_store.Store.open(testing.allocator, root);
    defer meta.deinit();
    var store = try repo_store.Store.init(testing.allocator, io, &meta);
    defer store.deinit();
    try store.put("did:plc:known", .{ .status = .complete, .rev = "3la" });

    // Three sealed sources, then delete the middle one.
    var source = try archive_mod.Archive.init(testing.allocator, io, live_root);
    source.max_segment_bytes = 1;
    for (0..3) |i| {
        _ = try source.append(row(.create, "did:plc:known", "3lz"), @intCast(i + 1));
        try source.rotate();
    }
    source.close();
    source.deinit();

    var seg_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const seg_dir_path = try std.fmt.bufPrint(&seg_buf, "{s}/segments", .{live_root});
    var seg_dir = try Io.Dir.cwd().openDir(io, seg_dir_path, .{ .iterate = true });
    defer seg_dir.close(io);
    var names: std.ArrayList([]u8) = .empty;
    defer {
        for (names.items) |n| testing.allocator.free(n);
        names.deinit(testing.allocator);
    }
    var it = seg_dir.iterate();
    while (try it.next(io)) |entry| {
        if (archive_mod.parseSegmentIndex(entry.name) == null) continue;
        try names.append(testing.allocator, try testing.allocator.dupe(u8, entry.name));
    }
    try testing.expect(names.items.len >= 3);
    std.mem.sort([]u8, names.items, {}, struct {
        fn lessThan(_: void, a: []u8, b: []u8) bool {
            return std.mem.order(u8, a, b) == .lt;
        }
    }.lessThan);
    try seg_dir.deleteFile(io, names.items[1]);

    var dst = try archive_mod.Archive.init(testing.allocator, io, dst_root);
    defer {
        dst.close();
        dst.deinit();
    }
    var metric_stats: metrics.Stats = .{};
    try testing.expectError(
        error.SourceIndexGap,
        run(testing.allocator, io, live_root, &dst, &store, &metric_stats),
    );
}