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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! Authenticated asynchronous whole-repo repair for live Sync 1.1 ingest.
//!
//! This is the Atmos/Jetstream V2 state machine, expressed in Stream's
//! ordered pipeline: 32 fetch workers, a 64-job bounded queue, five repairs
//! per DID per minute (burst five), 2,048 pending commits per DID, unlocked
//! five-minute getRepo fetches, stale-head rejection, authenticated apply,
//! and ordered replay before the per-DID lane is released.
const std = @import("std");
const zat = @import("zat");
const fetched_car = @import("backfill/fetched_car.zig");
const prepared_fetch = @import("backfill/prepared_fetch.zig");
const verify = @import("verify.zig");
const metrics = @import("../runtime/metrics.zig");
const lru = @import("../storage/lru.zig");
const meta_store = @import("../storage/meta_store.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.stream);
pub const worker_count = 32;
pub const queue_capacity = worker_count * 2;
pub const pending_capacity = 2048;
const lane_count = 4096;
const limiter_capacity = 16_384;
const refill_us = 12 * std.time.us_per_s; // five tokens per minute
const Bucket = struct { tokens: u8 = 5, last_us: i64 };
pub const PendingVerified = struct {
arena: *std.heap.ArenaAllocator,
event: zat.FirehoseEvent,
verdict: verify.Result,
};
/// Ownership handed to the single archive writer. The fetched mmap and parse
/// arena remain live until all replacement rows have been emitted.
pub const Completion = struct {
allocator: Allocator,
io: Io,
did: []u8,
prepared_arena: *std.heap.ArenaAllocator,
prepared: prepared_fetch.Prepared,
fetched_chain: verify.ChainUpdate,
pending: std.ArrayList(PendingVerified) = .empty,
witnessed_at: i64,
/// Successful synchronous #sync repair carries the original firehose
/// cursor. Commit-triggered and retry repairs are synthetic and carry nil.
upstream_seq: ?i64 = null,
/// Byte-exact typed #sync envelope which triggered a synchronous repair.
/// It must survive the trigger Job: the repair completion is emitted only
/// after that Job has been retired and its decode arena freed.
sync_payload: ?[]u8 = null,
/// The trigger ticket must complete ordered emission before this repair
/// may enter the archive. This preserves the verifier collector's global
/// result order while per-DID apply remains asynchronous.
after_ticket: u64,
pub fn deinit(self: *Completion) void {
for (self.pending.items) |item| {
item.arena.deinit();
self.allocator.destroy(item.arena);
}
self.pending.deinit(self.allocator);
self.prepared.deinit(self.io);
self.prepared_arena.deinit();
self.allocator.destroy(self.prepared_arena);
if (self.sync_payload) |payload| self.allocator.free(payload);
self.allocator.free(self.did);
self.allocator.destroy(self);
}
};
const Status = enum { idle, resyncing };
const State = struct {
did: []u8,
status: Status = .idle,
pending: std.ArrayList([]u8) = .empty,
trigger_ticket: u64 = 0,
sync_payload: ?[]u8 = null,
};
const Job = struct { did: []const u8, upstream_seq: ?i64 = null };
pub const Coordinator = struct {
allocator: Allocator,
io: Io,
verifier: *verify.Verifier,
relay_http: []const u8,
scratch_dir: []const u8,
stats: ?*metrics.Stats = null,
emit_failure_logs: bool = true,
publish_ctx: *anyopaque,
publish: *const fn (*anyopaque, *Completion) anyerror!void,
lanes: [lane_count]Io.Mutex = @splat(.init),
states_mu: Io.Mutex = .init,
states: std.StringHashMapUnmanaged(*State) = .empty,
limiter_mu: Io.Mutex = .init,
limiters: ?lru.LruCache(Bucket) = null,
queue_mu: Io.Mutex = .init,
queue_cond: Io.Condition = .init,
queue_space: Io.Condition = .init,
queue: [queue_capacity]?Job = @splat(null),
queue_read: u64 = 0,
queue_write: u64 = 0,
accepting: bool = true,
alive: bool = true,
fatal_error: ?anyerror = null,
futures: [worker_count]?Io.Future(void) = @splat(null),
pub fn start(self: *Coordinator) !void {
self.limiters = lru.LruCache(Bucket).init(self.allocator, limiter_capacity, self.io);
var spawned: usize = 0;
errdefer {
self.stop();
for (self.futures[0..spawned]) |*slot| {
if (slot.*) |*future| _ = future.cancel(self.io);
}
}
for (&self.futures) |*slot| {
slot.* = try self.io.concurrent(workerLoop, .{self});
spawned += 1;
}
}
pub fn stop(self: *Coordinator) void {
self.queue_mu.lockUncancelable(self.io);
self.accepting = false;
self.alive = false;
self.queue_cond.broadcast(self.io);
self.queue_space.broadcast(self.io);
self.queue_mu.unlock(self.io);
for (&self.futures) |*slot| {
if (slot.*) |*future| _ = future.cancel(self.io);
slot.* = null;
}
}
/// Close the job queue and wait for accepted repairs to publish their
/// completion. This is part of the archive cutover durability boundary.
pub fn drainAndStop(self: *Coordinator) !void {
self.queue_mu.lockUncancelable(self.io);
self.accepting = false;
self.queue_cond.broadcast(self.io);
self.queue_mu.unlock(self.io);
for (&self.futures) |*slot| {
if (slot.*) |*future| _ = future.await(self.io);
slot.* = null;
}
self.queue_mu.lockUncancelable(self.io);
const failure = self.fatal_error;
self.alive = false;
self.queue_mu.unlock(self.io);
if (failure) |err| return err;
}
pub fn deinit(self: *Coordinator) void {
self.stop();
var it = self.states.iterator();
while (it.next()) |entry| self.freeState(entry.value_ptr.*);
self.states.deinit(self.allocator);
if (self.limiters) |*limiters| limiters.deinit();
self.limiters = null;
}
pub fn fatalError(self: *Coordinator) ?anyerror {
self.queue_mu.lockUncancelable(self.io);
defer self.queue_mu.unlock(self.io);
return self.fatal_error;
}
/// Verify one decoded frame while holding the same bounded per-DID lane
/// used by repair apply. A commit arriving during fetch is copied into the
/// bounded pending FIFO; the reader and other DIDs continue immediately.
pub fn process(
self: *Coordinator,
resolver: *zat.DidResolver,
frame: []const u8,
event: zat.FirehoseEvent,
ticket: u64,
) !verify.Result {
const did = eventDid(event) orelse return .{};
const lane = self.laneFor(did);
lane.lockUncancelable(self.io);
var lane_locked = true;
defer if (lane_locked) lane.unlock(self.io);
if (event == .commit) {
if (self.getState(did)) |state| if (state.status == .resyncing) {
try self.bufferPending(state, frame);
return .{ .outcome = .needs_resync };
};
}
const result = switch (event) {
.commit => |value| try self.verifier.verifyCommit(resolver, value),
.sync => |value| try self.verifier.verifySync(resolver, value),
.identity => |value| blk: {
self.verifier.evict(value.did);
break :blk verify.Result{};
},
.account => |value| try self.verifier.onAccount(value),
.info => verify.Result{},
};
if (result.outcome != .needs_resync) return result;
// Unlike a broken #commit, Atmos first repairs #sync inline. The
// network fetch is unlocked, and only a retry enters the async queue.
if (event == .sync) {
const sync_payload = try encodeSyncPayload(self.allocator, event.sync);
const started = self.beginSynchronousRepairLocked(did, ticket, sync_payload) catch |err| {
self.allocator.free(sync_payload);
return err;
};
if (!started) {
self.allocator.free(sync_payload);
return result;
}
const state = self.getState(did).?;
lane.unlock(self.io);
lane_locked = false;
self.runJob(resolver, .{ .did = state.did, .upstream_seq = event.sync.seq }) catch |err| {
if (self.emit_failure_logs)
log.err("synchronous sync repair failed for {s}: {s}", .{ did, @errorName(err) });
if (retryableSyncFailure(err)) {
lane.lockUncancelable(self.io);
lane_locked = true;
const retry_state = self.getState(did) orelse return error.RepairStateMissing;
retry_state.status = .idle;
self.noteFailed(err);
try self.scheduleLocked(did, ticket);
} else {
self.failJob(did, err);
}
};
return result;
}
try self.scheduleLocked(did, ticket);
return result;
}
/// Begin the inline #sync attempt. Caller holds the DID lane. A repair
/// already in flight is sufficient, so the sync directive is withheld.
fn beginSynchronousRepairLocked(self: *Coordinator, did: []const u8, ticket: u64, sync_payload: []u8) !bool {
const existing = self.getState(did);
if (existing) |state| if (state.status == .resyncing) return false;
const state = existing orelse try self.createState(did);
state.status = .resyncing;
state.trigger_ticket = ticket;
if (state.sync_payload) |old| self.allocator.free(old);
state.sync_payload = sync_payload;
return true;
}
fn scheduleLocked(self: *Coordinator, did: []const u8, ticket: u64) !void {
const existing = self.getState(did);
const state = existing orelse try self.createState(did);
if (state.status == .resyncing) return;
state.status = .resyncing;
state.trigger_ticket = ticket;
self.queue_mu.lockUncancelable(self.io);
defer self.queue_mu.unlock(self.io);
while (self.alive and self.accepting and self.queue_write - self.queue_read >= queue_capacity)
try self.queue_space.wait(self.io, &self.queue_mu);
if (!self.alive or !self.accepting) return error.Closed;
self.queue[self.queue_write % queue_capacity] = .{ .did = state.did };
self.queue_write += 1;
self.queue_cond.signal(self.io);
if (self.stats) |stats| stats.resync_queue_depth.store(@intCast(self.queue_write - self.queue_read), .monotonic);
}
fn bufferPending(self: *Coordinator, state: *State, frame: []const u8) !void {
const owned = try self.allocator.dupe(u8, frame);
const grew = state.pending.items.len != pending_capacity;
if (!grew) {
const dropped = state.pending.orderedRemove(0);
self.allocator.free(dropped);
if (self.stats) |stats| _ = stats.resync_pending_dropped_total.fetchAdd(1, .monotonic);
if (self.emit_failure_logs)
log.err("repair pending overflow: {s}; dropped oldest commit", .{state.did});
}
try state.pending.append(self.allocator, owned);
if (grew) {
if (self.stats) |stats| _ = stats.resync_pending.fetchAdd(1, .monotonic);
}
}
fn workerLoop(self: *Coordinator) void {
var resolver = self.verifier.makeResolver();
defer resolver.deinit();
while (self.takeJob()) |job| self.runJob(&resolver, job) catch |err| {
if (self.emit_failure_logs)
log.err("repair worker failed for {s}: {s}", .{ job.did, @errorName(err) });
self.failJob(job.did, err);
};
}
fn takeJob(self: *Coordinator) ?Job {
self.queue_mu.lockUncancelable(self.io);
defer self.queue_mu.unlock(self.io);
while (self.alive and self.queue_read == self.queue_write and self.accepting)
self.queue_cond.wait(self.io, &self.queue_mu) catch {};
if (!self.alive or (self.queue_read == self.queue_write and !self.accepting)) return null;
const index = self.queue_read % queue_capacity;
const job = self.queue[index].?;
self.queue[index] = null;
self.queue_read += 1;
self.queue_space.signal(self.io);
if (self.stats) |stats| stats.resync_queue_depth.store(@intCast(self.queue_write - self.queue_read), .monotonic);
return job;
}
fn runJob(self: *Coordinator, resolver: *zat.DidResolver, job: Job) !void {
if (self.stats) |stats| _ = stats.resync_active.fetchAdd(1, .monotonic);
defer {
if (self.stats) |stats| _ = stats.resync_active.fetchSub(1, .monotonic);
}
const now_us = Io.Timestamp.now(self.io, .real).toMicroseconds();
if (!try self.takeRepairToken(job.did, now_us)) {
if (self.stats) |stats| _ = stats.resync_rate_limited_total.fetchAdd(1, .monotonic);
log.warn("repair rate limited: {s}", .{job.did});
return error.RepairRateLimited;
}
var parse_arena = try self.allocator.create(std.heap.ArenaAllocator);
parse_arena.* = std.heap.ArenaAllocator.init(self.allocator);
errdefer {
parse_arena.deinit();
self.allocator.destroy(parse_arena);
}
var final_host: fetched_car.FinalHost = .{};
const outcome = try prepared_fetch.fetch(
self.allocator,
parse_arena.allocator(),
self.io,
self.scratch_dir,
self.relay_http,
job.did,
&final_host,
);
var prepared = switch (outcome) {
.ok => |value| value,
else => return error.GetRepoFailed,
};
errdefer prepared.deinit(self.io);
const lane = self.laneFor(job.did);
lane.lockUncancelable(self.io);
defer lane.unlock(self.io);
const state = self.getState(job.did) orelse return error.RepairStateMissing;
if (state.status != .resyncing) return error.RepairStateMissing;
const fetched = try self.verifier.verifyFetchedRepo(resolver, job.did, &prepared.repo);
const fetched_chain = fetched.chain orelse return error.RepairAuthenticationFailed;
try validateFetchedHead(try self.verifier.chainFor(job.did), fetched_chain);
try self.verifier.rememberChain(job.did, fetched_chain);
const completion = try self.allocator.create(Completion);
errdefer self.allocator.destroy(completion);
completion.* = .{
.allocator = self.allocator,
.io = self.io,
.did = try self.allocator.dupe(u8, job.did),
.prepared_arena = parse_arena,
.prepared = prepared,
.fetched_chain = fetched_chain,
.witnessed_at = Io.Timestamp.now(self.io, .real).toMicroseconds(),
.after_ticket = state.trigger_ticket,
.upstream_seq = job.upstream_seq,
.sync_payload = state.sync_payload,
};
state.sync_payload = null;
errdefer {
self.allocator.free(completion.did);
if (completion.sync_payload) |payload| self.allocator.free(payload);
for (completion.pending.items) |item| {
item.arena.deinit();
self.allocator.destroy(item.arena);
}
completion.pending.deinit(self.allocator);
}
for (state.pending.items) |raw| {
const arena = try self.allocator.create(std.heap.ArenaAllocator);
arena.* = std.heap.ArenaAllocator.init(self.allocator);
const event = zat.firehose.decodeFrame(arena.allocator(), raw) catch {
arena.deinit();
self.allocator.destroy(arena);
continue;
};
const verdict = switch (event) {
.commit => |value| try self.verifier.verifyCommit(resolver, value),
else => {
arena.deinit();
self.allocator.destroy(arena);
continue;
},
};
switch (verdict.outcome) {
.valid => try completion.pending.append(self.allocator, .{
.arena = arena,
.event = event,
.verdict = verdict,
}),
.replay => {
arena.deinit();
self.allocator.destroy(arena);
},
else => {
log.err("pending repair replay rejected: {s} reason={s}", .{ job.did, @tagName(verdict.outcome) });
arena.deinit();
self.allocator.destroy(arena);
},
}
}
// Registration under the DID lane is the ordered outbox boundary:
// no later same-DID verification can finish before this callback.
try self.publish(self.publish_ctx, completion);
parse_arena = undefined;
prepared = undefined;
self.removeState(state);
if (self.stats) |stats| _ = stats.resync_completed_total.fetchAdd(1, .monotonic);
}
fn failJob(self: *Coordinator, did: []const u8, err: anyerror) void {
const lane = self.laneFor(did);
lane.lockUncancelable(self.io);
defer lane.unlock(self.io);
if (self.getState(did)) |state| {
if (state.pending.items.len == 0)
self.removeState(state)
else
state.status = .idle;
}
self.noteFailed(err);
// Local allocation/write/publication failures are fatal. Remote and
// validation failures remain observable and allow a later retry.
switch (err) {
error.OutOfMemory, error.WriteFailed, error.ArchiveAppendFailed => self.setFatal(err),
else => {},
}
}
fn noteFailed(self: *Coordinator, err: anyerror) void {
if (self.stats) |stats| _ = stats.resync_failed_total.fetchAdd(1, .monotonic);
if (err == error.StaleRepair) {
if (self.stats) |stats| _ = stats.resync_stale_total.fetchAdd(1, .monotonic);
}
}
fn setFatal(self: *Coordinator, err: anyerror) void {
self.queue_mu.lockUncancelable(self.io);
defer self.queue_mu.unlock(self.io);
if (self.fatal_error == null) self.fatal_error = err;
}
fn laneFor(self: *Coordinator, did: []const u8) *Io.Mutex {
return &self.lanes[std.hash.Wyhash.hash(0, did) % lane_count];
}
fn getState(self: *Coordinator, did: []const u8) ?*State {
self.states_mu.lockUncancelable(self.io);
defer self.states_mu.unlock(self.io);
return self.states.get(did);
}
fn createState(self: *Coordinator, did: []const u8) !*State {
const state = try self.allocator.create(State);
errdefer self.allocator.destroy(state);
state.* = .{ .did = try self.allocator.dupe(u8, did) };
errdefer self.allocator.free(state.did);
self.states_mu.lockUncancelable(self.io);
defer self.states_mu.unlock(self.io);
try self.states.put(self.allocator, state.did, state);
return state;
}
fn removeState(self: *Coordinator, state: *State) void {
self.states_mu.lockUncancelable(self.io);
_ = self.states.remove(state.did);
self.states_mu.unlock(self.io);
if (self.stats) |stats| _ = stats.resync_pending.fetchSub(state.pending.items.len, .monotonic);
self.freeState(state);
}
fn freeState(self: *Coordinator, state: *State) void {
for (state.pending.items) |frame| self.allocator.free(frame);
state.pending.deinit(self.allocator);
if (state.sync_payload) |payload| self.allocator.free(payload);
self.allocator.free(state.did);
self.allocator.destroy(state);
}
fn takeRepairToken(self: *Coordinator, did: []const u8, now_us: i64) !bool {
self.limiter_mu.lockUncancelable(self.io);
defer self.limiter_mu.unlock(self.io);
const limiters = &(self.limiters orelse return error.CoordinatorNotStarted);
var bucket = limiters.get(did) orelse Bucket{ .last_us = now_us };
const allowed = takeToken(&bucket, now_us);
try limiters.put(did, bucket);
return allowed;
}
};
fn encodeSyncPayload(allocator: Allocator, sync_event: zat.firehose.SyncEvent) ![]u8 {
const entries = [_]zat.cbor.Value.MapEntry{
.{ .key = "did", .value = .{ .text = sync_event.did } },
.{ .key = "rev", .value = .{ .text = sync_event.rev } },
.{ .key = "seq", .value = .{ .unsigned = @intCast(@max(sync_event.seq, 0)) } },
.{ .key = "time", .value = .{ .text = sync_event.time } },
.{ .key = "blocks", .value = .{ .bytes = sync_event.blocks } },
};
return zat.cbor.encodeAlloc(allocator, .{ .map = &entries });
}
fn takeToken(bucket: *Bucket, now_us: i64) bool {
if (now_us > bucket.last_us) {
const steps: u64 = @intCast(@divFloor(now_us - bucket.last_us, refill_us));
if (steps != 0) {
bucket.tokens = @intCast(@min(@as(u64, bucket.tokens) + steps, 5));
bucket.last_us += @as(i64, @intCast(steps)) * refill_us;
}
}
if (bucket.tokens == 0) return false;
bucket.tokens -= 1;
return true;
}
fn validateFetchedHead(current: ?verify.ChainUpdate, fetched: verify.ChainUpdate) !void {
const seen = current orelse return;
switch (std.mem.order(u8, &fetched.rev, &seen.rev)) {
.lt => return error.StaleRepair,
.eq => if (!std.mem.eql(u8, fetched.dataSlice(), seen.dataSlice()))
return error.ContradictoryRepair,
.gt => {},
}
}
/// Match Atmos's one deferred retry for transport/rate-limit failures of a
/// synchronous #sync repair. Authentication and rev-regression failures are
/// deterministic and deliberately do not retry the same authoritative head.
fn retryableSyncFailure(err: anyerror) bool {
return switch (err) {
error.GetRepoFailed,
error.AttemptTimeout,
error.TransferTooSlow,
error.RepairRateLimited,
error.ConnectionRefused,
error.ConnectionResetByPeer,
error.NetworkUnreachable,
error.TemporaryNameServerFailure,
=> true,
else => false,
};
}
fn eventDid(event: zat.FirehoseEvent) ?[]const u8 {
return switch (event) {
.commit => |value| value.repo,
.sync => |value| value.did,
.identity => |value| value.did,
.account => |value| value.did,
.info => null,
};
}
test "repair limiter matches upstream five per minute burst five" {
var bucket: Bucket = .{ .last_us = 1_000_000 };
for (0..5) |_| try std.testing.expect(takeToken(&bucket, 1_000_000));
try std.testing.expect(!takeToken(&bucket, 1_000_000));
try std.testing.expect(!takeToken(&bucket, 1_000_000 + 11 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 12 * std.time.us_per_s));
try std.testing.expect(!takeToken(&bucket, 1_000_000 + 12 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
try std.testing.expect(takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
try std.testing.expect(!takeToken(&bucket, 1_000_000 + 72 * std.time.us_per_s));
}
test "repair apply rejects older and contradictory authoritative heads" {
var current: verify.ChainUpdate = .{ .rev = undefined, .data_len = 3 };
@memcpy(¤t.rev, "3k2abcdefghij");
@memcpy(current.data[0..3], "one");
var fetched = current;
try validateFetchedHead(current, fetched);
@memcpy(fetched.data[0..3], "two");
try std.testing.expectError(error.ContradictoryRepair, validateFetchedHead(current, fetched));
@memcpy(&fetched.rev, "3k2abc0000000");
try std.testing.expectError(error.StaleRepair, validateFetchedHead(current, fetched));
@memcpy(&fetched.rev, "3k2zzzzzzzzzz");
try validateFetchedHead(current, fetched);
}
test "pending FIFO is bounded at 2048 and drops the oldest real frame" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
var stats: metrics.Stats = .{};
var coordinator: Coordinator = .{
.allocator = testing.allocator,
.io = threaded.io(),
.verifier = undefined,
.relay_http = "http://offline.invalid",
.scratch_dir = "unused",
.stats = &stats,
.emit_failure_logs = false,
.publish_ctx = undefined,
.publish = undefined,
};
var state: State = .{ .did = @constCast("did:plc:pending-fixture") };
defer {
for (state.pending.items) |frame| testing.allocator.free(frame);
state.pending.deinit(testing.allocator);
}
var frame_buf: [16]u8 = undefined;
for (0..pending_capacity + 1) |i| {
const frame = try std.fmt.bufPrint(&frame_buf, "frame-{d}", .{i});
try coordinator.bufferPending(&state, frame);
}
try testing.expectEqual(@as(usize, pending_capacity), state.pending.items.len);
try testing.expectEqualStrings("frame-1", state.pending.items[0]);
try testing.expectEqualStrings("frame-2048", state.pending.items[pending_capacity - 1]);
try testing.expectEqual(@as(u64, 1), stats.resync_pending_dropped_total.load(.monotonic));
try testing.expectEqual(@as(usize, pending_capacity), stats.resync_pending.load(.monotonic));
}
test "offline worker pool performs exactly 32 concurrent real HTTP fetches" {
const testing = std.testing;
const request_count = 40;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
defer server.deinit(io);
var active: std.atomic.Value(usize) = .init(0);
var maximum: std.atomic.Value(usize) = .init(0);
var reached_pool: Io.Event = .unset;
var release: Io.Event = .unset;
const Fixture = struct {
fn serveOne(
stream_value: Io.net.Stream,
task_io: Io,
active_count: *std.atomic.Value(usize),
max_count: *std.atomic.Value(usize),
reached: *Io.Event,
release_gate: *Io.Event,
) void {
var stream = stream_value;
defer stream.close(task_io);
var read_buf: [2048]u8 = undefined;
var write_buf: [2048]u8 = undefined;
var reader = stream.reader(task_io, &read_buf);
var writer = stream.writer(task_io, &write_buf);
var http_server = std.http.Server.init(&reader.interface, &writer.interface);
var request = http_server.receiveHead() catch return;
const now = active_count.fetchAdd(1, .acq_rel) + 1;
var seen = max_count.load(.acquire);
while (now > seen) {
seen = max_count.cmpxchgWeak(seen, now, .acq_rel, .acquire) orelse break;
}
if (now == worker_count) reached.set(task_io);
release_gate.wait(task_io) catch return;
request.respond("", .{ .status = .service_unavailable, .keep_alive = false }) catch return;
_ = active_count.fetchSub(1, .acq_rel);
}
fn run(
listener: *Io.net.Server,
task_io: Io,
active_count: *std.atomic.Value(usize),
max_count: *std.atomic.Value(usize),
reached: *Io.Event,
release_gate: *Io.Event,
) !void {
var futures: [request_count]?Io.Future(void) = @splat(null);
for (&futures) |*slot| {
const stream = try listener.accept(task_io);
slot.* = try task_io.concurrent(serveOne, .{ stream, task_io, active_count, max_count, reached, release_gate });
}
for (&futures) |*slot| {
if (slot.*) |*future| _ = future.await(task_io);
}
}
};
var server_future = try io.concurrent(Fixture.run, .{ &server, io, &active, &maximum, &reached_pool, &release });
defer _ = server_future.cancel(io) catch {};
var url_buf: [96]u8 = undefined;
const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});
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 meta = try meta_store.Store.open(testing.allocator, root);
defer meta.deinit();
var verifier = verify.Verifier.init(testing.allocator, io, "http://offline.invalid", &meta);
defer verifier.deinit();
const NoPublish = struct {
fn publish(_: *anyopaque, _: *Completion) !void {
return error.UnexpectedCompletion;
}
};
var scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const scratch = try std.fmt.bufPrint(&scratch_buf, "{s}/scratch", .{root});
var coordinator: Coordinator = .{
.allocator = testing.allocator,
.io = io,
.verifier = &verifier,
.relay_http = url,
.scratch_dir = scratch,
.emit_failure_logs = false,
.publish_ctx = undefined,
.publish = NoPublish.publish,
};
defer coordinator.deinit();
try coordinator.start();
for (0..request_count) |i| {
var did_buf: [64]u8 = undefined;
const did = try std.fmt.bufPrint(&did_buf, "did:plc:worker-{d}", .{i});
const lane = coordinator.laneFor(did);
lane.lockUncancelable(io);
try coordinator.scheduleLocked(did, i);
lane.unlock(io);
}
try reached_pool.waitTimeout(io, .{ .duration = .{ .raw = Io.Duration.fromSeconds(2), .clock = .awake } });
try testing.expectEqual(@as(usize, worker_count), active.load(.acquire));
release.set(io);
try coordinator.drainAndStop();
_ = try server_future.await(io);
try testing.expectEqual(@as(usize, worker_count), maximum.load(.acquire));
}
test "offline coordinator fetches and authenticates a real complete repo" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(21));
const did = "did:plc:repairfixture";
const did_key = try keypair.did(alloc);
const multibase = did_key["did:key:".len..];
const record = try zat.cbor.encodeAlloc(alloc, .{ .map = &.{
.{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
.{ .key = "text", .value = .{ .text = "offline repair" } },
} });
const record_cid = try zat.cbor.Cid.forDagCbor(alloc, record);
var tree = zat.mst.Mst.init(alloc);
try tree.put("app.bsky.feed.post/3k2abcdefghij", record_cid);
const data_cid = try tree.rootCid();
const signed = try zat.signCommit(alloc, .{
.did = did,
.rev = "3k2abcdefghij",
.data = data_cid,
}, &keypair);
var blocks: std.ArrayList(zat.car.Block) = .empty;
try blocks.append(alloc, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
try tree.collectBlocks(&blocks);
try blocks.append(alloc, .{ .cid_raw = record_cid.raw, .data = record });
const car_bytes = try zat.car.writeAlloc(alloc, .{ .roots = &.{signed.cid}, .blocks = blocks.items });
const did_doc = try std.fmt.allocPrint(alloc,
\\{{"id":"{s}","verificationMethod":[{{"id":"{s}#atproto","type":"Multikey","controller":"{s}","publicKeyMultibase":"{s}"}}]}}
, .{ did, did, did, multibase });
var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
defer server.deinit(io);
var fetch_started: Io.Event = .unset;
var release_fetch: Io.Event = .unset;
const Fixture = struct {
fn run(listener: *Io.net.Server, task_io: Io, doc: []const u8, car: []const u8, started: *Io.Event, release: *Io.Event) !void {
for (0..2) |_| {
var stream = try listener.accept(task_io);
defer stream.close(task_io);
var read_buf: [4096]u8 = undefined;
var write_buf: [4096]u8 = undefined;
var reader = stream.reader(task_io, &read_buf);
var writer = stream.writer(task_io, &write_buf);
var http_server = std.http.Server.init(&reader.interface, &writer.interface);
var request = try http_server.receiveHead();
const is_repo = std.mem.startsWith(u8, request.head.target, "/xrpc/");
if (is_repo) {
started.set(task_io);
try release.wait(task_io);
}
const body = if (is_repo) car else doc;
try request.respond(body, .{
.status = .ok,
.keep_alive = false,
.extra_headers = &.{.{
.name = "content-type",
.value = if (is_repo) "application/vnd.ipld.car" else "application/json",
}},
});
}
}
};
var server_future = try io.concurrent(Fixture.run, .{ &server, io, did_doc, car_bytes, &fetch_started, &release_fetch });
defer _ = server_future.cancel(io) catch {};
var url_buf: [96]u8 = undefined;
const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()});
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 meta = try meta_store.Store.open(testing.allocator, root);
defer meta.deinit();
var verifier = verify.Verifier.init(testing.allocator, io, url, &meta);
defer verifier.deinit();
const Published = struct {
completion: ?*Completion = null,
fn publish(ctx: *anyopaque, completion: *Completion) !void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.completion != null) return error.DuplicateCompletion;
self.completion = completion;
}
};
var published: Published = .{};
var scratch_buf: [Io.Dir.max_path_bytes]u8 = undefined;
const scratch = try std.fmt.bufPrint(&scratch_buf, "{s}/scratch", .{root});
var coordinator: Coordinator = .{
.allocator = testing.allocator,
.io = io,
.verifier = &verifier,
.relay_http = url,
.scratch_dir = scratch,
.publish_ctx = &published,
.publish = Published.publish,
};
defer coordinator.deinit();
try coordinator.start();
var resolver = verifier.makeResolver();
defer resolver.deinit();
const sync_event: zat.FirehoseEvent = .{ .sync = .{
.seq = 1,
.did = did,
.rev = "3k2abcdefghij",
.time = "2026-07-16T00:00:00Z",
.blocks = &.{},
} };
const SyncTask = struct {
coordinator: *Coordinator,
resolver: *zat.DidResolver,
event: zat.FirehoseEvent,
result: ?(anyerror!verify.Result) = null,
fn run(self: *@This()) void {
self.result = self.coordinator.process(self.resolver, "", self.event, 0);
}
};
var sync_task: SyncTask = .{ .coordinator = &coordinator, .resolver = &resolver, .event = sync_event };
var sync_future = try io.concurrent(SyncTask.run, .{&sync_task});
defer _ = sync_future.cancel(io);
try fetch_started.wait(io);
// The HTTP response is deliberately held open. A same-DID commit must
// still return immediately into the real pending FIFO: fetch I/O never
// owns the per-DID apply lane.
const pending_frame = try zat.firehose.encodeCommitEvent(alloc, .{
.seq = 2,
.repo_did = did,
.commit_cid = signed.cid,
.rev = "3k2abcdefghij",
.blocks = car_bytes,
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2abcdefghij",
.cid = record_cid,
}},
.time = "2026-07-16T00:00:01Z",
});
var pending_arena = std.heap.ArenaAllocator.init(testing.allocator);
defer pending_arena.deinit();
const pending_event = try zat.firehose.decodeFrame(pending_arena.allocator(), pending_frame);
const buffered = try coordinator.process(&resolver, pending_frame, pending_event, 1);
try testing.expectEqual(verify.Outcome.needs_resync, buffered.outcome);
release_fetch.set(io);
_ = sync_future.await(io);
const result = try sync_task.result.?;
try testing.expectEqual(verify.Outcome.needs_resync, result.outcome);
try coordinator.drainAndStop();
_ = try server_future.await(io);
const completion = published.completion orelse return error.MissingCompletion;
defer completion.deinit();
try testing.expectEqualStrings(did, completion.did);
try testing.expectEqualStrings("3k2abcdefghij", &completion.fetched_chain.rev);
try testing.expectEqualSlices(u8, data_cid.raw, completion.fetched_chain.dataSlice());
try testing.expectEqual(@as(usize, 0), completion.pending.items.len);
try testing.expectEqual(@as(?i64, 1), completion.upstream_seq);
try testing.expectEqual(@as(?anyerror, null), coordinator.fatalError());
}