summaryrefslogtreecommitdiff
path: root/test/replicas.zig
blob: 9b5c3c3b4b051674aa7ba3ca2ed9dc68953f6b40 (plain) (blame)
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
//! pardes-replicas: one authority and several replicas of a session in one
//! process (src/replica.zig), each client typing at once over its own
//! delayed, jittered link, as monkey.zig's scripts type at a tty, each in a
//! view of its own (src/views.zig) over the text they share; `--shared`
//! puts them all in one, where they clash at every key: a stress of
//! correctness, not a picture of a session.
//!
//! Terminals cross as screen state (src/screen_state.zig): the session's
//! shell pane runs a full-screen program and then a `yes` flood (`--flood`
//! MB of it) while the clients type, its output stepped by the authority
//! and sent to each replica as deltas, once a frame and before any input
//! the authority steps, each replica acknowledging them over its link and
//! asking for the rows it scrolls back into and does not hold.
//!
//!   zig build replicas -Dplatform=tty -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] [--shared]
//!
//! Gates, per seed and RTT: no replica diverges (every confirmed unit's
//! digests agree as it is replayed), and at quiescence every replica's
//! digest is the authority's; every delta a replica applies leaves its
//! terminal what the authority's was at that version, and at quiescence it
//! is the authority's, cell for cell. Reported per RTT: how inputs went
//! (applied at once, stopped at a host call, left to the authority), how
//! units were taken (fast path, rollback for a misprediction or another's
//! input), what a speculative apply, a copy and a rollback cost against a
//! frame, and the terminals': deltas a second, wire bytes a second under
//! the flood, encode a frame (every peer), apply a delta.
const std = @import("std");
const libc = std.c;
const pardes = @import("pardes");
const replica = pardes.replica;
const screen_state = pardes.screen_state;
const Key = pardes.Key;

const gpa = std.heap.c_allocator;
var trace = false;
const frame_us = 16_667;

/// The authority's host: no frames drawn (a replica draws its own), and a
/// pty that echoes what it is written, 2 ms later, as a shell's.
const Host = struct {
    echo: std.ArrayListUnmanaged(struct { pane: u8, bytes: []u8 }) = .empty,

    fn watched(_: ?*anyopaque) bool {
        return false;
    }

    fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
        const h: *Host = @ptrCast(@alignCast(ctx.?));
        h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {};
    }

    fn ignore(_: ?*anyopaque, _: []const u8) void {}

    const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore };

    fn host(h: *Host) pardes.Host {
        return .{ .ctx = h, .vtable = &vtable };
    }
};

const Kind = enum { input, to_authority, to_replica, echo, frame, output, screen_down, screen_up };

const Msg = struct {
    at: u64,
    n: u64,
    kind: Kind,
    who: u16,
    bytes: []u8,

    fn order(_: void, a: Msg, b: Msg) std.math.Order {
        if (a.at != b.at) return std.math.order(a.at, b.at);
        return std.math.order(a.n, b.n);
    }
};

const Link = struct {
    last: u64 = 0,
    /// When a message sent at `now` arrives: half the RTT, jitter on top,
    /// and never before the one sent ahead of it (a stream keeps order).
    fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 {
        const at = @max(l.last + 1, now + one_way + random.uintLessThan(u64, jitter + 1));
        l.last = at;
        return at;
    }
};

const Totals = struct {
    inputs: u64 = 0,
    speculated: u64 = 0,
    stopped: u64 = 0,
    unspeculated: u64 = 0,
    units: u64 = 0,
    fast: u64 = 0,
    mispredicted: u64 = 0,
    foreign: u64 = 0,
    rebases: u64 = 0,
    copies: u64 = 0,
    copy_bytes: u64 = 0,
    divergences: u64 = 0,
    unequal: u64 = 0,
    spec_ns: std.ArrayListUnmanaged(u64) = .empty,
    copy_ns: std.ArrayListUnmanaged(u64) = .empty,
    rollback_ns: std.ArrayListUnmanaged(u64) = .empty,
    // Terminals.
    apply_ns: std.ArrayListUnmanaged(u64) = .empty,
    frame_ns: std.ArrayListUnmanaged(u64) = .empty,
    deltas: u64 = 0,
    delta_bytes: u64 = 0,
    unit_bytes: u64 = 0,
    /// Deltas the replicas applied while the flood ran.
    flood_deltas: u64 = 0,
    flood_us: u64 = 0,
    flood_delta_bytes: u64 = 0,
    flood_unit_bytes: u64 = 0,
    fetched: u64 = 0,
    /// Bytes of rows sent before a step's unit, the step having read them.
    filled_bytes: u64 = 0,
    resets: u64 = 0,
    screens_wrong: u64 = 0,
    screens_checked: u64 = 0,

    fn add(t: *Totals, s: *const replica.Stats) !void {
        t.inputs += s.inputs;
        t.speculated += s.speculated;
        t.stopped += s.stopped;
        t.unspeculated += s.unspeculated;
        t.units += s.units;
        t.fast += s.fast;
        t.mispredicted += s.mispredicted;
        t.foreign += s.foreign;
        t.rebases += s.rebases;
        t.copies += s.copies;
        t.copy_bytes += s.copy_bytes;
        try t.spec_ns.appendSlice(gpa, s.spec_ns.items);
        try t.copy_ns.appendSlice(gpa, s.copy_ns.items);
        try t.rollback_ns.appendSlice(gpa, s.rollback_ns.items);
        try t.apply_ns.appendSlice(gpa, s.apply_ns.items);
    }
};

/// One client's next input: monkey.zig's mix, as events, and now and then
/// a wheel over the shell pane, which scrolls its history into view.
fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16) pardes.Event {
    const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()";
    const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC";
    switch (random.uintLessThan(u8, 43)) {
        0...15 => {
            buf[0] = typed[random.uintLessThan(usize, typed.len)];
            return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
        },
        16...27 => {
            buf[0] = normal[random.uintLessThan(usize, normal.len)];
            return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
        },
        28...31 => return .{ .key = .{ .cp = Key.escape } },
        32 => return .{ .key = .{ .cp = Key.enter } },
        33 => return .{ .key = .{ .cp = Key.backspace } },
        34 => return .{ .key = .{ .cp = switch (random.uintLessThan(u8, 4)) {
            0 => Key.up,
            1 => Key.down,
            2 => Key.left,
            else => Key.right,
        } } },
        35 => {
            const n = random.intRangeAtMost(usize, 1, 24);
            for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)];
            return .{ .paste = buf[0..n] };
        },
        36 => return .{ .command = switch (random.uintLessThan(u8, 4)) {
            0 => "Newcol",
            1 => "Zerox",
            2 => "Undo",
            else => "Redo",
        } },
        37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } },
        38 => return .{ .mouse = .{ .button = .left, .kind = .press, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } },
        39 => return .{ .mouse = .{ .button = .left, .kind = .release, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } },
        // Out of a shell's tty mode and back: its text, a cursor and
        // selections over it.
        40 => return .{ .key = .{ .cp = 'b', .ctrl = true } },
        else => {
            const at = wheel_at orelse return .{ .key = .{ .cp = Key.escape } };
            return .{ .mouse = .{ .button = if (random.uintLessThan(u8, 3) == 0) .wheel_down else .wheel_up, .kind = .press, .col = at[0], .row = at[1] } };
        },
    }
}

fn writeFile(path: [:0]const u8, lines: usize) !void {
    const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
    if (fd < 0) return error.OpenFailed;
    defer _ = libc.close(fd);
    var line: [80]u8 = undefined;
    for (0..lines) |n| {
        const text = try std.fmt.bufPrint(&line, "const value_{d:0>4} = {d}; // a line to edit\n", .{ n, n *% 7919 });
        if (libc.write(fd, text.ptr, text.len) != @as(isize, @intCast(text.len))) return error.WriteFailed;
    }
}

const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, shared: bool, flood_mb: u64 };

/// The terminal pane's screen as a hash of screen_state's dump of it.
fn screenHash(t: *pardes.panes.terminal.VtSlot) u64 {
    var buf: [8192]u8 = undefined;
    var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf);
    screen_state.dumpScreen(t, &h.writer) catch {};
    h.writer.flush() catch {};
    return h.hasher.final();
}

fn run(r: Run, dir: []const u8, totals: *Totals) !void {
    if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms });
    var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms);
    const random = prng.random();
    var host: Host = .{};
    defer {
        for (host.echo.items) |e| gpa.free(e.bytes);
        host.echo.deinit(gpa);
    }
    var paths: [3][256:0]u8 = undefined;
    for (&paths, 0..) |*p, i| {
        const path = try std.fmt.bufPrintSentinel(p, "{s}/f{d}.zig", .{ dir, i }, 0);
        try writeFile(path, 60 + 40 * i);
    }
    // The tty's own boot (a raw shell, a text pane under it), then three
    // files looked at: keys go to the last, a pane's shell echoes.
    const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true);
    defer a.deinit();
    var screens: replica.Screens = .init(gpa);
    defer screens.deinit(a.core);
    const first = try gpa.dupe(u8, try a.unit(0, 0));
    defer gpa.free(first);
    var reps: [8]*replica.Replica = undefined;
    var peers: [8]u16 = undefined;
    for (reps[0..r.clients], peers[0..r.clients], 1..) |*rp, *peer, id| {
        rp.* = try replica.Replica.init(gpa, @intCast(id), first, true);
        peer.* = try screens.addPeer();
    }
    defer for (reps[0..r.clients]) |rp| rp.deinit();
    const shell: u8 = for (a.core.panes, 0..) |slot, id| {
        if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
    } else return error.NoShell;
    for (&paths) |*path| {
        var line: [300]u8 = undefined;
        const unit = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) });
        for (reps[0..r.clients]) |rp| rp.confirm(unit);
    }
    // Each client a view of its own (src/views.zig), the first the
    // session's; or, --shared, every client in the one.
    if (!r.shared) for (reps[1..r.clients], 2..) |rp, id| {
        const opened = try a.openView(@intCast(id));
        rp.view = opened.view;
        for (reps[0..r.clients]) |each| each.confirm(opened.unit);
    };
    // Where a wheel over the shell lands in the session's view (the first
    // client's); the others' views put it elsewhere, and their wheels hit
    // whatever is there.
    const sr = a.core.rects[shell];
    const wheel_at: ?[2]u16 = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null;

    // What the shell's program prints: a full-screen program, a shell's
    // session (prompts, titles, directories, a clear now and then), then a
    // flood of `yes`, read 4 KB at a time as a pty gives it.
    const tui = try screen_state.tuiStream(gpa);
    defer gpa.free(tui);
    const session = try screen_state.shellStream(gpa);
    defer gpa.free(session);
    const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3));
    defer gpa.free(yes);
    const tui_at: u64 = 400_000;
    const session_at: u64 = 1_000_000;
    const flood_at: u64 = 2_500_000;
    var flood_end: u64 = 0;
    var program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{};
    // The authority's version of each terminal, as its screen showed then.
    var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty;
    defer versions.deinit(gpa);
    var flood_deltas: [8]u64 = @splat(0);

    var queue: std.PriorityQueue(Msg, void, Msg.order) = .empty;
    defer {
        while (queue.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes);
        queue.deinit(gpa);
    }
    var n: u64 = 0;
    const one_way = r.rtt_ms * 1000 / 2;
    const jitter = one_way / 10;
    var up: [8]Link = @splat(.{});
    var down: [8]Link = @splat(.{});
    var left: [8]usize = @splat(r.steps);
    var typing: usize = r.clients;
    const push = struct {
        fn f(q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, m: Msg) !void {
            var mm = m;
            mm.n = nn.*;
            nn.* += 1;
            try q.push(gpa, mm);
        }
    }.f;
    // Each client's first input, soon; the programs; the first frame.
    for (0..r.clients) |c| try push(&queue, &n, .{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .input, .who = @intCast(c + 1), .bytes = &.{} });
    try push(&queue, &n, .{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} });
    try push(&queue, &n, .{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} });
    try push(&queue, &n, .{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} });
    try push(&queue, &n, .{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
    var frames_left: u32 = 0;
    var flood_units: u64 = 0;

    // What each peer is owed of the terminals, onto its link: before the
    // authority steps an input, and once a frame.
    var owed: std.ArrayListUnmanaged([]u8) = .empty;
    defer owed.deinit(gpa);
    const flushAll = struct {
        fn f(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *std.ArrayListUnmanaged([]u8), q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, now: u64, dl: []Link, rnd: std.Random, ow: u64, jt: u64, vs: *std.AutoHashMapUnmanaged(u64, u64), tot: *Totals) !void {
            for (ps, 0..) |peer, c| {
                list.clearRetainingCapacity();
                try sc.flush(core, peer, list);
                for (list.items) |bytes| {
                    tot.deltas += 1;
                    tot.delta_bytes += bytes.len;
                    try push(q, nn, .{ .at = dl[c].arrive(rnd, now, ow, jt), .n = 0, .kind = .screen_down, .who = @intCast(c + 1), .bytes = bytes });
                }
            }
            // Each version as the authority's screen showed it.
            for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| {
                const key = @as(u64, tr.serial) << 32 | tr.track.version;
                if (tr.track.version == 0 or vs.contains(key)) continue;
                _ = core.panes[id] orelse continue;
                try vs.put(gpa, key, screenHash(&tr.state.vt));
            };
        }
    }.f;

    while (queue.pop()) |m| {
        defer if (m.bytes.len > 0) gpa.free(m.bytes);
        switch (m.kind) {
            .input => {
                const c = m.who - 1;
                var buf: [64]u8 = undefined;
                const ev = nextEvent(random, &buf, if (c == 0) wheel_at else null);
                const before = reps[c].stats;
                const msg = try gpa.dupe(u8, try reps[c].input(ev));
                if (trace) std.debug.print("{d} ms client {d}: {t} {s} -> {s}\n", .{ m.at / 1000, m.who, ev, switch (ev) {
                    .key => |k| k.text,
                    .paste => |t| t,
                    .command => |t| t,
                    else => "",
                }, if (reps[c].stats.speculated > before.speculated) "applied" else if (reps[c].stats.stopped > before.stopped) "STOPPED" else if (reps[c].stats.unspeculated > before.unspeculated) "view" else "waits" });
                try push(&queue, &n, .{ .at = up[c].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .to_authority, .who = m.who, .bytes = msg });
                left[c] -= 1;
                if (left[c] > 0) {
                    // A typist: keys 50-200 ms apart, a pause now and then.
                    const gap: u64 = if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000);
                    try push(&queue, &n, .{ .at = m.at + gap, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
                } else typing -= 1;
            },
            .to_authority, .echo, .output => {
                const unit = switch (m.kind) {
                    .echo => echo: {
                        a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } });
                        break :echo null;
                    },
                    .output => out: {
                        // The program's next read, 4 KB, then the next a
                        // fraction of a millisecond on (ghostty's pace).
                        if (program.at == program.bytes.len) {
                            program = .{ .bytes = switch (m.who) {
                                0 => tui,
                                1 => yes,
                                else => session,
                            } };
                        }
                        const k = @min(program.bytes.len - program.at, if (m.who == 1) @as(usize, 4096) else 700);
                        const chunk = program.bytes[program.at..][0..k];
                        program.at += k;
                        if (program.at < program.bytes.len)
                            try push(&queue, &n, .{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} })
                        else if (m.who == 1) flood_end = m.at;
                        if (m.who == 1) flood_units += 1;
                        a.output(.{ .output = .{ .pane = shell, .bytes = chunk } });
                        break :out null;
                    },
                    else => in: {
                        // The authority's own steps since the last unit, and
                        // the terminals as they are: what the input's step
                        // reads, before it is stepped.
                        if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0, &screens, a.core, peers[0..r.clients]);
                        try flushAll(&screens, a.core, peers[0..r.clients], &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, totals);
                        break :in try a.take(m.bytes);
                    },
                };
                if (unit) |u| try sendUnit(&queue, &n, u, m.at, down[0..r.clients], random, one_way, jitter, totals, false, &screens, a.core, peers[0..r.clients]);
                for (host.echo.items) |e| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes });
                host.echo.clearRetainingCapacity();
            },
            .frame => {
                if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0, &screens, a.core, peers[0..r.clients]);
                const t0 = screens.encode_ns;
                const before = totals.delta_bytes;
                try flushAll(&screens, a.core, peers[0..r.clients], &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, totals);
                if (m.at >= flood_at and (flood_end == 0 or m.at <= flood_end)) {
                    totals.flood_delta_bytes += totals.delta_bytes - before;
                    try totals.frame_ns.append(gpa, screens.encode_ns - t0);
                }
                // Frames go on while anything moves, and a second after.
                const busy = typing > 0 or flood_end == 0 or queue.count() > 0;
                frames_left = if (busy) 60 else frames_left -| 1;
                if (frames_left > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
            },
            .to_replica, .screen_down => {
                const c = m.who - 1;
                const rp = reps[c];
                if (m.kind == .to_replica) {
                    rp.confirm(m.bytes);
                    rp.settle();
                } else if (rp.screen(m.bytes)) |reply| {
                    const pane = m.bytes[0];
                    if (reply[5] == 1) {
                        // Applied: the screen is the authority's at that version.
                        const sc = rp.screens[pane].?;
                        const vt = &rp.core().panes[pane].?.terminal.?.vt;
                        totals.screens_checked += 1;
                        if (versions.get(@as(u64, sc.serial) << 32 | sc.rep.seq)) |want| {
                            if (want != screenHash(vt)) {
                                totals.screens_wrong += 1;
                                std.debug.print("seed {d} rtt {d} ms: replica {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, sc.rep.seq });
                            }
                        } else totals.screens_wrong += 1;
                        // Deltas while the flood runs (an RTT/2 behind it).
                        if (m.at >= flood_at + one_way and (flood_end == 0 or m.at <= flood_end + one_way)) flood_deltas[c] += 1;
                    } else totals.resets += 1;
                    try push(&queue, &n, .{ .at = up[c].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = m.who, .bytes = try gpa.dupe(u8, reply) });
                }
                if (rp.screenRequest()) |req| try push(&queue, &n, .{ .at = up[c].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = m.who, .bytes = try gpa.dupe(u8, req) });
            },
            .screen_up => {
                const c = m.who - 1;
                if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little);
                if (try screens.take(a.core, peers[c], m.bytes)) |answer| try push(&queue, &n, .{ .at = down[c].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = m.who, .bytes = answer });
            },
        }
    }
    totals.flood_us += flood_end -| flood_at;
    for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d;
    const want = replica.digestOf(a);
    for (reps[0..r.clients], 1..) |rp, id| {
        try totals.add(&rp.stats);
        if (rp.diverged) |why| {
            totals.divergences += 1;
            std.debug.print("seed {d} rtt {d} ms: replica {d} diverged: {s}\n", .{ r.seed, r.rtt_ms, id, why });
        } else if (!rp.quiet() or rp.digest() != want) {
            totals.unequal += 1;
            std.debug.print("seed {d} rtt {d} ms: replica {d} at quiescence: {s}\n", .{ r.seed, r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" });
        }
        // At quiescence, every terminal the authority's, cell for cell.
        for (a.core.panes, 0..) |slot, pid| {
            const pane = slot orelse continue;
            const state = pane.terminal orelse continue;
            const mine = (rp.core().panes[pid] orelse {
                totals.unequal += 1;
                continue;
            }).terminal orelse continue;
            if (screenHash(&state.vt) != screenHash(&mine.vt)) {
                totals.unequal += 1;
                std.debug.print("seed {d} rtt {d} ms: replica {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid });
            }
        }
    }
}

/// A unit of the authority's to every replica, down its link: first the
/// rows of its terminals its step read that a replica holds as holes.
fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void {
    var rows: std.ArrayListUnmanaged([]u8) = .empty;
    defer rows.deinit(gpa);
    for (down, peers, 1..) |*l, peer, who| {
        rows.clearRetainingCapacity();
        try screens.fill(core, peer, &rows);
        for (rows.items) |bytes| {
            totals.filled_bytes += bytes.len;
            try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes });
            n.* += 1;
        }
    }
    screens.filled(core);
    totals.unit_bytes += unit.len * down.len;
    if (flooding) totals.flood_unit_bytes += unit.len * down.len;
    for (down, 1..) |*l, who| {
        try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .to_replica, .who = @intCast(who), .bytes = try gpa.dupe(u8, unit) });
        n.* += 1;
    }
}

fn pct(samples: []u64, p: usize) u64 {
    if (samples.len == 0) return 0;
    std.mem.sort(u64, samples, {}, std.sort.asc(u64));
    return samples[@min(samples.len - 1, samples.len * p / 100)];
}

pub fn main(init: std.process.Init) !void {
    const args = try init.minimal.args.toSlice(init.arena.allocator());
    var seeds: u64 = 4;
    var first: u64 = 0;
    var steps: usize = 120;
    var clients: u16 = 3;
    var rtts: []const u64 = &.{ 30, 80, 207 };
    var shared = false;
    var flood_mb: u64 = 8;
    var rtt_buf: [8]u64 = undefined;
    var i: usize = 1;
    while (i < args.len) : (i += 1) {
        const name = args[i];
        if (std.mem.eql(u8, name, "--shared")) {
            shared = true;
            continue;
        }
        if (i + 1 >= args.len) return error.MissingValue;
        i += 1;
        const value = args[i];
        if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--rtt")) {
            var it = std.mem.tokenizeScalar(u8, value, ',');
            var k: usize = 0;
            while (it.next()) |v| : (k += 1) rtt_buf[k] = try std.fmt.parseInt(u64, v, 10);
            rtts = rtt_buf[0..k];
        } else return error.UnknownOption;
    }
    trace = libc.getenv("PARDES_REPLICA_TRACE") != null;
    if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff;
    var dir_buf: [256]u8 = undefined;
    const tmp = std.mem.span(libc.getenv("TMPDIR") orelse "/tmp");
    const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) });
    try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir);
    defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {};
    var failed = false;
    std.debug.print("{d} seeds x {d} inputs from each of {d} clients, {s}, a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, if (shared) "sharing one view" else "a view each", flood_mb, frame_us });
    std.debug.print(" rtt  inputs  at-once stopped view   units   fast  rollback(mis+foreign) rate  rebase  spec p50/p99   copy p50/p99 (KB)  rollback p50/p99  diverged unequal\n", .{});
    var term_lines: std.ArrayList(u8) = .empty;
    defer term_lines.deinit(gpa);
    for (rtts) |rtt| {
        var t: Totals = .{};
        for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .shared = shared, .flood_mb = flood_mb }, dir, &t);
        const rollbacks = t.mispredicted + t.foreign;
        std.debug.print("{d:>4}  {d:>6}  {d:>7} {d:>7} {d:>4}  {d:>6} {d:>6}  {d:>6} ({d}+{d})  {d:>5.1}%  {d:>6}  {d:>5}/{d:<6}  {d:>5}/{d:<5} ({d})  {d:>7}/{d:<7}  {d:>8} {d:>7}\n", .{
            rtt,                                 t.inputs,                                                                              t.speculated,
            t.stopped,                           t.unspeculated,                                                                        t.units,
            t.fast,                              rollbacks,                                                                             t.mispredicted,
            t.foreign,                           @as(f64, @floatFromInt(rollbacks)) * 100 / @as(f64, @floatFromInt(@max(t.inputs, 1))), t.rebases,
            pct(t.spec_ns.items, 50) / 1000,     pct(t.spec_ns.items, 99) / 1000,                                                       pct(t.copy_ns.items, 50) / 1000,
            pct(t.copy_ns.items, 99) / 1000,     t.copy_bytes / @max(t.copies, 1) / 1024,                                               pct(t.rollback_ns.items, 50) / 1000,
            pct(t.rollback_ns.items, 99) / 1000, t.divergences,                                                                         t.unequal,
        });
        const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6;

        try term_lines.print(gpa, "{d:>4}  {d:>7.1}  {d:>9.0}  {d:>9.0}  {d:>5}/{d:<5}  {d:>5}/{d:<5}  {d:>7}  {d:>9}  {d:>6}  {d:>6}/{d:<6}\n", .{
            rtt,
            @as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)),
            @as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
            @as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
            pct(t.frame_ns.items, 50) / 1000,
            pct(t.frame_ns.items, 99) / 1000,
            pct(t.apply_ns.items, 50) / 1000,
            pct(t.apply_ns.items, 99) / 1000,
            t.fetched,
            t.filled_bytes / 1024,
            t.resets,
            t.screens_checked,
            t.screens_wrong,
        });
        if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0) failed = true;
    }
    std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{});
    std.debug.print(" rtt  deltas/s  delta B/s   unit B/s   encode p50/p99  apply p50/p99  fetched  filled KB  resets  checked/wrong\n{s}", .{term_lines.items});
    if (failed) std.process.exit(1);
}