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
//! 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),
);
}