//! Atmos-compatible live scheduler: 32 workers, FIFO per DID, 64 pending //! events per DID with drop-oldest overflow, completion-order delivery across //! DIDs, and a smallest-in-flight relay cursor watermark. const std = @import("std"); const zat = @import("zat"); const verify = @import("verify.zig"); const repair = @import("repair.zig"); const observability = @import("../runtime/observability.zig"); const meta_store = @import("../storage/meta_store.zig"); const metrics = @import("../runtime/metrics.zig"); const Io = std.Io; const Allocator = std.mem.Allocator; const log = std.log.scoped(.stream); const worker_count = 32; const key_queue_capacity = worker_count * 2; const result_capacity = 4096; const batch_size = 50; const batch_timeout: Io.Clock.Duration = .{ .raw = Io.Duration.fromMilliseconds(500), .clock = .awake }; const Job = struct { ticket: u64, frame: []u8, arena: ?*std.heap.ArenaAllocator = null, event: ?zat.FirehoseEvent = null, key: []const u8 = "", seq: ?i64 = null, verdict: verify.Result = .{}, failure: ?anyerror = null, }; const KeyChain = struct { key: []u8, pending: std.ArrayList(*Job) = .empty, }; const Delivery = union(enum) { job: *Job, repair: *repair.Completion, }; pub const Pipeline = struct { allocator: Allocator, io: Io, verifier: ?*verify.Verifier, repair: ?*repair.Coordinator = null, stats: ?*metrics.Stats = null, /// Normal events are delivered in cross-DID verification completion /// order, while each DID remains FIFO. emit_ctx: *anyopaque, emit: *const fn (*anyopaque, zat.FirehoseEvent, verify.Result, observability.Context) anyerror!void, emit_repair: ?*const fn (*anyopaque, *repair.Completion, observability.Context) anyerror!void = null, emit_cursor: ?*const fn (*anyopaque, i64) anyerror!void = null, mutex: Io.Mutex = .init, work_cond: Io.Condition = .init, space_cond: Io.Condition = .init, wake: Io.Event = .unset, chains: std.StringHashMapUnmanaged(*KeyChain) = .empty, ready: std.ArrayList(*Job) = .empty, ready_read: usize = 0, completed: std.ArrayList(*Job) = .empty, completed_read: usize = 0, inflight: std.AutoHashMapUnmanaged(i64, void) = .empty, processed_sparse: std.AutoHashMapUnmanaged(u64, void) = .empty, processed_prefix: u64 = 0, next_submit: u64 = 0, claimed: u64 = 0, processed: u64 = 0, active_chains: usize = 0, writer_jobs_buffered: usize = 0, cursor_watermark: i64 = 0, trace_context: observability.Context = observability.root_context, /// Highest positive relay seq accepted by this process. Atmos falls back /// to this global high-water when the inflight set is empty; using only /// the current completion batch can strand the cursor after a replayed /// lower-seq batch completes after newer work. highest_seq: i64 = 0, accepting: bool = true, alive: bool = true, stopped: bool = false, fatal_error: ?anyerror = null, repair_queue: std.ArrayList(*repair.Completion) = .empty, repair_buffered: usize = 0, // workers + writer run as io.concurrent tasks, never raw std.Threads: // they call io-backed I/O (DID resolution, archive writes), and Io // primitives must run under the backend that created them // (docs/lessons-from-zlay.md #2) futures: [worker_count + 1]?Io.Future(void) = @splat(null), pub fn start(self: *Pipeline) !void { if (self.stats) |stats| { stats.pipeline_submitted.store(0, .monotonic); stats.pipeline_claimed.store(0, .monotonic); stats.pipeline_unclaimed_dropped.store(0, .monotonic); stats.pipeline_emitted.store(0, .monotonic); stats.pipeline_fatal.store(0, .monotonic); } var spawned: usize = 0; errdefer { self.signalStop(); for (self.futures[0..spawned]) |*f| { if (f.*) |*future| _ = future.cancel(self.io); } } for (0..worker_count) |i| { self.futures[i] = try self.io.concurrent(workerLoop, .{self}); spawned += 1; } self.futures[worker_count] = try self.io.concurrent(writerLoop, .{self}); } fn signalStop(self: *Pipeline) void { self.mutex.lockUncancelable(self.io); self.accepting = false; self.alive = false; self.work_cond.broadcast(self.io); self.space_cond.broadcast(self.io); self.wake.set(self.io); self.mutex.unlock(self.io); } pub fn stop(self: *Pipeline) void { if (self.stopped) return; self.stopped = true; if (self.repair) |coordinator| coordinator.stop(); self.signalStop(); for (&self.futures) |*f| { if (f.*) |*future| _ = future.cancel(self.io); f.* = null; } for (self.ready.items[self.ready_read..]) |job| self.freeJob(job); for (self.completed.items[self.completed_read..]) |job| self.freeJob(job); self.ready.deinit(self.allocator); self.completed.deinit(self.allocator); var chains = self.chains.iterator(); while (chains.next()) |entry| self.freeChain(entry.value_ptr.*); self.chains.deinit(self.allocator); self.inflight.deinit(self.allocator); self.processed_sparse.deinit(self.allocator); for (self.repair_queue.items) |completion| completion.deinit(); self.repair_queue.deinit(self.allocator); } /// Stop accepting frames, wait until every already-accepted ticket has /// completed its ordered emit callback, then stop the worker tasks. This /// is the archive cutover boundary: callers may close or seal storage only /// after this returns. pub fn drainAndStop(self: *Pipeline) !void { self.mutex.lockUncancelable(self.io); self.accepting = false; // Signals are intentionally not counted by a condition variable. A // burst submitted immediately before capture cancellation can leave // workers asleep even though claimed trails next_submit, so the // cutover must wake every worker to consume the fixed backlog. self.work_cond.broadcast(self.io); self.space_cond.broadcast(self.io); log.debug("pipeline drain boundary: {d} submitted, {d} claimed, {d} processed", .{ self.next_submit, self.claimed, self.processed, }); while (self.alive and (self.processed != self.next_submit or self.writer_jobs_buffered != 0)) { self.space_cond.wait(self.io, &self.mutex) catch {}; } self.mutex.unlock(self.io); if (self.repair) |coordinator| try coordinator.drainAndStop(); self.mutex.lockUncancelable(self.io); while (self.alive and (self.repair_queue.items.len != 0 or self.repair_buffered != 0)) self.space_cond.wait(self.io, &self.mutex) catch {}; const failure = self.fatal_error; self.mutex.unlock(self.io); self.stop(); if (failure) |err| return err; } fn freeJob(self: *Pipeline, job: *Job) void { if (job.arena) |a| { a.deinit(); self.allocator.destroy(a); } self.allocator.free(job.frame); self.allocator.destroy(job); } fn freeChain(self: *Pipeline, chain: *KeyChain) void { for (chain.pending.items) |job| self.freeJob(job); chain.pending.deinit(self.allocator); self.allocator.free(chain.key); self.allocator.destroy(chain); } pub fn fatalError(self: *Pipeline) ?anyerror { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); if (self.fatal_error) |err| return err; if (self.repair) |coordinator| if (coordinator.fatalError()) |err| { self.recordFatalLocked(.repair, err); return err; }; return null; } pub const Gauges = struct { submitted: u64, claimed: u64, emitted: u64 }; pub fn gauges(self: *Pipeline) Gauges { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); return .{ .submitted = self.next_submit, .claimed = self.claimed, .emitted = self.processed }; } /// Envelope peek on the dispatch path — seq and the per-DID chain key /// only, via lax CBOR that never hydrates the CAR block set. The full /// decode runs in the worker pool (see workerLoop): Atmos's dispatch /// decode is the envelope unmarshal alone, and its CAR/block parse /// happens inside the parallel workers (streaming/operation.go). Doing /// the CAR parse here serialized the entire firehose on the websocket /// reader thread (~360 events/s measured against a 3,700/s socket). /// The returned key borrows from `frame` and lives as long as the job. const Peek = struct { seq: ?i64 = null, key: []const u8 = "" }; fn peekEnvelope(allocator: Allocator, frame: []const u8) Peek { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const header = zat.cbor.decodeLax(arena.allocator(), frame) catch return .{}; const payload = zat.cbor.decodeAllLax(arena.allocator(), frame[header.consumed..]) catch return .{}; const seq = payload.getInt("seq"); const tag = header.value.getString("t") orelse return .{ .seq = seq }; const key = (if (std.mem.eql(u8, tag, "#commit")) payload.getString("repo") else payload.getString("did")) orelse ""; return .{ .seq = seq, .key = key }; } pub fn submit(self: *Pipeline, data: []const u8) !void { const job = try self.allocator.create(Job); errdefer self.allocator.destroy(job); const frame = try self.allocator.dupe(u8, data); errdefer self.allocator.free(frame); const peek = peekEnvelope(self.allocator, frame); job.* = .{ .ticket = 0, .frame = frame, .key = peek.key, .seq = peek.seq }; self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); if (!self.alive or !self.accepting) return error.Closed; while (self.chains.get(job.key) == null and self.active_chains >= worker_count) { self.space_cond.wait(self.io, &self.mutex) catch return error.Canceled; if (!self.alive or !self.accepting) return error.Closed; } if (self.chains.get(job.key)) |chain| { try chain.pending.ensureUnusedCapacity(self.allocator, 1); if (job.seq) |seq| if (seq > 0) try self.inflight.ensureUnusedCapacity(self.allocator, 1); if (chain.pending.items.len >= key_queue_capacity) try self.processed_sparse.ensureUnusedCapacity(self.allocator, 1); job.ticket = self.next_submit; self.next_submit += 1; if (job.seq) |seq| if (seq > 0) { self.inflight.putAssumeCapacity(seq, {}); self.highest_seq = @max(self.highest_seq, seq); }; if (chain.pending.items.len >= key_queue_capacity) { const dropped = chain.pending.orderedRemove(0); self.dropJobLocked(dropped); } chain.pending.appendAssumeCapacity(job); } else { const chain = try self.allocator.create(KeyChain); errdefer self.allocator.destroy(chain); chain.* = .{ .key = try self.allocator.dupe(u8, job.key) }; errdefer self.allocator.free(chain.key); try self.chains.ensureUnusedCapacity(self.allocator, 1); try self.ready.ensureUnusedCapacity(self.allocator, 1); if (job.seq) |seq| if (seq > 0) try self.inflight.ensureUnusedCapacity(self.allocator, 1); job.ticket = self.next_submit; self.next_submit += 1; if (job.seq) |seq| if (seq > 0) { self.inflight.putAssumeCapacity(seq, {}); self.highest_seq = @max(self.highest_seq, seq); }; self.chains.putAssumeCapacity(chain.key, chain); self.ready.appendAssumeCapacity(job); self.active_chains += 1; self.work_cond.signal(self.io); } if (self.stats) |stats| stats.pipeline_submitted.store(self.next_submit, .monotonic); } fn dropJobLocked(self: *Pipeline, job: *Job) void { if (job.seq) |seq| _ = self.inflight.remove(seq); if (self.stats) |stats| _ = stats.pipeline_unclaimed_dropped.fetchAdd(1, .monotonic); self.markProcessedLocked(job.ticket); if (self.stats) |stats| _ = stats.verify_queue_dropped_total.fetchAdd(1, .monotonic); log.warn("verify queue overflow dropped oldest event: key={s} ticket={d}", .{ job.key, job.ticket }); self.freeJob(job); } fn workerLoop(self: *Pipeline) void { var resolver_storage = if (self.verifier) |v| v.makeResolver() else null; defer if (resolver_storage) |*r| r.deinit(); while (true) { self.mutex.lockUncancelable(self.io); while (self.alive and self.ready_read == self.ready.items.len) { self.compactReadyLocked(); self.work_cond.wait(self.io, &self.mutex) catch {}; } if (!self.alive) { self.mutex.unlock(self.io); return; } var job = self.ready.items[self.ready_read]; self.ready_read += 1; self.compactReadyLocked(); self.mutex.unlock(self.io); var owned_job: ?*Job = job; defer if (owned_job) |owned| self.freeJob(owned); while (true) { self.mutex.lockUncancelable(self.io); self.claimed += 1; if (self.stats) |stats| stats.pipeline_claimed.store(self.claimed, .monotonic); self.mutex.unlock(self.io); // Full frame decode (including CAR hydration) — parallel // across the pool, ordered per DID by the chain the job // arrived on. Decode failures leave event null; the writer // collects those silently, matching the old dispatch-path // behavior. if (job.event == null) { if (self.allocator.create(std.heap.ArenaAllocator)) |arena| { arena.* = std.heap.ArenaAllocator.init(self.allocator); if (zat.firehose.decodeFrame(arena.allocator(), job.frame)) |event| { job.arena = arena; job.event = event; } else |err| { log.debug("frame decode error: {s}", .{@errorName(err)}); if (self.stats) |stats| _ = stats.livestream_decode_errors_total.fetchAdd(1, .monotonic); arena.deinit(); self.allocator.destroy(arena); } } else |_| {} } var verdict: verify.Result = .{}; var failure: ?anyerror = null; if (self.verifier) |v| { if (job.event) |ev| verdict = if (self.repair) |coordinator| coordinator.process(if (resolver_storage) |*r| r else undefined, job.frame, ev, job.ticket) catch |err| blk: { failure = err; break :blk .{}; } else switch (ev) { .commit => |c| v.verifyCommit(if (resolver_storage) |*r| r else undefined, c) catch |err| blk: { failure = err; break :blk .{}; }, .sync => |sync_event| v.verifySync(if (resolver_storage) |*r| r else undefined, sync_event) catch |err| blk: { failure = err; break :blk .{}; }, // Key rotation must be observed in the same per-DID // order as commits, not later at global emission. .identity => |identity| blk: { v.evict(identity.did); break :blk .{}; }, .account => |account| v.onAccount(account) catch |err| blk: { failure = err; break :blk .{}; }, .info => .{}, }; } self.mutex.lockUncancelable(self.io); job.verdict = verdict; job.failure = failure; while (self.alive and self.completed.items.len - self.completed_read >= result_capacity) self.space_cond.wait(self.io, &self.mutex) catch {}; if (!self.alive) { self.mutex.unlock(self.io); return; } self.completed.append(self.allocator, job) catch |err| { self.mutex.unlock(self.io); owned_job = null; self.failJob(job, .scheduler, err); return; }; owned_job = null; const chain = self.chains.get(job.key).?; if (chain.pending.items.len > 0) { job = chain.pending.orderedRemove(0); owned_job = job; self.wake.set(self.io); self.mutex.unlock(self.io); continue; } _ = self.chains.remove(chain.key); chain.pending.deinit(self.allocator); self.allocator.free(chain.key); self.allocator.destroy(chain); self.active_chains -= 1; self.space_cond.broadcast(self.io); self.wake.set(self.io); self.mutex.unlock(self.io); break; } } } 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, }; } fn writerLoop(self: *Pipeline) void { var batch: std.ArrayList(Delivery) = .empty; var release_from: usize = 0; defer { for (batch.items[release_from..]) |delivery| switch (delivery) { .job => |job| self.freeJob(job), .repair => |completion| { completion.deinit(); self.mutex.lockUncancelable(self.io); self.repair_buffered -= 1; self.mutex.unlock(self.io); }, }; batch.deinit(self.allocator); } while (true) { batch.clearRetainingCapacity(); release_from = 0; var timed_out = false; var deadline: ?Io.Timestamp = null; while (batch.items.len < batch_size and !timed_out) { self.wake.reset(); self.mutex.lockUncancelable(self.io); if (!self.alive) { self.mutex.unlock(self.io); return; } if (self.completed_read < self.completed.items.len) { const job = self.completed.items[self.completed_read]; self.completed_read += 1; self.compactCompletedLocked(); self.space_cond.signal(self.io); if (job.seq) |seq| _ = self.inflight.remove(seq); self.mutex.unlock(self.io); if (job.failure != null or isSilent(job)) { if (job.failure) |err| log.warn("verification worker rejected event: {s}", .{@errorName(err)}); self.finishJob(job); } else { batch.append(self.allocator, .{ .job = job }) catch |err| { self.failJob(job, .scheduler, err); return; }; self.mutex.lockUncancelable(self.io); self.writer_jobs_buffered += 1; self.mutex.unlock(self.io); } if (batch.items.len > 0 and deadline == null) deadline = Io.Timestamp.now(self.io, .awake).addDuration(batch_timeout.raw); if (!self.appendEligibleRepairs(&batch, &deadline)) return; continue; } self.mutex.unlock(self.io); if (!self.appendEligibleRepairs(&batch, &deadline)) return; if (batch.items.len >= batch_size) continue; if (batch.items.len > 0) { const now = Io.Timestamp.now(self.io, .awake); if (now.toNanoseconds() >= deadline.?.toNanoseconds()) { timed_out = true; continue; } self.wake.waitTimeout(self.io, .{ .duration = .{ .raw = now.durationTo(deadline.?), .clock = .awake, } }) catch |err| switch (err) { error.Timeout => timed_out = true, else => return, }; continue; } self.wake.wait(self.io) catch return; } var max_seq: i64 = 0; var normal_jobs: usize = 0; var trace = observability.Span.start( self.allocator, "ingest/live", "processBatch", self.trace_context, &.{}, ); defer trace.deinit(); for (batch.items, 0..) |delivery, i| switch (delivery) { .job => |job| { if (job.event) |event| self.emit(self.emit_ctx, event, job.verdict, trace.context()) catch |err| { trace.fail(err); release_from = i + 1; self.failJob(job, .emit, err); return; }; if (job.seq) |seq| max_seq = @max(max_seq, seq); self.finishJob(job); normal_jobs += 1; release_from = i + 1; }, .repair => |completion| { const callback = self.emit_repair orelse { release_from = i + 1; completion.deinit(); self.finishBufferedRepair(); self.failPipeline(.repair, error.MissingRepairEmitter); return; }; callback(self.emit_ctx, completion, trace.context()) catch |err| { trace.fail(err); release_from = i + 1; completion.deinit(); self.finishBufferedRepair(); self.failPipeline(.repair, err); return; }; completion.deinit(); self.finishBufferedRepair(); release_from = i + 1; }, }; if (max_seq > 0) { const watermark = self.cursorAfterBatch(); if (watermark > self.cursor_watermark) { if (self.emit_cursor) |callback| callback(self.emit_ctx, watermark) catch |err| { trace.fail(err); self.failPipeline(.cursor, err); return; }; self.cursor_watermark = watermark; } } self.finishWriterBatch(normal_jobs); trace.succeed(); } } fn finishWriterBatch(self: *Pipeline, normal_jobs: usize) void { if (normal_jobs == 0) return; self.mutex.lockUncancelable(self.io); self.writer_jobs_buffered -= normal_jobs; self.space_cond.broadcast(self.io); self.mutex.unlock(self.io); } fn isSilent(job: *const Job) bool { const event = job.event orelse return true; return switch (event) { .commit, .sync => job.verdict.outcome != .valid, else => false, }; } fn finishJob(self: *Pipeline, job: *Job) void { self.mutex.lockUncancelable(self.io); self.markProcessedLocked(job.ticket); self.mutex.unlock(self.io); self.freeJob(job); } fn markProcessedLocked(self: *Pipeline, ticket: u64) void { self.processed += 1; if (self.stats) |stats| stats.pipeline_emitted.store(self.processed, .monotonic); if (ticket == self.processed_prefix) { self.processed_prefix += 1; while (self.processed_sparse.remove(self.processed_prefix)) self.processed_prefix += 1; } else if (ticket > self.processed_prefix) { self.processed_sparse.put(self.allocator, ticket, {}) catch { self.recordFatalLocked(.scheduler, error.OutOfMemory); self.alive = false; }; } self.space_cond.broadcast(self.io); self.wake.set(self.io); } fn cursorAfterBatch(self: *Pipeline) i64 { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); var minimum: ?i64 = null; var it = self.inflight.iterator(); while (it.next()) |entry| { const seq = entry.key_ptr.*; if (minimum == null or seq < minimum.?) minimum = seq; } return if (minimum) |seq| seq - 1 else self.highest_seq; } fn appendEligibleRepairs( self: *Pipeline, batch: *std.ArrayList(Delivery), deadline: *?Io.Timestamp, ) bool { while (batch.items.len < batch_size) { self.mutex.lockUncancelable(self.io); if (!self.alive) { self.mutex.unlock(self.io); return false; } const repair_index = self.eligibleRepairIndex() orelse { self.mutex.unlock(self.io); return true; }; const completion = self.repair_queue.orderedRemove(repair_index); self.repair_buffered += 1; self.mutex.unlock(self.io); batch.append(self.allocator, .{ .repair = completion }) catch |err| { completion.deinit(); self.finishBufferedRepair(); self.failPipeline(.scheduler, err); return false; }; if (deadline.* == null) deadline.* = Io.Timestamp.now(self.io, .awake).addDuration(batch_timeout.raw); } return true; } fn finishBufferedRepair(self: *Pipeline) void { self.mutex.lockUncancelable(self.io); self.repair_buffered -= 1; self.space_cond.broadcast(self.io); self.mutex.unlock(self.io); } /// Caller holds `mutex`. Choose the oldest trigger whose ordinary ticket /// has already crossed the writer callback; a faster later repair cannot /// jump ahead of earlier relay input. fn eligibleRepairIndex(self: *Pipeline) ?usize { for (self.repair_queue.items, 0..) |completion, i| { if (completion.after_ticket < self.processed_prefix or self.processed_sparse.contains(completion.after_ticket)) return i; } return null; } /// Repair workers call this while still holding their per-DID lane. The /// writer mutex makes registration atomic with selection of the next /// ordinary ticket, preserving upstream's ordered outbox guarantee. pub fn publishRepair(ctx: *anyopaque, completion: *repair.Completion) !void { const self: *Pipeline = @ptrCast(@alignCast(ctx)); self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); if (!self.alive) return error.Closed; try self.repair_queue.append(self.allocator, completion); self.wake.set(self.io); } fn failJob(self: *Pipeline, job: *Job, stage: metrics.PipelineFailureStage, err: anyerror) void { self.freeJob(job); self.failPipeline(stage, err); } fn failPipeline(self: *Pipeline, stage: metrics.PipelineFailureStage, err: anyerror) void { self.mutex.lockUncancelable(self.io); self.recordFatalLocked(stage, err); self.alive = false; self.work_cond.broadcast(self.io); self.space_cond.broadcast(self.io); self.wake.set(self.io); self.mutex.unlock(self.io); } /// Caller holds mutex. Count exactly the first terminal cause; secondary /// shutdown errors must not obscure the stage which stopped ingestion. fn recordFatalLocked(self: *Pipeline, stage: metrics.PipelineFailureStage, err: anyerror) void { if (self.fatal_error != null) return; self.fatal_error = err; if (self.stats) |stats| { stats.pipeline_fatal.store(1, .monotonic); _ = stats.pipeline_failures.getPtr(stage).fetchAdd(1, .monotonic); } } fn compactReadyLocked(self: *Pipeline) void { if (self.ready_read == self.ready.items.len) { self.ready.clearRetainingCapacity(); self.ready_read = 0; } } fn compactCompletedLocked(self: *Pipeline) void { if (self.completed_read == self.completed.items.len) { self.completed.clearRetainingCapacity(); self.completed_read = 0; } else if (self.completed_read >= result_capacity) { const remaining = self.completed.items.len - self.completed_read; std.mem.copyForwards( *Job, self.completed.items[0..remaining], self.completed.items[self.completed_read..], ); self.completed.items.len = remaining; self.completed_read = 0; } } }; // === tests === const testing = std.testing; const Collector = struct { frames: std.ArrayList([]u8) = .empty, allocator: Allocator, // no lock needed: emit runs only on the pipeline's single writer thread fn emit(ctx: *anyopaque, event: zat.FirehoseEvent, verdict: verify.Result, _: observability.Context) !void { _ = verdict; const self: *Collector = @ptrCast(@alignCast(ctx)); // test frames are #info envelopes carrying a name payload const copy = try self.allocator.dupe(u8, event.info.name orelse ""); try self.frames.append(self.allocator, copy); } }; fn controlFrame(allocator: Allocator, event: union(enum) { identity: zat.firehose.IdentityEvent, account: zat.firehose.AccountEvent, }) ![]u8 { var out: Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); const tag: []const u8 = switch (event) { .identity => "#identity", .account => "#account", }; try zat.cbor.encode(allocator, &out.writer, .{ .map = &.{ .{ .key = "op", .value = .{ .unsigned = 1 } }, .{ .key = "t", .value = .{ .text = tag } }, } }); switch (event) { .identity => |identity| try zat.cbor.encode(allocator, &out.writer, .{ .map = &.{ .{ .key = "did", .value = .{ .text = identity.did } }, .{ .key = "seq", .value = .{ .unsigned = @intCast(identity.seq) } }, .{ .key = "time", .value = .{ .text = identity.time } }, } }), .account => |account| try zat.cbor.encode(allocator, &out.writer, .{ .map = &.{ .{ .key = "active", .value = .{ .boolean = account.active } }, .{ .key = "did", .value = .{ .text = account.did } }, .{ .key = "seq", .value = .{ .unsigned = @intCast(account.seq) } }, .{ .key = "time", .value = .{ .text = account.time } }, } }), } return out.toOwnedSlice(); } const SeqCollector = struct { io: Io, mutex: Io.Mutex = .init, seqs: std.ArrayList(i64) = .empty, fn emit(ctx: *anyopaque, event: zat.FirehoseEvent, _: verify.Result, _: observability.Context) !void { const self: *SeqCollector = @ptrCast(@alignCast(ctx)); const seq = event.seq() orelse return; self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); try self.seqs.append(testing.allocator, seq); } fn len(self: *SeqCollector) usize { self.mutex.lockUncancelable(self.io); defer self.mutex.unlock(self.io); return self.seqs.items.len; } }; const WakeCollector = struct { io: Io, emitted: Io.Event = .unset, fn emit(ctx: *anyopaque, _: zat.FirehoseEvent, _: verify.Result, _: observability.Context) !void { const self: *WakeCollector = @ptrCast(@alignCast(ctx)); self.emitted.set(self.io); } }; const CursorProbe = struct { calls: usize = 0, last: i64 = 0, fn emit(_: *anyopaque, _: zat.FirehoseEvent, _: verify.Result, _: observability.Context) !void {} fn cursor(ctx: *anyopaque, value: i64) !void { const self: *CursorProbe = @ptrCast(@alignCast(ctx)); self.calls += 1; self.last = value; } }; test "pipeline preserves same-key submission order under parallel workers" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var collector: Collector = .{ .allocator = testing.allocator }; defer { for (collector.frames.items) |f| testing.allocator.free(f); collector.frames.deinit(testing.allocator); } var stats: metrics.Stats = .{}; var p: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .stats = &stats, .emit_ctx = &collector, .emit = Collector.emit, }; try p.start(); // 1000 frames over 100 DIDs, 10 per DID — under key_queue_capacity, so // nothing may drop, while distinct DIDs exercise genuinely parallel // chains. (A single shared key would hit live-scheduler.md's specced // drop-oldest once decode moved off the dispatch path and the producer // could outrun one chain.) Frames are #identity so each carries a DID; // name encodes key and per-key index as "frame--". for (0..1000) |i| { const k = i % 100; const j = i / 100; var did_buf: [24]u8 = undefined; const did = try std.fmt.bufPrint(&did_buf, "did:plc:key{d:0>3}", .{k}); var name_buf: [24]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "frame-{d}-{d}", .{ k, j }); var frame_buf: [96]u8 = undefined; var fw: Io.Writer = .fixed(&frame_buf); // header {"t":"#info","op":1} (length-first key order) try fw.writeAll(&.{ 0xa2, 0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', 0x62, 'o', 'p', 0x01 }); // payload {"did": , "name": } — the peek keys the chain // off "did" even for #info, giving 100 independent chains. try fw.writeAll(&.{ 0xa2, 0x63, 'd', 'i', 'd' }); try fw.writeByte(@intCast(0x60 + did.len)); try fw.writeAll(did); try fw.writeAll(&.{ 0x64, 'n', 'a', 'm', 'e' }); try fw.writeByte(@intCast(0x60 + name.len)); try fw.writeAll(name); try p.submit(fw.buffered()); } try p.drainAndStop(); try testing.expectEqual(@as(u64, 0), stats.verify_queue_dropped_total.load(.monotonic)); try testing.expectEqual(@as(usize, 1000), collector.frames.items.len); // per-key submission order must survive parallel workers var next_per_key: [100]usize = @splat(0); for (collector.frames.items) |f| { var it = std.mem.splitScalar(u8, f, '-'); _ = it.next(); // "frame" const k = try std.fmt.parseInt(usize, it.next().?, 10); const j = try std.fmt.parseInt(usize, it.next().?, 10); try testing.expectEqual(next_per_key[k], j); next_per_key[k] = j + 1; } for (next_per_key) |n| try testing.expectEqual(@as(usize, 10), n); } test "offline batch timeout is measured from the first completed event" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var collector: WakeCollector = .{ .io = io }; var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = io, .verifier = null, .emit_ctx = &collector, .emit = WakeCollector.emit, }; try pipeline.start(); defer pipeline.stop(); const first = &.{ 0xa2, 0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', 0x62, 'o', 'p', 0x01, 0xa1, 0x64, 'n', 'a', 'm', 'e', 0x61, 'a', }; const second = &.{ 0xa2, 0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', 0x62, 'o', 'p', 0x01, 0xa1, 0x64, 'n', 'a', 'm', 'e', 0x61, 'b', }; try pipeline.submit(first); try io.sleep(Io.Duration.fromMilliseconds(350), .awake); try pipeline.submit(second); // A sliding timeout would fire 500 ms after the second completion. The // upstream timer is armed by the first completion, so 300 ms is ample. try collector.emitted.waitTimeout(io, .{ .duration = .{ .raw = Io.Duration.fromMilliseconds(300), .clock = .awake }, }); try pipeline.drainAndStop(); } test "offline scheduler completes other DIDs while one verifier lane is blocked" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(io, &path_buf); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var verifier = verify.Verifier.init(testing.allocator, io, "http://offline.invalid", &meta); defer verifier.deinit(); var collector: SeqCollector = .{ .io = io }; defer collector.seqs.deinit(testing.allocator); var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = io, .verifier = &verifier, .emit_ctx = &collector, .emit = SeqCollector.emit, }; try pipeline.start(); defer pipeline.stop(); // Hold the real hosting-state lane so the first account event blocks in // Verifier.onAccount. A different DID must still verify and reach the // writer on another worker; no network or fake verifier is involved. verifier.chain_mu.lockUncancelable(io); var lane_held = true; defer if (lane_held) verifier.chain_mu.unlock(io); const slow = try controlFrame(testing.allocator, .{ .account = .{ .seq = 1, .did = "did:plc:slow-lane", .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(slow); const fast = try controlFrame(testing.allocator, .{ .identity = .{ .seq = 2, .did = "did:plc:fast-lane", .time = "2026-07-16T00:00:01Z", } }); defer testing.allocator.free(fast); try pipeline.submit(slow); while (pipeline.gauges().claimed < 1) std.Thread.yield() catch {}; try pipeline.submit(fast); const deadline = Io.Timestamp.now(io, .awake).addDuration(.fromSeconds(2)); while (collector.len() == 0 and Io.Timestamp.now(io, .awake).toNanoseconds() < deadline.toNanoseconds()) std.Thread.yield() catch {}; try testing.expectEqual(@as(usize, 1), collector.len()); try testing.expectEqual(@as(i64, 2), collector.seqs.items[0]); verifier.chain_mu.unlock(io); lane_held = false; try pipeline.drainAndStop(); try testing.expectEqualSlices(i64, &.{ 2, 1 }, collector.seqs.items); } test "offline scheduler keeps one DID FIFO while its verifier lane is blocked" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(io, &path_buf); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var verifier = verify.Verifier.init(testing.allocator, io, "http://offline.invalid", &meta); defer verifier.deinit(); var collector: SeqCollector = .{ .io = io }; defer collector.seqs.deinit(testing.allocator); var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = io, .verifier = &verifier, .emit_ctx = &collector, .emit = SeqCollector.emit, }; try pipeline.start(); defer pipeline.stop(); const did = "did:plc:one-fifo"; verifier.chain_mu.lockUncancelable(io); var lane_held = true; defer if (lane_held) verifier.chain_mu.unlock(io); const first = try controlFrame(testing.allocator, .{ .account = .{ .seq = 1, .did = did, .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(first); const second = try controlFrame(testing.allocator, .{ .identity = .{ .seq = 2, .did = did, .time = "2026-07-16T00:00:01Z", } }); defer testing.allocator.free(second); try pipeline.submit(first); while (pipeline.gauges().claimed < 1) std.Thread.yield() catch {}; try pipeline.submit(second); try io.sleep(Io.Duration.fromMilliseconds(600), .awake); try testing.expectEqual(@as(usize, 0), collector.len()); verifier.chain_mu.unlock(io); lane_held = false; try pipeline.drainAndStop(); try testing.expectEqualSlices(i64, &.{ 1, 2 }, collector.seqs.items); } test "offline scheduler backpressures the thirty-third active DID" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(io, &path_buf); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var verifier = verify.Verifier.init(testing.allocator, io, "http://offline.invalid", &meta); defer verifier.deinit(); var collector: SeqCollector = .{ .io = io }; defer collector.seqs.deinit(testing.allocator); var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = io, .verifier = &verifier, .emit_ctx = &collector, .emit = SeqCollector.emit, }; try pipeline.start(); defer pipeline.stop(); verifier.chain_mu.lockUncancelable(io); var lane_held = true; defer if (lane_held) verifier.chain_mu.unlock(io); for (0..worker_count) |i| { var did_buf: [64]u8 = undefined; const did = try std.fmt.bufPrint(&did_buf, "did:plc:active-{d}", .{i}); const frame = try controlFrame(testing.allocator, .{ .account = .{ .seq = @intCast(i + 1), .did = did, .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(frame); try pipeline.submit(frame); } while (pipeline.gauges().claimed < worker_count) std.Thread.yield() catch {}; const extra = try controlFrame(testing.allocator, .{ .identity = .{ .seq = worker_count + 1, .did = "did:plc:thirty-third", .time = "2026-07-16T00:00:01Z", } }); defer testing.allocator.free(extra); var started: Io.Event = .unset; var finished: Io.Event = .unset; var submit_error: ?anyerror = null; const Submit = struct { fn run(p: *Pipeline, frame: []const u8, began: *Io.Event, done: *Io.Event, result: *?anyerror) void { began.set(p.io); p.submit(frame) catch |err| { result.* = err; }; done.set(p.io); } }; var submit_future = try io.concurrent(Submit.run, .{ &pipeline, extra, &started, &finished, &submit_error }); defer _ = submit_future.cancel(io); try started.wait(io); try testing.expectError(error.Timeout, finished.waitTimeout(io, .{ .duration = .{ .raw = Io.Duration.fromMilliseconds(100), .clock = .awake }, })); verifier.chain_mu.unlock(io); lane_held = false; try finished.wait(io); _ = submit_future.await(io); try testing.expect(submit_error == null); try pipeline.drainAndStop(); try testing.expectEqual(@as(usize, worker_count + 1), collector.len()); } test "offline per-DID overflow drops the oldest of 64 pending events" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var stats: metrics.Stats = .{}; var collector: SeqCollector = .{ .io = io }; defer collector.seqs.deinit(testing.allocator); var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = io, .verifier = null, .stats = &stats, .emit_ctx = &collector, .emit = SeqCollector.emit, }; defer pipeline.stop(); const did = "did:plc:overflow"; for (1..67) |raw_seq| { const frame = try controlFrame(testing.allocator, .{ .identity = .{ .seq = @intCast(raw_seq), .did = did, .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(frame); try pipeline.submit(frame); } const chain = pipeline.chains.get(did).?; try testing.expectEqual(@as(usize, key_queue_capacity), chain.pending.items.len); try testing.expectEqual(@as(?i64, 3), chain.pending.items[0].seq); try testing.expectEqual(@as(?i64, 66), chain.pending.items[key_queue_capacity - 1].seq); try testing.expect(!pipeline.inflight.contains(2)); try testing.expectEqual(@as(u64, 1), stats.verify_queue_dropped_total.load(.monotonic)); } test "cursor watermark is smallest inflight minus one or global accepted high-water" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var collector: SeqCollector = .{ .io = threaded.io() }; defer collector.seqs.deinit(testing.allocator); var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .emit_ctx = &collector, .emit = SeqCollector.emit, }; defer pipeline.stop(); pipeline.highest_seq = 91; try pipeline.inflight.put(testing.allocator, 40, {}); try pipeline.inflight.put(testing.allocator, 7, {}); try testing.expectEqual(@as(i64, 6), pipeline.cursorAfterBatch()); pipeline.inflight.clearRetainingCapacity(); try testing.expectEqual(@as(i64, 91), pipeline.cursorAfterBatch()); } test "loaded cursor baseline cannot regress on a replayed batch" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var probe: CursorProbe = .{}; var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .emit_ctx = &probe, .emit = CursorProbe.emit, .emit_cursor = CursorProbe.cursor, .cursor_watermark = 100, }; try pipeline.start(); defer pipeline.stop(); const replay = try controlFrame(testing.allocator, .{ .identity = .{ .seq = 50, .did = "did:plc:cursor-replay", .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(replay); try pipeline.submit(replay); try pipeline.drainAndStop(); try testing.expectEqual(@as(usize, 0), probe.calls); } test "graceful drain waits for the final cursor callback" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var probe: CursorProbe = .{}; var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .emit_ctx = &probe, .emit = CursorProbe.emit, .emit_cursor = CursorProbe.cursor, }; try pipeline.start(); defer pipeline.stop(); const event = try controlFrame(testing.allocator, .{ .identity = .{ .seq = 50, .did = "did:plc:cursor-drain", .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(event); try pipeline.submit(event); try pipeline.drainAndStop(); try testing.expectEqual(@as(usize, 1), probe.calls); try testing.expectEqual(@as(i64, 50), probe.last); } test "repair outbox waits for trigger ticket and selects relay order" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var collector: Collector = .{ .allocator = testing.allocator }; var pipeline: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .emit_ctx = &collector, .emit = Collector.emit, }; // Only `after_ticket` is observed by eligibleRepairIndex; these never // enter writer ownership and are deliberately stack-backed. var later: repair.Completion = undefined; later.after_ticket = 9; var earlier: repair.Completion = undefined; earlier.after_ticket = 4; try pipeline.repair_queue.append(testing.allocator, &later); try pipeline.repair_queue.append(testing.allocator, &earlier); defer pipeline.repair_queue.deinit(testing.allocator); pipeline.processed_prefix = 4; try testing.expect(pipeline.eligibleRepairIndex() == null); pipeline.processed_prefix = 5; try testing.expectEqual(@as(?usize, 1), pipeline.eligibleRepairIndex()); pipeline.processed_prefix = 10; try testing.expectEqual(@as(?usize, 0), pipeline.eligibleRepairIndex()); } test "pipeline exposes emit failure without advancing emitted ticket" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const Failing = struct { fn emit(_: *anyopaque, _: zat.FirehoseEvent, _: verify.Result, _: observability.Context) !void { return error.PersistenceFailed; } }; var context: u8 = 0; var stats: metrics.Stats = .{}; var p: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .stats = &stats, .emit_ctx = &context, .emit = Failing.emit, }; try p.start(); defer p.stop(); // A minimal valid #info frame: header then {"name":"fail"}. const frame = &.{ 0xa2, 0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', 0x62, 'o', 'p', 0x01, 0xa1, 0x64, 'n', 'a', 'm', 'e', 0x64, 'f', 'a', 'i', 'l', }; try p.submit(frame); while (p.fatalError() == null) std.Thread.yield() catch {}; try testing.expectEqual(error.PersistenceFailed, p.fatalError().?); const gauges = p.gauges(); try testing.expectEqual(@as(u64, 1), gauges.submitted); try testing.expectEqual(@as(u64, 0), gauges.emitted); try testing.expectEqual(@as(u64, 1), stats.pipeline_submitted.load(.monotonic)); try testing.expectEqual(@as(u64, 1), stats.pipeline_claimed.load(.monotonic)); try testing.expectEqual(@as(u64, 0), stats.pipeline_emitted.load(.monotonic)); try testing.expectEqual(@as(u64, 1), stats.pipeline_fatal.load(.monotonic)); try testing.expectEqual(@as(u64, 1), stats.pipeline_failures.getPtrConst(.emit).load(.monotonic)); try testing.expectError(error.Closed, p.submit(frame)); } test "pipeline classifies cursor persistence failure" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const FailingCursor = struct { fn emit(_: *anyopaque, _: zat.FirehoseEvent, _: verify.Result, _: observability.Context) !void {} fn cursor(_: *anyopaque, _: i64) !void { return error.CursorPersistenceFailed; } }; var context: u8 = 0; var stats: metrics.Stats = .{}; var p: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = null, .stats = &stats, .emit_ctx = &context, .emit = FailingCursor.emit, .emit_cursor = FailingCursor.cursor, }; try p.start(); defer p.stop(); const frame = try controlFrame(testing.allocator, .{ .identity = .{ .seq = 42, .did = "did:plc:cursor-failure", .time = "2026-07-16T00:00:00Z", } }); defer testing.allocator.free(frame); try p.submit(frame); while (p.fatalError() == null) std.Thread.yield() catch {}; try testing.expectEqual(error.CursorPersistenceFailed, p.fatalError().?); try testing.expectEqual(@as(u64, 1), stats.pipeline_fatal.load(.monotonic)); try testing.expectEqual(@as(u64, 1), stats.pipeline_failures.getPtrConst(.cursor).load(.monotonic)); try testing.expectEqual(@as(u64, 0), stats.pipeline_failures.getPtrConst(.emit).load(.monotonic)); } test "malformed frame advances ordered verifier registration" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(threaded.io(), &path_buf); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var verifier = verify.Verifier.init(testing.allocator, threaded.io(), "http://unused", &meta); defer verifier.deinit(); var stats: metrics.Stats = .{}; var collector: Collector = .{ .allocator = testing.allocator }; defer { for (collector.frames.items) |frame| testing.allocator.free(frame); collector.frames.deinit(testing.allocator); } var p: Pipeline = .{ .allocator = testing.allocator, .io = threaded.io(), .verifier = &verifier, .stats = &stats, .emit_ctx = &collector, .emit = Collector.emit, }; try p.start(); defer p.stop(); try p.submit("not cbor"); const valid = &.{ 0xa2, 0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', 0x62, 'o', 'p', 0x01, 0xa1, 0x64, 'n', 'a', 'm', 'e', 0x62, 'o', 'k', }; try p.submit(valid); while (p.gauges().emitted != 2) std.Thread.yield() catch {}; try testing.expectEqual(@as(usize, 1), collector.frames.items.len); try testing.expectEqualStrings("ok", collector.frames.items[0]); try testing.expectEqual(@as(u64, 1), stats.livestream_decode_errors_total.load(.monotonic)); }