1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! 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 = .{
.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.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(¬_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));
}