summaryrefslogtreecommitdiff
path: root/src/replica.zig
blob: a18391d49e9e5a622aa105db6f6425787749c01e (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
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
//! A session's replicas (docs/next-daemon.md, phase 5 part A): the authority
//! orders every input and records what its core consumed (src/tape.zig);
//! each replica runs a core of its own, applies its own inputs at once, and
//! takes the authority's stream as the truth.
//!
//! A replica's state is the confirmed position plus its own pending inputs,
//! applied on top (a speculation, recorded as the authority would record
//! it). For each unit of the authority's stream, in order:
//!   - its own pending head, recorded the same (inputs, host calls and
//!     answers): the head goes, nothing is redone (the fast path);
//!   - else the rollback copy is put back (src/rollback.zig), the confirmed
//!     units since it are replayed, then this one, and the pending inputs
//!     are applied again.
//! A speculation that reaches a host call or a syscall (a Host function,
//! a `tape.site`) or an emulator (the authority's) stops: the copy is put
//! back and the input waits for the authority's answer, one RTT late but
//! never wrong. Clock and environment reads (`tape.value`) are made here,
//! and the comparison catches a guess the authority did not share.
//!
//! No transport: messages are bytes in and out. A client's input is its
//! id, a sequence number and the event as detached/wire.zig frames it; a
//! unit is the input's origin (0 for the authority's own: a pty's output, a
//! tick), its sequence number and the authority's tape of it.
const std = @import("std");
const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const tape = @import("tape.zig");
const rollback = @import("rollback.zig");
const walk = @import("walk.zig");
const wire = @import("detached/wire.zig");
const screen_state = @import("screen_state.zig");
const terminal = pardes.panes.terminal;
const Allocator = std.mem.Allocator;
const Pardes = pardes.Pardes;

const checked = builtin.mode == .debug or builtin.mode == .safe;
const head_len = 6; // origin or client: u16le, seq: u32le
/// Confirmed units fast-pathed under one copy before it is taken afresh:
/// a rollback replays them all.
const rebase_after = 32;

fn header(buf: []u8, who: u16, seq: u32) void {
    std.mem.writeInt(u16, buf[0..2], who, .little);
    std.mem.writeInt(u32, buf[2..6], seq, .little);
}

pub const Unit = struct { origin: u16, seq: u32, tape: []const u8 };

pub fn parseUnit(msg: []const u8) ?Unit {
    if (msg.len < head_len) return null;
    return .{ .origin = std.mem.readInt(u16, msg[0..2], .little), .seq = std.mem.readInt(u32, msg[2..6], .little), .tape = msg[head_len..] };
}

pub const Input = struct { client: u16, seq: u32, event: pardes.Event };

/// A client's input message; its event borrows `msg`.
pub fn parseInput(msg: []const u8) ?Input {
    if (msg.len < head_len) return null;
    const f = (wire.framed(msg[head_len..]) catch return null) orelse return null;
    const ev = switch (wire.decodeClient(f.tag, f.payload) catch return null) {
        .event => |ev| ev,
        else => return null,
    };
    return .{ .client = std.mem.readInt(u16, msg[0..2], .little), .seq = std.mem.readInt(u32, msg[2..6], .little), .event = ev };
}

/// The core whose tape is `t`, stepped: tape.on is process-wide, and so
/// are syntax.zig's held trees, so one process can step several.
const Stepping = struct {
    tape: ?*tape.Tape,
    trees: ?*pardes.syntax.HeldTrees,

    fn begin(t: *tape.Tape, epoch: ?*rollback.Epoch) Stepping {
        const was: Stepping = .{ .tape = tape.on, .trees = pardes.syntax.held_trees };
        tape.on = t;
        rollback.Epoch.select(epoch);
        return was;
    }

    fn end(was: Stepping) void {
        tape.on = was.tape;
        pardes.syntax.held_trees = was.trees;
    }
};

fn nowNs() u64 {
    return pardes.FrameStats.nowNs();
}

// ---- the authority ----

pub const Authority = struct {
    gpa: Allocator,
    t: tape.Tape,
    core: *Pardes,
    host: pardes.Host,
    out: std.ArrayListUnmanaged(u8) = .empty,
    seq: u32 = 0,
    /// Each client's view (src/views.zig): its own layout, focus and
    /// cursors over the session's text. The first client has the session's.
    view_of: [64]u8 = @splat(0),
    /// Steps of its own taken since the last unit (`output`): one unit,
    /// `pending`, sent before the next input it steps and at a frame.
    batched: u32 = 0,

    /// A session booted with `opts`; `unit` is its first, which a replica
    /// is made from.
    /// `screens`: its terminals cross as screen state (`Screens`), not as
    /// their pty's bytes.
    pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host, screens: bool) !*Authority {
        // A replay gives its core every allocator (tape.zig), and a digest
        // tells an allocator from none.
        var opts = options;
        opts.image_allocator = opts.image_allocator orelse gpa;
        opts.pdf_allocator = opts.pdf_allocator orelse gpa;
        opts.tree_sitter_allocator = opts.tree_sitter_allocator orelse gpa;
        opts.frame_allocator = opts.frame_allocator orelse gpa;
        const a = try gpa.create(Authority);
        errdefer gpa.destroy(a);
        a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host };
        a.t.screen_state = screens;
        // One word a digest: every pty read is a unit.
        a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null;
        const was = Stepping.begin(&a.t, null);
        defer was.end();
        a.core = try Pardes.init(gpa, opts);
        a.core.host = host;
        a.core.pump(host) catch {};
        return a;
    }

    pub fn deinit(a: *Authority) void {
        const was = Stepping.begin(&a.t, null);
        a.core.deinit();
        was.end();
        tape.release(&a.t);
        a.out.deinit(a.gpa);
        a.gpa.destroy(a);
    }

    /// What was recorded since the last unit, as one (the boot's, a setup's
    /// done straight on the core).
    pub fn unit(a: *Authority, origin: u16, seq: u32) ![]const u8 {
        a.out.clearRetainingCapacity();
        try a.out.appendNTimes(a.gpa, 0, head_len);
        header(a.out.items, origin, seq);
        try a.out.appendSlice(a.gpa, tape.taken(&a.t));
        tape.clearTaken(&a.t);
        return a.out.items;
    }

    /// An input of the authority's own (a pty's output, a tick, a setup's
    /// command), recorded into the unit being made.
    pub fn apply(a: *Authority, ev: pardes.Event) void {
        const was = Stepping.begin(&a.t, null);
        a.core.update(ev);
        a.core.pump(a.host) catch {};
        was.end();
    }

    /// One of the authority's own inputs, as its unit.
    pub fn local(a: *Authority, ev: pardes.Event) ![]const u8 {
        std.debug.assert(a.batched == 0); // `pending` first: units keep the order steps took
        a.apply(ev);
        a.seq += 1;
        return a.unit(0, a.seq);
    }

    /// A step of its own (a pty's output) into the open batch: under a
    /// flood a replica gets a unit a frame, not one a read (each unit of the
    /// authority's rolls back a replica's pending inputs), and its digest
    /// once a unit.
    pub fn output(a: *Authority, ev: pardes.Event) void {
        a.t.no_digest = true;
        defer a.t.no_digest = false;
        a.apply(ev);
        a.batched += 1;
    }

    /// The open batch as a unit, or null: what the host sends before it
    /// steps any other input, and once a frame.
    pub fn pending(a: *Authority) !?[]const u8 {
        if (a.batched == 0) return null;
        a.batched = 0;
        const was = Stepping.begin(&a.t, null);
        tape.digestHere(&a.t);
        was.end();
        a.seq += 1;
        return try a.unit(0, a.seq);
    }

    /// A view of its own for `client`, as its unit; which it is.
    pub fn openView(a: *Authority, client: u16) !struct { view: u8, unit: []const u8 } {
        std.debug.assert(a.batched == 0);
        const was = Stepping.begin(&a.t, null);
        const k = a.core.openView() orelse {
            was.end();
            return error.TooManyViews;
        };
        a.core.pump(a.host) catch {};
        was.end();
        a.view_of[client] = k;
        a.seq += 1;
        return .{ .view = k, .unit = try a.unit(0, a.seq) };
    }

    /// One client's input, applied in the order it came, in its view: the
    /// unit every replica takes.
    pub fn take(a: *Authority, msg: []const u8) ![]const u8 {
        std.debug.assert(a.batched == 0);
        const in = parseInput(msg) orelse return error.BadInput;
        const was = Stepping.begin(&a.t, null);
        a.core.toView(a.view_of[in.client]);
        a.core.update(in.event);
        a.core.pump(a.host) catch {};
        was.end();
        return a.unit(in.client, in.seq);
    }
};

// ---- terminals as screen state (src/screen_state.zig) ----
//
// A message of either side is u8 pane, u32 the pane's serial (a slot's
// next pane is another), u8 kind, and the kind's bytes:
//   to a replica:   kind 1, a delta; kind 2, rows it asked for (encodeRows);
//   to the authority: kind 1, an acknowledgement (u32 seq); kind 2, a
//                   request for rows (u64 lo, u64 hi, absolute); kind 3, a
//                   delta refused: start this terminal afresh.
// The authority sends a peer what it is owed (`Screens.flush`) before it
// steps any input but a pty's output, and once a frame; a replica takes
// them in that order between units (`Replica.screen`). So a step a replica
// replays reads the terminal its authority's read.

const kind_delta = 1;
const kind_rows = 2;
const kind_ack = 1;
const kind_reset = 3;

const ScreenMsg = struct { pane: u8, serial: u32, kind: u8, payload: []const u8 };

fn parseScreen(msg: []const u8) ?ScreenMsg {
    if (msg.len < 6) return null;
    return .{ .pane = msg[0], .serial = std.mem.readInt(u32, msg[1..5], .little), .kind = msg[5], .payload = msg[6..] };
}

fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, serial: u32, kind: u8) !void {
    var head: [6]u8 = undefined;
    head[0] = pane;
    std.mem.writeInt(u32, head[1..5], serial, .little);
    head[5] = kind;
    try out.appendSlice(gpa, &head);
}

/// The authority's side of its replicas' terminals: a track each terminal
/// pane, and what each peer was sent of it.
pub const Screens = struct {
    gpa: Allocator,
    enc: screen_state.Encoder,
    tracks: [pardes.MAX_PANES]?Tracked = @splat(null),
    peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty,
    out: std.ArrayListUnmanaged(u8) = .empty,
    /// Nanoseconds: what each flush spent encoding, for every peer.
    encode_ns: u64 = 0,

    const Tracked = struct { serial: u32, state: *terminal.State, track: screen_state.Track };
    const PeerOf = struct { serial: u32 = 0, peer: screen_state.Peer = .{} };

    pub fn init(gpa: Allocator) Screens {
        return .{ .gpa = gpa, .enc = .init(gpa) };
    }

    /// `core` is the session's, its terminals still there.
    pub fn deinit(s: *Screens, core: *Pardes) void {
        for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| tr.track.deinit(s.gpa, if (s.live(core, id, tr)) &tr.state.vt else null);
        for (s.peers.items) |p| s.gpa.destroy(p);
        s.peers.deinit(s.gpa);
        s.out.deinit(s.gpa);
        s.enc.deinit();
    }

    fn live(_: *const Screens, core: *Pardes, id: usize, tr: *const Tracked) bool {
        const pane = core.panes[id] orelse return false;
        return pane.serial == tr.serial and pane.terminal == tr.state;
    }

    /// A new peer, with nothing yet: its first delta of each terminal
    /// starts it afresh.
    pub fn addPeer(s: *Screens) !u16 {
        const p = try s.gpa.create([pardes.MAX_PANES]PeerOf);
        p.* = @splat(.{});
        try s.peers.append(s.gpa, p);
        return @intCast(s.peers.items.len - 1);
    }

    /// What `peer` is owed of every terminal, each a message onto `out`
    /// (owned): nothing for one it has as it is, or with `bound` in flight.
    pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void {
        const t0 = nowNs();
        defer s.encode_ns += nowNs() - t0;
        for (core.panes, 0..) |slot, id| {
            const pane = slot orelse continue;
            const state = pane.terminal orelse continue;
            const tr = try s.track(core, id);
            const pp = &s.peers.items[peer][id];
            if (pp.serial != pane.serial) pp.* = .{ .serial = pane.serial };
            var marks: [terminal.marks_len]u8 = undefined;
            s.out.clearRetainingCapacity();
            try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta);
            var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out);
            defer s.out = w.toArrayList();
            if (!try screen_state.encode(&s.enc, &tr.track, &pp.peer, &state.vt, state.changes, terminal.marksOf(state, &marks), &w.writer)) continue;
            try out.append(s.gpa, try s.gpa.dupe(u8, w.written()));
        }
    }

    fn track(s: *Screens, core: *Pardes, id: usize) !*Tracked {
        const pane = core.panes[id].?;
        if (s.tracks[id]) |*tr| {
            if (s.live(core, id, tr)) return tr;
            // Its pane closed (its emulator, the pin with it, gone).
            tr.track.deinit(s.gpa, null);
        }
        s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = .init(s.gpa) };
        return &s.tracks[id].?;
    }

    /// A peer's message (`Replica.screen`'s, `Replica.screenRequest`'s):
    /// an answer for it (owned), or null.
    pub fn take(s: *Screens, core: *Pardes, peer: u16, msg: []const u8) !?[]u8 {
        const m = parseScreen(msg) orelse return null;
        const pane = core.panes[m.pane] orelse return null;
        if (pane.serial != m.serial) return null;
        const state = pane.terminal orelse return null;
        const pp = &s.peers.items[peer][m.pane];
        if (pp.serial != m.serial) return null;
        switch (m.kind) {
            kind_ack => if (m.payload.len == 4) pp.peer.ack(std.mem.readInt(u32, m.payload[0..4], .little)),
            kind_reset => pp.peer.reset(),
            kind_rows => {
                if (m.payload.len != 16) return null;
                const tr = try s.track(core, m.pane);
                s.out.clearRetainingCapacity();
                try writeScreenHead(&s.out, s.gpa, m.pane, m.serial, kind_rows);
                var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out);
                defer s.out = w.toArrayList();
                try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer);
                return try s.gpa.dupe(u8, w.written());
            },
            else => {},
        }
        return null;
    }
};

// ---- a replica ----

pub const Stats = struct {
    inputs: u32 = 0,
    /// Applied at once and clean.
    speculated: u32 = 0,
    /// Stopped at a host call, a syscall or an emulator: waits one RTT.
    stopped: u32 = 0,
    /// Not tried: an event of the view's (a resize, the pointer), phase 4's.
    unspeculated: u32 = 0,
    /// The authority's unit was the pending head, recorded the same.
    fast: u32 = 0,
    /// The copy put back: the head recorded otherwise (a guess of the clock
    /// the authority did not share), or another's unit first.
    mispredicted: u32 = 0,
    foreign: u32 = 0,
    rebases: u32 = 0,
    units: u32 = 0,
    /// Nanoseconds: one speculative apply, a copy taken, a rollback (the
    /// copy put back, the confirmed units replayed, the pending reapplied).
    spec_ns: std.ArrayListUnmanaged(u64) = .empty,
    copy_ns: std.ArrayListUnmanaged(u64) = .empty,
    rollback_ns: std.ArrayListUnmanaged(u64) = .empty,
    copy_bytes: u64 = 0,
    copies: u32 = 0,
    /// Nanoseconds: a terminal's delta applied.
    apply_ns: std.ArrayListUnmanaged(u64) = .empty,

    pub fn deinit(s: *Stats, gpa: Allocator) void {
        s.spec_ns.deinit(gpa);
        s.copy_ns.deinit(gpa);
        s.rollback_ns.deinit(gpa);
        s.apply_ns.deinit(gpa);
    }
};

const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null };

pub const Replica = struct {
    gpa: Allocator,
    id: u16,
    /// Its own view of the session (Authority.openView's).
    view: u8 = 0,
    /// The core's allocator; its tapes and the engine's own lists are not.
    epoch: rollback.Epoch = .{},
    t: tape.Tape,
    copy: rollback.Copy = .{},
    pending: std.ArrayListUnmanaged(Pending) = .empty,
    /// pending[0..applied] are applied on top of the confirmed position.
    applied: usize = 0,
    /// The pending input that waits for the authority (it stopped at a host
    /// call, or is the view's), and those after it with it.
    blocked: ?u32 = null,
    /// Confirmed units fast-pathed since the copy was taken.
    since: std.ArrayListUnmanaged([]u8) = .empty,
    /// Pending inputs to apply again (after a rollback).
    dirty: bool = false,
    next_seq: u32 = 1,
    stats: Stats = .{},
    diverged: ?[]const u8 = null,
    out: std.ArrayListUnmanaged(u8) = .empty,
    /// Nanoseconds of the rollback being made, until its reapply.
    recovering: ?u64 = null,
    /// Its terminals' screen state, as the authority's deltas made it.
    screens: [pardes.MAX_PANES]?ScreenOf = @splat(null),
    screen_out: std.ArrayListUnmanaged(u8) = .empty,

    const ScreenOf = struct {
        serial: u32,
        rep: screen_state.Replica = .{},
        /// A delta was refused, and a reset asked for: those in flight
        /// before it are refused unasked.
        refused: bool = false,
        /// The rows asked for and not yet answered.
        asked: ?[2]u64 = null,
    };

    /// A replica of the session whose first unit is `first`; `screens`
    /// as the authority's (its terminals fed by `screen`).
    pub fn init(gpa: Allocator, id: u16, first: []const u8, screens: bool) !*Replica {
        const r = try gpa.create(Replica);
        r.* = .{ .gpa = gpa, .id = id, .t = tape.memory(gpa) };
        r.t.screen_state = screens;
        r.t.core_gpa = r.epoch.allocator();
        r.confirm(first);
        if (r.t.core == null) {
            r.deinit();
            return error.NoCore;
        }
        return r;
    }

    pub fn deinit(r: *Replica) void {
        for (&r.screens) |*slot| if (slot.*) |*sc| sc.rep.deinit(r.coreGpa());
        if (r.t.core) |c| {
            const was = Stepping.begin(&r.t, &r.epoch);
            if (r.copy.held) r.copy.restore();
            c.deinit();
            was.end();
        }
        r.copy.deinit();
        for (r.pending.items) |p| r.freePending(p);
        r.pending.deinit(r.gpa);
        for (r.since.items) |u| r.gpa.free(u);
        r.since.deinit(r.gpa);
        r.out.deinit(r.gpa);
        r.screen_out.deinit(r.gpa);
        r.stats.deinit(r.gpa);
        tape.release(&r.t);
        if (r.diverged) |why| r.gpa.free(why);
        r.epoch.deinit();
        r.gpa.destroy(r);
    }

    pub fn core(r: *const Replica) *Pardes {
        return r.t.core.?;
    }

    fn freePending(r: *Replica, p: Pending) void {
        r.gpa.free(p.msg);
        if (p.spec) |s| r.gpa.free(s);
    }

    /// The replica's own input: applied at once when it can be, and the
    /// message for the authority returned (valid until the next call).
    pub fn input(r: *Replica, ev: pardes.Event) ![]const u8 {
        r.stats.inputs += 1;
        const seq = r.next_seq;
        r.next_seq += 1;
        const room = try r.gpa.alloc(u8, head_len + wire.clientBound(.{ .event = ev }));
        defer r.gpa.free(room);
        const n = (try wire.encodeClient(room[head_len..], .{ .event = ev })).len;
        header(room, r.id, seq);
        const msg = try r.gpa.dupe(u8, room[0 .. head_len + n]);
        try r.pending.append(r.gpa, .{ .seq = seq, .msg = msg });
        r.dirty = true;
        r.settle();
        r.out.clearRetainingCapacity();
        try r.out.appendSlice(r.gpa, msg);
        return r.out.items;
    }

    /// One unit of the authority's stream, in its order.
    pub fn confirm(r: *Replica, msg: []const u8) void {
        if (r.diverged != null) return;
        const u = parseUnit(msg) orelse return r.fail("a unit too short to read");
        r.stats.units += 1;
        const was = Stepping.begin(&r.t, &r.epoch);
        defer was.end();
        if (u.origin == r.id and r.pending.items.len > 0 and r.pending.items[0].seq == u.seq and r.applied > 0 and
            tape.sameRecords(r.pending.items[0].spec.?, u.tape))
        {
            r.stats.fast += 1;
            r.freePending(r.pending.orderedRemove(0));
            r.applied -= 1;
            if (r.applied == 0) {
                // Nothing speculative on top any more: the state is the
                // confirmed one.
                r.copy.release();
                rollback.Epoch.select(null);
                r.clearSince();
                return;
            }
            const kept = r.gpa.dupe(u8, u.tape) catch return r.fail("out of memory");
            r.since.append(r.gpa, kept) catch return r.fail("out of memory");
            if (r.since.items.len >= rebase_after) {
                r.stats.rebases += 1;
                r.toConfirmed();
                r.dirty = true;
            }
            return;
        }
        if (r.applied > 0) {
            if (u.origin == r.id) r.stats.mispredicted += 1 else r.stats.foreign += 1;
            if (u.origin == r.id and std.c.getenv("PARDES_REPLICA_TRACE") != null) {
                var w: std.Io.Writer.Allocating = .init(r.gpa);
                defer w.deinit();
                w.writer.print("replica {d}: its input {d} was recorded otherwise; it guessed:\n", .{ r.id, u.seq }) catch {};
                tape.describe(r.pending.items[0].spec.?, &w.writer);
                w.writer.print("and the authority recorded:\n", .{}) catch {};
                tape.describe(u.tape, &w.writer);
                std.debug.print("{s}", .{w.written()});
            }
            r.recovering = nowNs();
            r.toConfirmed();
        }
        if (tape.replayUnit(&r.t, u.tape)) |why| {
            if (std.c.getenv("PARDES_REPLICA_TRACE") != null) {
                var w: std.Io.Writer.Allocating = .init(r.gpa);
                defer w.deinit();
                w.writer.print("replica {d}: the unit of {d}/{d} diverged: {s}\n", .{ r.id, u.origin, u.seq, why }) catch {};
                tape.describe(u.tape, &w.writer);
                std.debug.print("{s}", .{w.written()});
            }
            return r.fail(why);
        }
        if (u.origin == r.id) {
            if (r.pending.items.len == 0 or r.pending.items[0].seq != u.seq) return r.fail("the authority confirmed an input this replica did not send next");
            if (r.blocked == u.seq) r.blocked = null;
            r.freePending(r.pending.orderedRemove(0));
        }
        r.dirty = true;
    }

    fn fail(r: *Replica, why: []const u8) void {
        if (r.diverged == null) r.diverged = r.gpa.dupe(u8, why) catch return;
    }

    fn clearSince(r: *Replica) void {
        for (r.since.items) |u| r.gpa.free(u);
        r.since.clearRetainingCapacity();
    }

    /// Back to the confirmed position: the copy put back, the units fast-
    /// pathed since replayed.
    fn toConfirmed(r: *Replica) void {
        if (r.copy.held) {
            r.copy.restore();
            rollback.Epoch.select(null);
        }
        r.applied = 0;
        for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| return r.fail(why);
        r.clearSince();
        for (r.pending.items) |*p| if (p.spec) |s| {
            r.gpa.free(s);
            p.spec = null;
        };
    }

    /// The pending inputs applied again, as far as they go.
    pub fn settle(r: *Replica) void {
        if (!r.dirty or r.diverged != null) return;
        r.dirty = false;
        const was = Stepping.begin(&r.t, &r.epoch);
        defer was.end();
        while (r.applied < r.pending.items.len and r.blocked != r.pending.items[r.applied].seq) if (!r.speculate()) break;
        if (r.recovering) |t0| {
            r.stats.rollback_ns.append(r.gpa, nowNs() - t0) catch {};
            r.recovering = null;
        }
    }

    /// pending[applied] applied on top: whether it was.
    fn speculate(r: *Replica) bool {
        const p = &r.pending.items[r.applied];
        const in = parseInput(p.msg) orelse return false;
        switch (in.event) {
            .key, .paste, .command => {},
            else => {
                // The view's (a resize, the pointer): the authority's for
                // now, phase 4's views to come.
                r.stats.unspeculated += 1;
                r.blocked = p.seq;
                return false;
            },
        }
        const c = r.core();
        if (!r.copy.held) {
            const t0 = nowNs();
            r.copy.take(&r.epoch, c) catch return false;
            rollback.Epoch.select(&r.epoch);
            r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {};
            r.stats.copy_bytes += r.copy.savedBytes();
            r.stats.copies += 1;
        }
        var terminals: [pardes.MAX_PANES]u64 = undefined;
        if (checked) terminalDigests(c, &terminals);
        const t0 = nowNs();
        tape.beginSpeculation(&r.t);
        c.toView(r.view);
        // Input into a terminal is the authority's: its step reads the
        // emulator (rows, cursor, modes), which here is the last delta's and
        // there what the pty has said since. It waits; phase 6 predicts the
        // echo.
        if (r.t.screen_state) if (c.panes[c.active]) |pane| if (pane.isTerminal()) tape.poison();
        c.update(in.event);
        c.pump(c.host) catch {};
        const clean = tape.endSpeculation(&r.t);
        const dt = nowNs() - t0;
        // Where a blob was written, should one be: the input that did.
        if (checked and std.c.getenv("PARDES_REPLICA_TRACE") != null) r.copy.check();
        if (!clean) {
            // Undone, and the earlier ones applied again on the confirmed
            // position: this one waits for the authority.
            r.stats.stopped += 1;
            r.blocked = p.seq;
            const upto = r.applied;
            r.toConfirmed();
            while (r.applied < upto) if (!r.speculate()) break;
            if (r.applied == 0 and r.copy.held) {
                r.copy.release();
                rollback.Epoch.select(null);
            }
            return false;
        }
        if (checked) {
            var after: [pardes.MAX_PANES]u64 = undefined;
            terminalDigests(c, &after);
            if (!std.mem.eql(u64, &terminals, &after)) @panic("replica: a speculation wrote a terminal's emulator");
        }
        r.stats.speculated += 1;
        r.stats.spec_ns.append(r.gpa, dt) catch {};
        p.spec = r.gpa.dupe(u8, tape.taken(&r.t)) catch return false;
        tape.clearTaken(&r.t);
        r.applied += 1;
        return true;
    }

    /// Nothing pending and nothing applied: the replica is the authority's
    /// confirmed state, which `digest` says.
    pub fn quiet(r: *const Replica) bool {
        return r.pending.items.len == 0 and r.applied == 0 and !r.copy.held;
    }

    fn coreGpa(r: *Replica) Allocator {
        return r.epoch.allocator();
    }

    /// One of the authority's terminal messages (`Screens.flush`, or an
    /// answer to `screenRequests`), taken between units in stream order: a
    /// delta written into its pane's emulator, or fetched rows. The
    /// message for the authority (an acknowledgement, or a request to start
    /// afresh), valid until the next call, or null.
    pub fn screen(r: *Replica, msg: []const u8) ?[]const u8 {
        const m = parseScreen(msg) orelse return null;
        const c = r.t.core orelse return null;
        const pane = c.panes[m.pane] orelse return null;
        if (pane.serial != m.serial) return null; // a pane gone: its slot's next is another
        const state = pane.terminal orelse return null;
        const slot = &r.screens[m.pane];
        if (slot.* == null or slot.*.?.serial != m.serial) {
            if (slot.*) |*old| old.rep.deinit(r.coreGpa());
            slot.* = .{ .serial = m.serial };
        }
        const sc = &slot.*.?;
        // The emulator is the authority's, outside every rollback copy:
        // what it allocates now must outlive one.
        const was = r.epoch.pause();
        defer r.epoch.unpause(was);
        switch (m.kind) {
            kind_delta => {
                const t0 = nowNs();
                const applied = sc.rep.apply(r.coreGpa(), terminal.terminalIo(), &state.vt, m.payload) catch |err| {
                    if (err != error.BaseMismatch) r.fail("a terminal's delta did not apply");
                    if (sc.refused) return null;
                    sc.refused = true;
                    return r.screenMessage(m.pane, m.serial, kind_reset, &.{});
                };
                r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {};
                sc.refused = false;
                terminal.takeMarks(state, applied.extra);
                var seq: [4]u8 = undefined;
                std.mem.writeInt(u32, &seq, applied.seq, .little);
                return r.screenMessage(m.pane, m.serial, kind_ack, &seq);
            },
            kind_rows => {
                sc.asked = null;
                sc.rep.applyRows(r.coreGpa(), &state.vt, m.payload) catch r.fail("a terminal's rows did not apply");
                return null;
            },
            else => return null,
        }
    }

    /// A request for the rows a terminal shows here and does not hold (its
    /// holes in view, after a scroll back), one a terminal at a time; null
    /// when none is owed. Until the answer, a hole shows blank.
    pub fn screenRequest(r: *Replica) ?[]const u8 {
        const c = r.t.core orelse return null;
        for (&r.screens, 0..) |*slot, id| {
            const sc: *ScreenOf = if (slot.*) |*x| x else continue;
            if (sc.asked != null) continue;
            const pane = c.panes[id] orelse continue;
            if (pane.serial != sc.serial) continue;
            const state = pane.terminal orelse continue;
            const shown = sc.rep.shown(&state.vt);
            var holes: std.ArrayList([2]u64) = .empty;
            defer holes.deinit(r.gpa);
            sc.rep.missing(shown[0], shown[1], &holes, r.gpa) catch return null;
            if (holes.items.len == 0) continue;
            const want: [2]u64 = .{ holes.items[0][0], holes.items[holes.items.len - 1][1] };
            sc.rep.blank(&state.vt, want[0], want[1]);
            sc.asked = want;
            var range: [16]u8 = undefined;
            std.mem.writeInt(u64, range[0..8], want[0], .little);
            std.mem.writeInt(u64, range[8..16], want[1], .little);
            return r.screenMessage(@intCast(id), sc.serial, kind_rows, &range);
        }
        return null;
    }

    fn screenMessage(r: *Replica, pane: u8, serial: u32, kind: u8, payload: []const u8) ?[]const u8 {
        r.screen_out.clearRetainingCapacity();
        writeScreenHead(&r.screen_out, r.gpa, pane, serial, kind) catch return null;
        r.screen_out.appendSlice(r.gpa, payload) catch return null;
        return r.screen_out.items;
    }

    pub fn digest(r: *Replica) u64 {
        const was = Stepping.begin(&r.t, &r.epoch);
        defer was.end();
        return tape.digestOf(r.core());
    }
};

fn terminalDigests(p: *const Pardes, out: *[pardes.MAX_PANES]u64) void {
    for (p.panes, out) |slot, *d| {
        d.* = 0;
        const pane = slot orelse continue;
        const state = pane.terminal orelse continue;
        var h = walk.Hasher.init(0);
        state.digestScreen(&h);
        d.* = h.final();
    }
}

pub fn digestOf(a: *Authority) u64 {
    const was = Stepping.begin(&a.t, null);
    defer was.end();
    return tape.digestOf(a.core);
}

const TestHost = struct {
    fn watched(_: ?*anyopaque) bool {
        return false;
    }
    const vtable: pardes.Host.VTable = .{ .watched = watched };
    fn host() pardes.Host {
        return .{ .vtable = &vtable };
    }
};

fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void {
    const text = [_]u8{@intCast(cp & 0x7f)};
    const msg = try r.input(.{ .key = .{ .cp = cp, .text = if (cp < 0x80 and cp >= 0x20) &text else "" } });
    try sent.append(std.testing.allocator, try std.testing.allocator.dupe(u8, msg));
}

test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" {
    const gpa = std.testing.allocator;
    const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
    defer a.deinit();
    const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
    defer r.deinit();
    try std.testing.expectEqual(digestOf(a), r.digest());
    var sent: std.ArrayListUnmanaged([]u8) = .empty;
    defer {
        for (sent.items) |m| gpa.free(m);
        sent.deinit(gpa);
    }
    for ("oabc") |k| try key(r, k, &sent);
    try key(r, pardes.Key.escape, &sent);
    try std.testing.expectEqual(@as(usize, 5), r.applied);
    for (sent.items) |m| {
        r.confirm(try a.take(m));
        r.settle();
    }
    if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
    try std.testing.expect(r.diverged == null);
    try std.testing.expectEqual(@as(u32, 5), r.stats.fast);
    try std.testing.expect(r.quiet());
    try std.testing.expectEqual(digestOf(a), r.digest());
}

test "another client's input first: a replica rolls back, replays it and applies its own again" {
    const gpa = std.testing.allocator;
    const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
    defer a.deinit();
    const first = try gpa.dupe(u8, try a.unit(0, 0));
    defer gpa.free(first);
    const r1 = try Replica.init(gpa, 1, first, false);
    defer r1.deinit();
    const r2 = try Replica.init(gpa, 2, first, false);
    defer r2.deinit();
    var s1: std.ArrayListUnmanaged([]u8) = .empty;
    var s2: std.ArrayListUnmanaged([]u8) = .empty;
    defer {
        for (s1.items) |m| gpa.free(m);
        for (s2.items) |m| gpa.free(m);
        s1.deinit(gpa);
        s2.deinit(gpa);
    }
    for ("oone") |k| try key(r1, k, &s1);
    for ("Otwo") |k| try key(r2, k, &s2);
    // The authority hears r2 first, then r1; both hear the units in that
    // order.
    for ([_]*std.ArrayListUnmanaged([]u8){ &s2, &s1 }) |list| for (list.items) |m| {
        const u = try gpa.dupe(u8, try a.take(m));
        defer gpa.free(u);
        r1.confirm(u);
        r1.settle();
        r2.confirm(u);
        r2.settle();
    };
    for ([_]*Replica{ r1, r2 }) |r| {
        if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
        try std.testing.expect(r.diverged == null);
        try std.testing.expect(r.quiet());
        try std.testing.expectEqual(digestOf(a), r.digest());
    }
    try std.testing.expect(r1.stats.foreign >= 1);
    try std.testing.expectEqual(@as(u32, 4), r2.stats.fast);
}