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

zat.dev/stream

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

0
0
700 lines · 28.0 KB Raw History
//! lifecycle — bootstrap → merging → steady_state orchestration
//!
//! upstream's Run() dispatch (docs/upstream-bootstrap-spec.md): on boot,
//! read the durable phase and fall through the states. bootstrap runs the
//! backfill engine against the real archive while a second live consumer
//! captures the firehose into backfill/live (throwaway seq space, SHARED
//! relay cursor — the steady consumer resumes where capture stopped).
//! when backfill drains, `merging` is committed, the live consumer is
//! torn down and its archive sealed, and the merge drains survivors into
//! the real archive. `steady_state` commits only after cleanup; the
//! caller gates serving on it (503 until then).
//!
//! crash matrix: bootstrap → re-run (complete repo rows skip);
//! merging → seal-guard + per-source cursor re-enter at-least-once;
//! post-cleanup-pre-phase-write → missing live dir short-circuits merge.

const std = @import("std");
const zat = @import("zat");
const archive_mod = @import("../../storage/archive.zig");
const capture_mod = @import("capture.zig");
const compact_pass = @import("../../compact/pass.zig");
const crashpoint = @import("../../runtime/crashpoint.zig");
const cursor_mod = @import("../cursor.zig");
const engine = @import("engine.zig");
const watermark_mod = @import("../../compact/watermark.zig");
const ingest = @import("../ingest.zig");
const merge = @import("merge.zig");
const metrics = @import("../../runtime/metrics.zig");
const meta_store = @import("../../storage/meta_store.zig");
const observability = @import("../../runtime/observability.zig");
const phase_mod = @import("phase.zig");
const pipeline_mod = @import("../pipeline.zig");
const repair_mod = @import("../repair.zig");
const repo_store_mod = @import("repo_store.zig");
const repos = @import("repos.zig");
const retry_mod = @import("retry.zig");
const resync = @import("resync.zig");
const tail_mod = @import("../../serve/tail.zig");
const verify = @import("../verify.zig");
const segment_io = @import("../../storage/segment_io.zig");

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

/// bootstrap live capture keeps a small scratch tail: nothing subscribes
/// to it (serving is gated), it only feeds the consumer plumbing
const capture_tail_bytes: usize = 16 * 1024 * 1024;
pub const default_async_flush_workers: usize = 4;

pub const Options = struct {
    data_dir: []const u8,
    upstream: []const u8,
    relay_http: []const u8,
    plc_url: []const u8,
    selected_repos: []const []const u8 = &.{},
    /// 0 = full crawl; >0 = upstream --max-backfill-repos debug semantics
    max_repos: usize = 0,
    workers: usize = engine.default_workers,
    batch_size: usize = engine.default_batch_size,
    /// Upstream default is four; zero explicitly keeps synchronous block
    /// compression. This applies only while the repository crawl is active.
    async_flush_workers: usize = default_async_flush_workers,
    /// Debug-only upstream control. Main also enables it automatically for
    /// max-repo and explicit-DID bootstrap selections.
    skip_merge_discovery: bool = false,
    /// Matches upstream: a zero interval disables both merge-tail and
    /// steady delete compaction. The destination is still sealed to serve.
    compaction_enabled: bool = true,
};

/// drive the lifecycle to steady_state. no-op if already there. the
/// destination archive receives backfill rows and merge survivors in the
/// real seq space; the caller starts the steady consumer after this
/// returns.
pub fn run(
    allocator: Allocator,
    io: Io,
    opts: Options,
    dst: *archive_mod.Archive,
    meta: *meta_store.Store,
    cursor_store: *cursor_mod.Store,
    verifier: ?*verify.Verifier,
    stats: *metrics.Stats,
) !void {
    return runTraced(allocator, io, opts, dst, meta, cursor_store, verifier, stats, observability.root_context);
}

pub fn runTraced(
    allocator: Allocator,
    io: Io,
    opts: Options,
    dst: *archive_mod.Archive,
    meta: *meta_store.Store,
    cursor_store: *cursor_mod.Store,
    verifier: ?*verify.Verifier,
    stats: *metrics.Stats,
    trace_context: observability.Context,
) !void {
    var phase_store = phase_mod.Store.init(meta);
    defer phase_store.deinit(io);

    var phase = (try phase_store.read(io)) orelse blk: {
        try phase_store.write(io, .bootstrap);
        break :blk phase_mod.Phase.bootstrap;
    };
    stats.setOrchestratorPhase(orchestratorPhase(phase));
    if (phase == .steady_state) return;

    // watermark floor (upstream initCompactionWatermarkFloor, when the
    // merge opens the destination writer): on first boot dst is fresh so
    // this floors W at 0; resumes no-op against the existing file
    var wm = watermark_mod.Store.init(meta);
    defer wm.deinit(io);
    _ = try wm.initFloor(io, dst.next_seq);

    var live_dir_buf: [256]u8 = undefined;
    const live_data_dir = try std.fmt.bufPrint(&live_dir_buf, "{s}/backfill/live", .{opts.data_dir});

    // `iterate=true` is required even though this handle is not iterated:
    // Zig 0.16 otherwise opens Linux directories with O_PATH, and fsync on an
    // O_PATH descriptor fails with EBADF.  Cleanup below needs a real fd so
    // removal of the backfill dirent is actually durable.
    var meta_dir = try Io.Dir.cwd().createDirPathOpen(io, opts.data_dir, .{ .open_options = .{ .iterate = true } });
    defer meta_dir.close(io);
    var repo_st = try repo_store_mod.Store.init(allocator, io, meta);
    defer repo_st.deinit();

    if (phase == .bootstrap) {
        var bootstrap_trace = observability.Span.start(
            allocator,
            "ingest/orchestrator",
            "runBootstrap",
            trace_context,
            &.{},
        );
        defer bootstrap_trace.deinit();
        defer bootstrap_trace.succeed();
        try bootstrap_trace.recordError(runBootstrap(
            allocator,
            io,
            opts,
            live_data_dir,
            dst,
            &phase_store,
            cursor_store,
            verifier,
            stats,
            &repo_st,
            bootstrap_trace.context(),
        ));
        phase = .merging;
        bootstrap_trace.succeed();
    }

    var merge_trace = observability.Span.start(
        allocator,
        "ingest/orchestrator",
        "runMerge",
        trace_context,
        &.{},
    );
    defer merge_trace.deinit();
    defer merge_trace.succeed();
    try merge_trace.recordError(runMerge(
        allocator,
        io,
        opts,
        live_data_dir,
        dst,
        meta,
        &phase_store,
        &wm,
        meta_dir,
        &repo_st,
        stats,
        &merge_trace,
    ));
}

fn runMerge(
    allocator: Allocator,
    io: Io,
    opts: Options,
    live_data_dir: []const u8,
    dst: *archive_mod.Archive,
    meta: *meta_store.Store,
    phase_store: *phase_mod.Store,
    wm: *watermark_mod.Store,
    meta_dir: Io.Dir,
    repo_st: *repo_store_mod.Store,
    stats: *metrics.Stats,
    merge_trace: *observability.Span,
) !void {
    const merge_started = Io.Timestamp.now(io, .awake);
    var merge_observed = false;
    defer if (!merge_observed) stats.observeOrchestratorState(.merge, elapsedUs(io, merge_started));

    // merging: restart-after-cleanup guard — live dir gone means a prior
    // run finished the drain and cleanup but died before the phase write
    var backfill_dir = try Io.Dir.cwd().createDirPathOpen(io, opts.data_dir, .{});
    defer backfill_dir.close(io);
    const have_live = try mergeSourceExists(io, live_data_dir);
    var bf_path_buf: [256]u8 = undefined;
    const bf_path = try std.fmt.bufPrint(&bf_path_buf, "{s}/backfill", .{opts.data_dir});
    if (have_live) {
        var bf_dir = try Io.Dir.cwd().openDir(io, bf_path, .{});
        defer bf_dir.close(io);

        const m = try merge.runTraced(allocator, io, live_data_dir, dst, repo_st, stats, merge_trace.context());
        log.info("merge: {d} kept, {d} dropped across {d} sources", .{ m.kept, m.dropped, m.sources });
        try dst.flushBlock();
        crashpoint.hit(.after_merge_drain_before_pending);

        // pending-repo pass (upstream RunPendingRepoRetryPass): repos
        // whose bootstrap download was crash-interrupted resync NOW,
        // above the merged live tail, so the first served view has their
        // current state before serving ungates
        try runPendingPass(allocator, io, opts.data_dir, opts.relay_http, dst, meta, stats, merge_trace.context());
        crashpoint.hit(.after_pending_pass);
    }

    // merge-tail compaction (upstream compactionMergeTail): seal the
    // merged tail, then compact once before the phase commit so the first
    // served view is already delete/update compliant. manifest-oblivious —
    // nothing is serving yet. idempotent, so the restart-after-cleanup
    // path re-runs it too.
    try dst.rotate();
    var compaction_trace = observability.Span.start(
        allocator,
        "ingest/orchestrator",
        "runDeleteCompaction",
        merge_trace.context(),
        &.{},
    );
    defer compaction_trace.deinit();
    defer compaction_trace.succeed();
    if (opts.compaction_enabled)
        try compaction_trace.recordError(compactMergeTail(allocator, io, opts.data_dir, wm, stats));
    compaction_trace.succeed();
    // Merge-tail rewriting is deliberately manifest-oblivious. Before
    // serving can ungate, every resident header/index must match disk.
    const reconciled = try dst.reconcileManifest();
    _ = stats.compaction_manifest_reconciled_total.fetchAdd(reconciled, .monotonic);
    crashpoint.hit(.after_merge_dst_seal_before_discovery);
    crashpoint.hit(.after_seal_before_discovery);

    if (have_live) {
        var bf_dir = try Io.Dir.cwd().openDir(io, bf_path, .{});
        defer bf_dir.close(io);

        // discovery (upstream runDiscovery): resume listRepos from the
        // bootstrap's last cursor; DIDs born during the bootstrap window
        // become failed rows the steady retry loop downloads. a relay
        // outage here fails the merge (upstream couples them the same
        // way) — re-entry is idempotent.
        if (!opts.skip_merge_discovery) {
            try runDiscovery(allocator, io, opts.relay_http, repo_st, stats, merge_trace.context());
        } else {
            log.info("merge discovery: skipped by configuration", .{});
        }
        crashpoint.hit(.after_merge_discovery_before_cleanup);
        crashpoint.hit(.after_discovery_before_cleanup);

        // cleanup: remove the backfill tree (including the discovery
        // cursor), make the removal durable before the phase write
        // (upstream fsyncs the data dir here; std.Io.Dir has no sync, so
        // fsync the directory fd directly — the Threaded backend's Dir
        // handle is a posix fd)
        meta_dir.deleteTree(io, "backfill") catch |err| {
            log.err("merge cleanup: remove backfill tree: {s}", .{@errorName(err)});
            return @errorCast(err);
        };
        crashpoint.hit(.after_cleanup_remove_before_sync);
    }
    // Always sync, including restart-after-cleanup. A prior process may have
    // removed the tree and died before this fsync; observing the cached
    // absence on this boot does not prove the dirent deletion is durable.
    segment_io.syncDir(meta_dir, io) catch |err| {
        log.err("merge cleanup: sync data directory: {s}", .{@errorName(err)});
        return @errorCast(err);
    };
    // Cleanup's dirent must be durable before these synced cursor deletes.
    // Otherwise a power cut can resurrect the source tree with cursor zero
    // and duplicate already-merged survivors on restart.
    {
        var cleanup = meta.batch();
        defer cleanup.deinit();
        cleanup.delete("merge/next_source_idx");
        cleanup.delete("bootstrap/last_listrepos_cursor");
        cleanup.commitDurable() catch |err| {
            log.err("merge cleanup: delete durable cursors: {s}", .{@errorName(err)});
            return @errorCast(err);
        };
    }
    crashpoint.hit(.after_merge_cleanup_complete);
    crashpoint.hit(.after_cleanup_before_phase_write);
    // Bootstrap-live used a temporary local sequence space. Publish the
    // merged destination's durable counters before steady_state can become
    // externally visible.
    {
        var writes = meta.batch();
        defer writes.deinit();
        const durable = dst.committed_seq.load(.acquire);
        var next_bytes: [8]u8 = undefined;
        std.mem.writeInt(u64, &next_bytes, durable + 1, .little);
        writes.put("seq/next", &next_bytes);
        var durable_bytes: [8]u8 = undefined;
        std.mem.writeInt(u64, &durable_bytes, durable, .little);
        writes.put("seq/durable", &durable_bytes);
        try writes.commitDurable();
    }
    stats.observeOrchestratorState(.merge, elapsedUs(io, merge_started));
    merge_observed = true;
    merge_trace.succeed();
    const write_started = Io.Timestamp.now(io, .awake);
    try phase_store.write(io, .steady_state);
    stats.observeOrchestratorState(.write_phase_steady, elapsedUs(io, write_started));
    stats.observeOrchestratorTransition(.merging, .steady_state);
    stats.setOrchestratorPhase(.steady_state);
    crashpoint.hit(.after_steady_phase_before_steady_run);
}

fn compactMergeTail(
    allocator: Allocator,
    io: Io,
    data_dir: []const u8,
    wm: *watermark_mod.Store,
    stats: *metrics.Stats,
) !void {
    const compaction_started = Io.Timestamp.now(io, .awake);
    var seg_path_buf: [256]u8 = undefined;
    const seg_path = try std.fmt.bufPrint(&seg_path_buf, "{s}/segments", .{data_dir});
    var seg_dir = try Io.Dir.cwd().openDir(io, seg_path, .{ .iterate = true });
    defer seg_dir.close(io);
    const cs = compact_pass.run(allocator, io, seg_dir, wm, null, .{
        .instrumentation = stats,
        .measure_pass = false,
    }) catch |err| {
        stats.observeCompactionPass(.error_result, elapsedUs(io, compaction_started));
        return @errorCast(err);
    };
    stats.observeCompactionPass(.ok, elapsedUs(io, compaction_started));
    log.info("merge-tail compaction: watermark {d}, {d} chunks, {d}/{d} segments rewritten, {d} rows dropped", .{
        cs.target_watermark, cs.chunks, cs.segments_rewritten, cs.segments_examined, cs.rows_dropped,
    });
}

/// Upstream's RunPendingRepoRetryPass: the same bounded retry runner with
/// eligibleStatus flipped to pending. Reusing it rather than hand-rolling a
/// second pass is what makes the durable bookkeeping match — worker pool,
/// per-host gate, computed backoff and 429 host parking all come with it.
/// Only infrastructure errors (archive/store I/O) abort the merge.
fn runPendingPass(
    allocator: Allocator,
    io: Io,
    data_dir: []const u8,
    relay_http: []const u8,
    dst: *archive_mod.Archive,
    meta: *meta_store.Store,
    stats: *metrics.Stats,
    trace_context: observability.Context,
) !void {
    var pending = retry_mod.Retry.init(allocator, io, dst, meta, data_dir, relay_http);
    defer pending.deinit();
    pending.eligible_status = .pending;
    pending.stats = stats;
    pending.trace_context = trace_context;
    const result = try pending.runPass();
    if (result.candidates > 0)
        log.info("pending-repo pass: {d} candidates, {d} resynced, {d} deferred to failed", .{
            result.candidates, result.succeeded, result.failed,
        });
}

/// resume listRepos from the bootstrap's last persisted cursor and mark
/// previously-unknown DIDs failed (queued for the steady retry loop).
/// no-op when no cursor was persisted (debug partial crawls).
fn runDiscovery(
    allocator: Allocator,
    io: Io,
    relay_http: []const u8,
    repo_st: *repo_store_mod.Store,
    stats: *metrics.Stats,
    trace_context: observability.Context,
) !void {
    var trace = observability.Span.start(
        allocator,
        "ingest/orchestrator",
        "runDiscovery",
        trace_context,
        &.{},
    );
    defer trace.deinit();
    defer trace.succeed();
    try trace.recordError(discover(allocator, io, relay_http, repo_st, stats));
}

fn discover(
    allocator: Allocator,
    io: Io,
    relay_http: []const u8,
    repo_st: *repo_store_mod.Store,
    stats: *metrics.Stats,
) !void {
    const start = (try engine.loadBootstrapLastListReposCursor(repo_st.meta, allocator)) orelse {
        log.info("merge discovery: no bootstrap cursor, skipping", .{});
        return;
    };
    defer allocator.free(start);

    var client = zat.XrpcClient.init(io, allocator, relay_http);
    defer client.deinit();

    var seen_arena = std.heap.ArenaAllocator.init(allocator);
    defer seen_arena.deinit();
    var seen: std.StringHashMapUnmanaged(void) = .empty;
    try seen.put(seen_arena.allocator(), try seen_arena.allocator().dupe(u8, start), {});

    var discovered: u64 = 0;
    var cursor_owned: ?[]u8 = null;
    defer if (cursor_owned) |owned| allocator.free(owned);
    var cursor: ?[]const u8 = start;
    while (true) {
        var arena = std.heap.ArenaAllocator.init(allocator);
        defer arena.deinit();
        const page = try engine.listReposPage(arena.allocator(), &client, cursor);
        for (page.repos) |ref| {
            if (try repo_st.get(allocator, ref.did)) |state| {
                repo_st.freeState(allocator, state);
                continue;
            }
            try repo_st.put(ref.did, .{
                .status = .failed,
                .active = ref.active,
                .last_error = "discovered post-bootstrap; queued for retry",
            });
            discovered += 1;
            _ = stats.orchestrator_merge_dids_discovered_post_bootstrap_total.fetchAdd(1, .monotonic);
        }
        const next = page.cursor orelse break;
        if (seen.contains(next)) return error.ListReposCursorLoop;
        try seen.put(seen_arena.allocator(), try seen_arena.allocator().dupe(u8, next), {});
        const owned = try allocator.dupe(u8, next);
        if (cursor_owned) |old| allocator.free(old);
        cursor_owned = owned;
        cursor = owned;
    }
    try repo_st.flush();
    log.info("merge discovery: {d} post-bootstrap DIDs queued for retry", .{discovered});
}

fn runBootstrap(
    allocator: Allocator,
    io: Io,
    opts: Options,
    live_data_dir: []const u8,
    dst: *archive_mod.Archive,
    phase_store: *phase_mod.Store,
    cursor_store: *cursor_mod.Store,
    verifier: ?*verify.Verifier,
    stats: *metrics.Stats,
    repo_st: *repo_store_mod.Store,
    trace_context: observability.Context,
) !void {
    var live_archive = try archive_mod.Archive.init(allocator, io, live_data_dir);
    live_archive.stats = stats;
    // Both the temporary capture archive and final merge destination apply
    // the same imported timestamp intent. The destination stamps again after
    // merge re-witnessing, so crash/re-entry remains idempotent.
    live_archive.stamper_ctx = dst.stamper_ctx;
    live_archive.stamper = dst.stamper;
    var live_sealed = false;
    defer if (!live_sealed) live_archive.deinit();

    var capture_tail = tail_mod.Tail.init(allocator, io, capture_tail_bytes);
    defer capture_tail.deinit();
    capture_tail.enableDurabilityGate(live_archive.committed_seq.load(.acquire));

    var consumer: ingest.Consumer = .{
        .delivery = .direct,
        .allocator = allocator,
        .io = io,
        .tail = &capture_tail,
        .upstream = opts.upstream,
        .verifier = verifier,
        .cursor_store = cursor_store,
        .archive = &live_archive,
        .stats = stats,
        .write_archive_sequence_metadata = false,
    };
    defer consumer.deinit();
    live_archive.on_durable_ctx = &consumer;
    live_archive.on_durable = ingest.Consumer.onArchiveDurable;
    var pipe: pipeline_mod.Pipeline = .{
        .allocator = allocator,
        .io = io,
        .verifier = verifier,
        .stats = stats,
        .emit_ctx = &consumer,
        .emit = ingest.Consumer.emitVerified,
        .emit_repair = ingest.Consumer.emitRepair,
        .emit_cursor = ingest.Consumer.emitCursor,
        .cursor_watermark = (try cursor_store.load(io)) orelse 0,
        .trace_context = trace_context,
    };
    var repair_scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const repair_scratch = try std.fmt.bufPrint(&repair_scratch_buf, "{s}/repair-scratch", .{live_data_dir});
    var repair_coordinator: ?repair_mod.Coordinator = if (verifier) |v| .{
        .allocator = allocator,
        .io = io,
        .verifier = v,
        .relay_http = opts.relay_http,
        .scratch_dir = repair_scratch,
        .stats = stats,
        .publish_ctx = &pipe,
        .publish = pipeline_mod.Pipeline.publishRepair,
    } else null;
    if (repair_coordinator) |*coordinator| {
        try coordinator.start();
        pipe.repair = coordinator;
    }
    defer if (repair_coordinator) |*coordinator| coordinator.deinit();
    try pipe.start();
    defer pipe.stop();
    consumer.delivery = .{ .pipeline = &pipe };

    var capture: capture_mod.Capture = .{
        .allocator = allocator,
        .io = io,
        .upstream = opts.upstream,
        .consumer = &consumer,
        .last_seq = try cursor_store.load(io),
    };
    const BootstrapRace = Io.Select(union(enum) {
        capture: void,
        backfill: anyerror!engine.Stats,
    });
    var race_results: [2]BootstrapRace.Union = undefined;
    var race = BootstrapRace.init(io, &race_results);
    try race.concurrent(.capture, capture_mod.Capture.run, .{&capture});
    defer {
        capture.requestStop();
        race.cancelDiscard();
    }
    log.info("bootstrap: live capture -> {s}", .{live_data_dir});
    try capture.waitConnected();
    log.info("bootstrap: live capture connected; starting repository backfill", .{});

    try dst.enableAsyncFlush(opts.async_flush_workers);
    if (opts.async_flush_workers > 0)
        log.info("backfill: async block compression on ({d} workers)", .{opts.async_flush_workers})
    else
        log.info("backfill: async block compression off", .{});
    var async_flush_enabled = opts.async_flush_workers > 0;
    defer if (async_flush_enabled) dst.disableAsyncFlush();
    try race.concurrent(.backfill, engine.runTraced, .{ allocator, io, .{
        .relay_http = opts.relay_http,
        .plc_url = opts.plc_url,
        .data_dir = opts.data_dir,
        .selected_repos = opts.selected_repos,
        .max_repos = opts.max_repos,
        .workers = opts.workers,
        .batch_size = opts.batch_size,
        .metrics = stats,
    }, dst, repo_st, trace_context });
    const bf = switch (try race.await()) {
        .capture => {
            race.cancelDiscard();
            return capture.unexpectedFailure() orelse error.LiveCaptureEnded;
        },
        .backfill => |result| blk: {
            const finished = try result;
            // Upstream's first commit point: backfill has drained, but the
            // bootstrap-live consumer is still running. Persist merging
            // before asking that consumer to stop so a crash cannot restart
            // the expensive whole-network crawl after successful completion.
            crashpoint.hit(.after_backfill_before_phase_merging);
            const write_started = Io.Timestamp.now(io, .awake);
            // Upstream's BackfillTiming spans entering bootstrap to committing
            // merging. The bootstrap entry stamp is only written on the
            // transition, so it survives restarts and the span correctly
            // includes any downtime rather than restarting at the last boot.
            const backfill_started_us = phase_store.readEnteredAt(io) catch null;
            try phase_store.writeAtWithBackfillTiming(
                io,
                .merging,
                Io.Timestamp.now(io, .real).toMicroseconds(),
                .{
                    .started_at_us = backfill_started_us,
                    .completed_at_us = Io.Timestamp.now(io, .real).toMicroseconds(),
                },
            );
            stats.observeOrchestratorState(.write_phase_merging, elapsedUs(io, write_started));
            stats.observeOrchestratorTransition(.bootstrap, .merging);
            stats.setOrchestratorPhase(.merging);
            crashpoint.hit(.after_phase_merging_before_live_stop);
            // Stop and join capture before beginning archive cutover. No
            // callback can race the live pipeline drain below this boundary.
            capture.requestStop();
            race.cancelDiscard();
            break :blk finished;
        },
    };
    dst.disableAsyncFlush();
    async_flush_enabled = false;
    log.info("backfill: {d} repos complete, {d} failed, {d} rows ({d} dropped)", .{
        bf.completed,
        bf.failed,
        bf.rows,
        bf.drops.invalid_collection + bf.drops.invalid_rkey + bf.drops.field_too_long,
    });

    // teardown order: stop the capture consumer (cooperative flag; the
    // cancel unblocks an idle read), then seal its archive so the merge
    // reads a fully-sealed source tree (the merge's seal guard covers a
    // crash landing between these two steps)
    var finish_trace = observability.Span.start(
        allocator,
        "ingest/orchestrator",
        "finishBootstrap",
        trace_context,
        &.{},
    );
    defer finish_trace.deinit();
    defer finish_trace.succeed();
    try finish_trace.recordError(finishBootstrap(io, stats, &pipe, &live_archive));
    live_sealed = true;
}

fn finishBootstrap(
    io: Io,
    stats: *metrics.Stats,
    pipe: *pipeline_mod.Pipeline,
    live_archive: *archive_mod.Archive,
) !void {
    const drain_started = Io.Timestamp.now(io, .awake);
    stats.observeOrchestratorState(.drain_bootstrap, elapsedUs(io, drain_started));
    // cancel joins the websocket reader, so no new submissions can race this
    // boundary. Drain every frame it already handed to the pipeline before
    // closing the archive those callbacks write to.
    const seal_started = Io.Timestamp.now(io, .awake);
    try pipe.drainAndStop();
    // Closing the live writer makes its final partial block durable before
    // the distinct seal step. A crash at the canonical close-before-seal seam
    // must recover every captured intermediate, not merely final repo state.
    try live_archive.flushBlock();
    crashpoint.hit(.after_bootstrap_live_close_before_seal);
    crashpoint.hit(.after_live_close_before_seal);
    live_archive.sealAndClose() catch |err| {
        log.warn("bootstrap: live archive seal failed: {s}", .{@errorName(err)});
        return @errorCast(err);
    };
    stats.observeOrchestratorState(.seal_bootstrap, elapsedUs(io, seal_started));
}

fn orchestratorPhase(phase: phase_mod.Phase) metrics.OrchestratorPhase {
    return switch (phase) {
        .bootstrap => .bootstrap,
        .merging => .merging,
        .steady_state => .steady_state,
    };
}

fn elapsedUs(io: Io, started_at: Io.Timestamp) u64 {
    return @intCast(@max(started_at.durationTo(Io.Timestamp.now(io, .awake)).toMicroseconds(), 0));
}

fn mergeSourceExists(io: Io, path: []const u8) !bool {
    var dir = Io.Dir.cwd().openDir(io, path, .{}) catch |err| switch (err) {
        error.FileNotFound => return false,
        else => return err,
    };
    dir.close(io);
    return true;
}

test "merge restart guard distinguishes missing source from filesystem failure" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var root_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const root_len = try tmp.dir.realPath(testing.io, &root_buf);
    const root = root_buf[0..root_len];
    var missing_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const missing = try std.fmt.bufPrint(&missing_buf, "{s}/missing", .{root});
    try testing.expect(!try mergeSourceExists(testing.io, missing));

    var present_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const present = try std.fmt.bufPrint(&present_buf, "{s}/present", .{root});
    var present_dir = try Io.Dir.cwd().createDirPathOpen(testing.io, present, .{});
    present_dir.close(testing.io);
    try testing.expect(try mergeSourceExists(testing.io, present));

    var not_dir_buf: [Io.Dir.max_path_bytes]u8 = undefined;
    const not_dir = try std.fmt.bufPrint(&not_dir_buf, "{s}/not-a-directory", .{root});
    var file = try Io.Dir.cwd().createFile(testing.io, not_dir, .{});
    file.close(testing.io);
    try testing.expectError(error.NotDir, mergeSourceExists(testing.io, not_dir));
}