diff options
| -rw-r--r-- | src/pardes.zig | 1 | ||||
| -rw-r--r-- | src/replica.zig | 82 | ||||
| -rw-r--r-- | test/replicas.zig | 832 |
3 files changed, 778 insertions, 137 deletions
diff --git a/src/pardes.zig b/src/pardes.zig index 48c87bf6..0bedab03 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -77,6 +77,7 @@ pub const config = @import("config.zig"); pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); +pub const wire = @import("wire.zig"); pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); diff --git a/src/replica.zig b/src/replica.zig index e5d5ad16..4140beca 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -218,6 +218,16 @@ pub const Authority = struct { return a.unit(0, a.seq); } + /// An input of its own frontend's, in the view that frontend shows + /// (the first: tui.zig `Shell.handle` goes into `s.own`), as its unit. + pub fn own(a: *Authority, ev: pardes.Event) ![]const u8 { + std.debug.assert(a.batched == 0); + const was = Stepping.begin(&a.t, null); + a.core.toView(0); + was.end(); + return a.local(ev); + } + /// 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 @@ -256,6 +266,51 @@ pub const Authority = struct { return .{ .view = k, .unit = try a.unit(0, a.seq) }; } + /// A client joining as `Peers.join` takes one: its view kept for it + /// (`back`, after a divergence) or a new one, null when every view is + /// taken (refused); the unit that says so to the others (valid until the + /// next call), and the dump it loads, its blobs in place (`gpa`'s), with + /// the digest it checks its load by. + pub fn join(a: *Authority, client: u16, back: ?u8) !?struct { view: u8, unit: []const u8, dump: []u8, digest: u64 } { + std.debug.assert(a.batched == 0); + const was = Stepping.begin(&a.t, null); + defer was.end(); + const again = if (back) |v| a.core.rejoinView(v) else false; + const k = (if (again) back else a.core.openView()) orelse return null; + a.core.undrawn |= @as(u8, 1) << @intCast(k); + a.view_of[client] = k; + a.seq += 1; + const u = try a.unit(0, a.seq); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(a.core.gpa); + const state = try pardes.dump.dumpJoin(a.core, &blobs); + defer a.core.gpa.free(state); + tape.resync(&a.t); + var whole: std.ArrayListUnmanaged(u8) = .empty; + errdefer whole.deinit(a.gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(a.gpa, state[pos..b.at]); + try whole.appendSlice(a.gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(a.gpa, state[pos..]); + return .{ .view = k, .unit = u, .dump = try whole.toOwnedSlice(a.gpa), .digest = tape.digestOf(a.core) }; + } + + /// Client `client` gone as `Peers.leave` lets one go: its view kept for + /// it (`again`: it joins again for it) or closed; the unit. + pub fn leave(a: *Authority, client: u16, again: bool) ![]const u8 { + std.debug.assert(a.batched == 0); + const was = Stepping.begin(&a.t, null); + const k = a.view_of[client]; + a.core.undrawn &= ~(@as(u8, 1) << @intCast(k)); + if (again) a.core.awayView(k) else a.core.closeView(k); + was.end(); + a.seq += 1; + return a.unit(0, a.seq); + } + /// Client `client`'s view gone (its link ended), as its unit. pub fn closeView(a: *Authority, client: u16) ![]const u8 { std.debug.assert(a.batched == 0); @@ -1013,6 +1068,9 @@ pub const Replica = struct { // was there before is of a grid the deltas since moved on // from (a rollback never brings a terminal's past back). r.core().shell_rows = .{}; + // A tab's width is the process's (config.tab_now), which a + // step that set it (Tab) wrote and the copy does not hold. + pardes.config.tab_now = r.core().settings.tab; } r.applied = 0; // Its views as the copy was taken, or as the last delta set them @@ -3558,6 +3616,30 @@ test "another client's input first: a replica rolls back, replays it and applies try std.testing.expectEqual(@as(u32, 4), r2.stats.fast); } +test "a rollback over a Tab it applied puts the process's tab width back as its core has it" { + // config.tab_now is the process's, written by the step that set the + // width (the soak, five clients: a Tab undone left it, and the next + // replayed step measured the files' tabs otherwise). + const gpa = std.testing.allocator; + defer pardes.config.tab_now = pardes.config.tab_width; + 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 r = try Replica.init(gpa, 1, first, false); + defer r.deinit(); + pardes.config.tab_now = r.core().settings.tab; + const was = r.core().settings.tab; + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Tab 2" })); + defer gpa.free(msg); + try std.testing.expectEqual(@as(usize, 1), r.applied); + try std.testing.expectEqual(@as(u16, 2), pardes.config.tab_now); + // The session's own key first: back to the confirmed position. + r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); + try std.testing.expectEqual(was, r.core().settings.tab); + try std.testing.expectEqual(was, pardes.config.tab_now); +} + test "a delta applied under a speculation outlives its rollback: the terminal stays the authority's newest" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; diff --git a/test/replicas.zig b/test/replicas.zig index ab665bf2..8d4b2e38 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1,9 +1,14 @@ -//! 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. +//! pardes-replicas: a session and its clients in one process +//! (src/replica.zig), each a process of its own for what a process holds +//! (`Proc`): the session's own frontend typing in its view and drawing it, +//! and each client (a terminal's loop or a window's, by turns) joined from +//! the session's dump for a view of its own, typing at once over its own +//! delayed, jittered link, as monkey.zig's scripts type at a tty, through +//! the real `replica.Link` on a socket pair: it draws its view, asks for +//! the rows it lacks, takes a copy while idle, asks the session's digest +//! when quiet; one joins late, one leaves, one is put off the session once +//! and joins again for its view, and those past the views a session has +//! are refused until one is let go. //! //! Terminals cross as screen state (src/term/screen_state.zig): the session's //! shell pane runs a full-screen program and then a `yes` flood (`--flood` @@ -12,7 +17,7 @@ //! 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=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] [--shared] +//! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] //! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K] //! zig build replicas -Dplatform=tui -Doptimize=ReleaseFast -- --screen-state <dir> //! @@ -47,9 +52,14 @@ const frame_us = 16_667; /// 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, + /// The session draws its own view in its pump, as one with a frontend + /// of its own does (Pardes.pump), what that writes in its core and + /// none of the replicas' with it. + draws: bool = false, - fn watched(_: ?*anyopaque) bool { - return false; + fn watched(ctx: ?*anyopaque) bool { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + return h.draws; } fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { @@ -66,7 +76,30 @@ const Host = struct { } }; -const Kind = enum { input, to_authority, to_replica, echo, frame, output, screen_down, screen_up, client_frame }; +const Kind = enum { + input, + to_authority, + to_replica, + echo, + frame, + output, + screen_down, + screen_up, + client_frame, + /// The session's own frontend's input, in its own view. + own, + /// A client's join: its dial at the session, its dump (or refusal) + /// back; its check of the session's digest asked and answered; its + /// bye; a wake its loop asked for (`quietCheck`); its quit. + dial, + dump, + refused, + check_up, + checked, + bye_up, + wake, + quit, +}; const Msg = struct { at: u64, @@ -74,8 +107,12 @@ const Msg = struct { kind: Kind, who: u16, bytes: []u8, - /// An echo's: the client's input that made it (--echo). + /// An echo's: the client's input that made it (--echo); a bye's + /// `again`. seq: u32 = 0, + /// The client's join it belongs to: one of an earlier join (its link + /// ended since) is dropped, as the closed socket drops it. + gen: u32 = 0, fn order(_: void, a: Msg, b: Msg) std.math.Order { if (a.at != b.at) return std.math.order(a.at, b.at); @@ -128,6 +165,17 @@ const Totals = struct { resets: u64 = 0, screens_wrong: u64 = 0, screens_checked: u64 = 0, + /// Joins from a dump, refused, again after a divergence put on it + /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. + joins: u64 = 0, + refused: u64 = 0, + rejoined: u64 = 0, + detached: u64 = 0, + agree: u64 = 0, + differ: u64 = 0, + /// Resizes the windows posted (each pass whose view's size is not + /// the window's: gui.zig `OwnView.run`). + resizes: u64 = 0, fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -178,7 +226,7 @@ fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)]; return .{ .paste = buf[0..n] }; }, - 36 => return .{ .command = switch (random.uintLessThan(u8, 10)) { + 36 => return .{ .command = switch (random.uintLessThan(u8, 12)) { 0 => "Newcol", 1 => "Zerox", 2 => "Undo", @@ -187,6 +235,10 @@ fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const 5 => "Search Recent", 6, 7 => looks[random.uintLessThan(usize, looks.len)], 8 => "Del", + // A tab's width: every pane's layout, and a process global + // (config.tab_now) its step writes. + 9 => "Tab 2", + 10 => "Tab 8", else => return .{ .key = .{ .cp = if (random.boolean()) 'o' else 'i', .ctrl = true } }, } }, 37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } }, @@ -208,7 +260,7 @@ fn writeFile(path: [:0]const u8, lines: usize) !void { 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 }); + const text = try std.fmt.bufPrint(&line, "const value_{d:0>4} = {d};\t// a line to edit\n", .{ n, n *% 7919 }); if (libc.write(fd, text.ptr, text.len) != @as(isize, @intCast(text.len))) return error.WriteFailed; } } @@ -220,7 +272,7 @@ fn writeText(path: [:0]const u8, text: []const u8) !void { 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 }; +const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, flood_mb: u64 }; /// The terminal pane's screen as a hash of screen_state's dump of it. /// The module's own replica behind the core's handle (Replica.screens). @@ -241,8 +293,260 @@ fn screenHash(t: *screen_state.Terminal) u64 { return h.hasher.final(); } +/// A process's own globals, where the soak runs the session and every +/// client in one: a step writes `config.tab_now` from its core's settings +/// (exec.zig's Tab, a dump's load), which a client's process and the +/// session's each hold apart. Shared, one core's rollback that left it +/// stale would leave the other cores reading it too, and agree. +const Proc = struct { + tab_now: u16 = pardes.config.tab_width, + + var current: ?*Proc = null; + + fn enter(p: *Proc) void { + if (current == p) return; + if (current) |was| was.tab_now = pardes.config.tab_now; + pardes.config.tab_now = p.tab_now; + current = p; + } +}; + +/// A client of the session: a process of its own (`proc`) whose loop is +/// the terminal's (tui.zig `runClient`) or the window's (gui.zig +/// `clientSession`), over the real `replica.Link` on a socket pair whose +/// other end the soak reads as the session's Peer does (`drain`). It joins +/// from the session's dump, may be refused (every view taken), leaves, and +/// joins again for its view after a divergence. +const Client = struct { + kind: enum { tty, window }, + proc: Proc = .{}, + link: replica.Link = undefined, + r: ?*replica.Replica = null, + fds: [2]c_int = .{ -1, -1 }, + check: [:0]u8 = undefined, + /// The session's side of its socket: bytes not yet a whole frame, the + /// stamp before an input, and the inputs it took (Peer.seq). + got: std.ArrayListUnmanaged(u8) = .empty, + stamp: std.ArrayListUnmanaged(u8) = .empty, + seq: u32 = 0, + /// Its id and its terminals' peer at the session, and the view the + /// session made or keeps for it (`back`, joining again). + id: u16 = 0, + sid: u16 = 0, + view: u8 = 0, + back: ?u8 = null, + digest: u64 = 0, + /// Joins the session made for it (its side), and the one its replica + /// is of (0: none, its link ended). + gen: u32 = 0, + live: u32 = 0, + joined: bool = false, + dialling: bool = false, + /// Refusals in a row, until it gives up (a person would). + tries: u32 = 0, + left: usize, + cols: u16, + rows: u16, + last_input: u64 = 0, + asked_at: u64 = 0, + wake_at: u64 = 0, + drew: bool = false, + resize: ?pardes.Event = null, + resizes: u32 = 0, + + fn present(ctx: ?*anyopaque, _: *const pardes.Surface) void { + const cl: *Client = @ptrCast(@alignCast(ctx.?)); + cl.drew = true; + } + + /// tui.zig `Client.draw` (gui.zig's is the same): its own view drawn + /// outside any step, what presenting writes in the core put back. + fn draw(cl: *Client) void { + const r = cl.r.?; + const core = r.core(); + const skipped = core.present_skipped; + const needs = core.needs_frame; + core.frames.mark_start = pardes.FrameStats.nowNs(); + core.frames.mark_update = core.frames.mark_start; + cl.drew = false; + r.draw(.{ .ctx = cl, .f = present }); + core.frames.mark_render = core.frames.mark_update; + cl.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed); + core.present_skipped = skipped; + core.needs_frame = needs; + cl.link.drawn(cl.drew); + } + + /// gui.zig `OwnView.run` over its own view (`Replica.within`): the + /// window's size against the view's, a resize posted when they differ. + fn own(cl: *Client, core: *pardes.Pardes) anyerror!void { + const v = core.view(); + const metrics: pardes.RowMetrics = .{ .body_w = 9, .body_h = 18, .tagline_w = 9, .tagline_h = 18 }; + if (cl.cols == v.screen_w and cl.rows == v.screen_h and v.cell_pixels.w == 9 and v.cell_pixels.h == 18 and std.meta.eql(metrics, v.row_metrics)) return; + cl.resize = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } }; + } + + /// The window's own pass over its view, and what it posted fed. + fn within(cl: *Client) void { + if (cl.kind != .window) return; + cl.r.?.within(cl, own); + if (cl.resize) |ev| { + cl.link.input(ev); + cl.resizes += 1; + } + cl.resize = null; + } +}; + +const Queue = std.PriorityQueue(Msg, void, Msg.order); + +/// What travels: the queue, its order, and each client's links. +const Net = struct { + q: Queue = .empty, + n: u64 = 0, + random: std.Random, + one_way: u64, + jitter: u64, + up: [8]Link = @splat(.{}), + down: [8]Link = @splat(.{}), + + fn send(net: *Net, m: Msg) !void { + var mm = m; + mm.n = net.n; + net.n += 1; + try net.q.push(gpa, mm); + } + + /// Down client `c`'s link (the session's stream to it), `bytes` its. + fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void { + try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); + } +}; + +/// What client `c` wrote to its socket since (its inputs, its terminal +/// messages, a check asked, its bye), read off the other end as the +/// session's Peer reads it (`Peer.take`), up its link. +fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { + var buf: [1 << 16]u8 = undefined; + while (true) { + const k = libc.read(cl.fds[0], &buf, buf.len); + if (k <= 0) break; + try cl.got.appendSlice(gpa, buf[0..@intCast(k)]); + } + const wire = pardes.wire; + var at: usize = 0; + while (try wire.framed(cl.got.items[at..])) |f| : (at += f.total) { + const frame = cl.got.items[at..][0..f.total]; + const kind: Kind = switch (std.enums.fromInt(wire.ClientTag, f.tag) orelse return error.BadFrame) { + .stamp => { + cl.stamp.clearRetainingCapacity(); + try cl.stamp.appendSlice(gpa, frame); + continue; + }, + .screen_ack => .screen_up, + .check => .check_up, + .bye => .bye_up, + else => .to_authority, + }; + var seq: u32 = 0; + const bytes: []u8 = switch (kind) { + .to_authority => in: { + // Its head (its id and seq at the session), its stamp, its event. + cl.seq += 1; + const msg = try gpa.alloc(u8, 6 + cl.stamp.items.len + frame.len); + std.mem.writeInt(u16, msg[0..2], cl.id, .little); + std.mem.writeInt(u32, msg[2..6], cl.seq, .little); + @memcpy(msg[6..][0..cl.stamp.items.len], cl.stamp.items); + @memcpy(msg[6 + cl.stamp.items.len ..], frame); + cl.stamp.clearRetainingCapacity(); + if (replica.parseInput(msg) == null) return error.BadInput; + break :in msg; + }, + .screen_up => try gpa.dupe(u8, f.payload), + .bye_up => bye: { + seq = @intFromBool((try wire.decodeClient(f.tag, f.payload)).bye.again); + break :bye &.{}; + }, + else => &.{}, + }; + try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .seq = seq, .gen = cl.gen }); + } + std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]); + cl.got.shrinkRetainingCapacity(cl.got.items.len - at); +} + +/// The rest of a pass of the client's loop, after what woke it (an input +/// applied and sent, a message of the stream taken): as the two loops do +/// each time round (tui.zig `runClient`, gui.zig `clientSession`): its +/// inputs settled, a rollback drawn again, then its predicted echo judged, +/// its view drawn if anything changed (the rows it lacks asked after), +/// the copy taken while idle, and the session's digest asked once quiet. +fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void { + const r = cl.r orelse return; + const link = &cl.link; + r.settle(); + if (r.moved) { + r.moved = false; + link.dirty = true; + } + if (link.owed or r.echo.changed) link.dirty = true; + if (r.diverged != null) link.quit = true; + if (!link.quit) { + cl.within(); + if (r.echoFrame()) link.dirty = true; + if (link.dirty) cl.draw(); + // Idle, its frame drawn: the window whenever its wait is not 0, + // the terminal unless an event is held already (one pass in four). + if (cl.kind == .window or net.random.uintLessThan(u8, 4) != 0) r.ready(); + // `quietCheck`, on the soak's clock: 300 ms after its last input + // and its last check, changed since and quiet, the digest asked. + if (link.changed and !link.asked and r.quiet()) { + const due = @max(cl.last_input, cl.asked_at) + 300_000; + if (now >= due) { + link.input_ns = 0; + link.asked_ns = 0; + _ = link.quietCheck(); + cl.asked_at = now; + } else if (cl.wake_at < due) { + cl.wake_at = due; + try net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(c + 1), .bytes = &.{}, .gen = cl.live }); + } + } + } + try drain(cl, c, net, now); +} + +/// Its link ended (it diverged, or it quits): its bye, and its join again +/// for its view after a divergence (`Link.rejoins`), the core it leaves +/// held until the dump comes, as `replica.join` holds it. +fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run) !void { + const r = cl.r.?; + const link = &cl.link; + replica.bye(cl.fds[1], r.diverged != null); + try drain(cl, c, net, now); + cl.live = 0; + if (r.diverged) |why| { + if (link.put_off) totals.rejoined += 1 else { + totals.divergences += 1; + std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ run_.seed, run_.rtt_ms, c + 1, why }); + } + } + if (link.rejoins()) { + cl.back = r.view; + cl.dialling = true; + return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + } + try totals.add(&r.stats); + r.deinit(); + cl.r = null; + totals.detached += 1; +} + 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 }); + // Last: the processes' globals were this run's. + defer Proc.current = null; var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var host: Host = .{}; @@ -259,48 +563,78 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { look.* = try std.fmt.bufPrint(l, "Look {s}", .{path}); } // 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. + // files looked at: the session's own frontend shows the first view + // and types in it; each client joins from a dump for a view of its own. + var session: Proc = .{}; + session.enter(); const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); - defer a.deinit(); + defer { + session.enter(); + 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(); + for (&paths) |*path| { + var line: [300]u8 = undefined; + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) }); } - 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. + // Where a wheel over the shell lands in the session's view, which a + // client's view is a copy of as it joins. const sr = a.core.view().rects[shell]; const wheel_at: ?[2]u16 = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null; + var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 }; + defer { + while (net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); + net.q.deinit(gpa); + } + // The clients: terminals and windows by turns. The first two dial at + // once, the third late (the shell's program on), more later still + // (refused while every view is taken, dialling again until one is + // let go); the first leaves when it is done; the second is put off + // the session once (PARDES_TEST_DIVERGE) and joins again for its view. + var clients: [8]Client = undefined; + for (clients[0..r.clients], 0..) |*cl, c| { + cl.* = .{ .kind = if (c % 2 == 0) .tty else .window, .left = r.steps, .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) }; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &cl.fds) != 0) return error.NoSocket; + _ = libc.fcntl(cl.fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); + var name: [300]u8 = undefined; + cl.check = try gpa.dupeSentinel(u8, try std.fmt.bufPrint(&name, "{s}/check-{d}", .{ dir, c }), 0); + _ = libc.unlink(cl.check); + cl.dialling = true; + const at: u64 = switch (c) { + 0, 1 => random.uintLessThan(u64, 100_000), + 2 => 1_200_000, + else => 2_000_000 + c * 100_000, + }; + try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + } + defer for (clients[0..r.clients]) |*cl| { + cl.proc.enter(); + if (cl.r) |rp| rp.deinit(); + _ = libc.close(cl.fds[0]); + _ = libc.close(cl.fds[1]); + cl.got.deinit(gpa); + cl.stamp.deinit(gpa); + gpa.free(cl.check); + }; + // The link is made at the first join (its replica the dump's). + var has_link: [8]bool = @splat(false); + defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) { + cl.link.check = null; + cl.link.deinit(gpa); + }; + // 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 shell_session = try screen_state.shellStream(gpa); + defer gpa.free(shell_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; @@ -313,56 +647,102 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { 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; - // 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 = &.{} }); + // The session's own typist, and every client's, until each is done. + var own_left = r.steps; + var typing: usize = r.clients + 1; + var next_id: u16 = 1; + try net.send(.{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }); + try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} }); + try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} }); + try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} }); + try net.send(.{ .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 Session = struct { + a: *replica.Authority, + screens: *replica.Screens, + clients: []Client, + net: *Net, + owed: *std.ArrayListUnmanaged([]u8), + versions: *std.AutoHashMapUnmanaged(u64, u64), + totals: *Totals, - while (queue.pop()) |m| { + /// The batch of its own steps as a unit, if any (`Authority.pending`). + fn pending(s: @This(), now: u64, flooding: bool) !void { + if (try s.a.pending()) |batch| try s.unit(batch, now, flooding); + } + + /// A unit to every client joined (Peers.unit), after the rows of + /// its terminals its steps read that a client holds as holes. + fn unit(s: @This(), u: []const u8, now: u64, flooding: bool) !void { + var rows: std.ArrayListUnmanaged([]u8) = .empty; + defer rows.deinit(gpa); + for (s.clients, 0..) |*cl, c| if (cl.joined) { + rows.clearRetainingCapacity(); + try s.screens.fill(s.a.core, cl.sid, &rows); + for (rows.items) |bytes| { + s.totals.filled_bytes += bytes.len; + try s.net.toClient(c, now, .screen_down, cl.gen, bytes); + } + }; + s.screens.filled(s.a.core); + // The sizes its steps gave terminals, after their rows. + pardes.panes.resizeDeferred(s.a.core); + for (s.clients, 0..) |*cl, c| if (cl.joined) { + s.totals.unit_bytes += u.len; + if (flooding) s.totals.flood_unit_bytes += u.len; + try s.net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, u)); + }; + } + + /// What each client is owed of the terminals (`Screens.flush`). + fn flush(s: @This(), now: u64, only: ?usize) !void { + for (s.clients, 0..) |*cl, c| if (cl.joined and (only == null or only.? == c)) { + s.owed.clearRetainingCapacity(); + try s.screens.flush(s.a.core, cl.sid, 0, s.owed); + for (s.owed.items) |bytes| { + s.totals.deltas += 1; + s.totals.delta_bytes += bytes.len; + try s.net.toClient(c, now, .screen_down, cl.gen, bytes); + } + }; + // Each version as the authority's screen showed it. + for (&s.screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| { + const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; + if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue; + _ = s.a.core.panes[id] orelse continue; + try s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)); + }; + } + }; + const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals }; + + while (net.q.pop()) |m| { defer if (m.bytes.len > 0) gpa.free(m.bytes); + const flooding = m.at >= flood_at and flood_end == 0; + // A client's message, but an echo's and an output's `who` (a pane, + // a program). + const c: usize = if (m.who == 0 or m.kind == .echo or m.kind == .output) 0 else m.who - 1; + const cl = &clients[c]; switch (m.kind) { - .input => { - const c = m.who - 1; + // ---- the session ---- + .own => { + session.enter(); var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, if (c == 0) wheel_at else null, &looks); - 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; + const ev = nextEvent(random, &buf, wheel_at, &looks); + try ses.pending(m.at, flooding); + try ses.flush(m.at, null); + try ses.unit(try a.own(ev), m.at, false); + try ses.flush(m.at, null); + for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); + host.echo.clearRetainingCapacity(); + own_left -= 1; + if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1; }, .to_authority, .echo, .output => { + session.enter(); const unit = switch (m.kind) { .echo => echo: { a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } }); @@ -375,92 +755,249 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { program = .{ .bytes = switch (m.who) { 0 => tui, 1 => yes, - else => session, + else => shell_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 = &.{} }) + try net.send(.{ .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: { + if (!cl.joined or m.gen != cl.gen) break :in null; // 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); + // reads, before it is stepped (Peers.input). + try ses.pending(m.at, flooding); + try ses.flush(m.at, null); 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 }); + if (unit) |u| { + try ses.unit(u, m.at, false); + try ses.flush(m.at, null); + } + for (host.echo.items) |e| try net.send(.{ .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]); + session.enter(); + // Its own frontend's frame: a pump that draws its view (and + // ticks: messages, streams) when one is owed or something is + // due, once a frame at most, as its host's loop paces it. + if (a.core.needs_frame or a.core.nextWake() != null) { + host.draws = true; + a.output(.tick); + host.draws = false; + } + try ses.pending(m.at, flooding); 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); + try ses.flush(m.at, null); 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; + const busy = typing > 0 or flood_end == 0 or net.q.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 = &.{} }); + if (frames_left > 0) try net.send(.{ .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(); - rp.ready(); - } 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 = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; - totals.screens_checked += 1; - if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(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, replicaOf(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) }); + .dial => { + // Peers.join at the session's next boundary: its view kept + // for it, or a new one, or refused when all are taken. + session.enter(); + try ses.pending(m.at, flooding); + const id = next_id; + const j = (try a.join(id, cl.back)) orelse { + totals.refused += 1; + try net.toClient(c, m.at, .refused, cl.gen, &.{}); + continue; + }; + next_id += 1; + try ses.unit(j.unit, m.at, false); + cl.joined = true; + cl.gen += 1; + cl.id = id; + cl.seq = 0; + cl.view = j.view; + cl.digest = j.digest; + cl.sid = try screens.addPeer(); + totals.joins += 1; + try net.toClient(c, m.at, .dump, cl.gen, j.dump); + // Its terminals afresh, after its dump and before any unit. + try ses.flush(m.at, c); + }, + .check_up => { + session.enter(); + if (!cl.joined or m.gen != cl.gen) continue; + try ses.pending(m.at, flooding); + const d = try gpa.alloc(u8, 8); + std.mem.writeInt(u64, d[0..8], replica.digestOf(a), .little); + try net.toClient(c, m.at, .checked, cl.gen, d); + }, + .bye_up => { + // Peers.leave: its view kept for it (`again`) or closed. + session.enter(); + if (!cl.joined or m.gen != cl.gen) continue; + try ses.pending(m.at, flooding); + cl.joined = false; + screens.dropPeer(cl.sid); + try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false); }, - .client_frame => {}, .screen_up => { - const c = m.who - 1; + session.enter(); + if (!cl.joined or m.gen != cl.gen) continue; 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 }); + if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer); + }, + // ---- a client ---- + .refused => { + if (!cl.dialling) continue; + // Said and gone; started again a while later (a person + // does), while it has keys left to type. + cl.back = null; + if (cl.r) |old| { + cl.proc.enter(); + try totals.add(&old.stats); + old.deinit(); + cl.r = null; + } + cl.tries += 1; + if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { + // Given up on: its keys are never typed. + cl.dialling = false; + if (cl.left > 0) typing -= 1; + cl.left = 0; + } + }, + .dump => { + cl.proc.enter(); + cl.dialling = false; + cl.tries = 0; + // replica.join: the core it left let go once the new one + // is here, the dump loaded and checked by the digest. + if (cl.r) |old| { + try totals.add(&old.stats); + old.deinit(); + } + const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows }); + cl.r = rp; + rp.stats.samples = true; + rp.t.local_files = true; + rp.echo.now = m.at * 1000; + if (!rp.loaded(cl.digest)) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ r.seed, r.rtt_ms, m.who }); + } + cl.live = m.gen; + var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; + if (!has_link[c]) { + cl.link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }; + has_link[c] = true; + if (c == 1) cl.link.test_diverge = 40; + } + cl.link.reset(rp, &j); + // What it is, then its size, are its view's first inputs + // (the window's size from its own pass over its view). + cl.link.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } }); + if (cl.kind == .tty) cl.link.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } }); + cl.last_input = m.at; + try pass(cl, c, &net, m.at); + if (cl.left > 0 and cl.left == r.steps) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + }, + .input, .to_replica, .screen_down, .checked, .wake, .quit => { + cl.proc.enter(); + if (m.kind == .input and cl.left == 0) continue; + const rp = cl.r orelse if (m.kind == .input and cl.dialling) { + try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + continue; + } else continue; + if (m.kind == .input) { + // A key typed while it joins again waits for the link. + if (cl.live == 0) { + try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + continue; + } + } else if (m.kind != .quit and m.gen != cl.live) continue; + rp.echo.now = m.at * 1000; + switch (m.kind) { + .input => { + var buf: [64]u8 = undefined; + const ev = nextEvent(random, &buf, wheel_at, &looks); + cl.within(); + cl.link.input(ev); + cl.last_input = m.at; + cl.left -= 1; + if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { + typing -= 1; + // The first leaves once it is done. + if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); + } + }, + .to_replica => cl.link.take(.{ .unit = try gpa.dupe(u8, m.bytes) }), + .screen_down => { + const pane = m.bytes[0]; + const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; + cl.link.take(.{ .screen = try gpa.dupe(u8, m.bytes) }); + if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { + const now_seq = replicaOf(sc.rep).seq; + if (now_seq == was) totals.resets += 1 else { + // Applied: the screen is the authority's at that version. + totals.screens_checked += 1; + const want = versions.get(@as(u64, sc.serial) << 32 | now_seq); + const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; + if (want == null or want.? != screenHash(vt)) { + totals.screens_wrong += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, now_seq }); + } + // Deltas while the flood runs (an RTT/2 behind it). + if (m.at >= flood_at + net.one_way and (flood_end == 0 or m.at <= flood_end + net.one_way)) flood_deltas[c] += 1; + } + }; + }, + .checked => cl.link.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), + .wake => cl.wake_at = 0, + .quit => cl.link.quit = true, + else => unreachable, + } + try pass(cl, c, &net, m.at); + if (cl.link.quit) try ended(cl, c, &net, m.at, totals, r); }, + .client_frame => {}, } } totals.flood_us += flood_end -| flood_at; for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d; + session.enter(); const want = replica.digestOf(a); - for (reps[0..r.clients], 1..) |rp, id| { + for (clients[0..r.clients], 1..) |*cl, id| { + totals.resizes += cl.resizes; + // Its quiet checks: what the session's digest was against its own. + if (readAll(cl.check)) |said| { + defer gpa.free(said); + var lines = std.mem.tokenizeScalar(u8, said, '\n'); + while (lines.next()) |line| if (std.mem.startsWith(u8, line, "agree")) { + totals.agree += 1; + } else { + totals.differ += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s quiet check: {s}\n", .{ r.seed, r.rtt_ms, id, line }); + }; + } + const rp = cl.r orelse continue; + cl.proc.enter(); try totals.add(&rp.stats); + if (cl.live == 0) continue; 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 }); + std.debug.print("seed {d} rtt {d} ms: client {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" }); + std.debug.print("seed {d} rtt {d} ms: client {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| { @@ -472,7 +1009,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }).terminal orelse continue; if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(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 }); + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); } } // ...and every file's text the authority's, byte for byte: a digest @@ -482,10 +1019,31 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { const mine = if (rp.core().panes[pid]) |pane| pane.file else null; if (mine == null or !std.mem.eql(u8, f.content, mine.?.content)) { totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: replica {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); + std.debug.print("seed {d} rtt {d} ms: client {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); } } } + session.enter(); +} + +/// A typist: keys 50-200 ms apart, a pause now and then. +fn typistGap(random: std.Random) u64 { + return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); +} + +/// A file's bytes, or null. +fn readAll(path: [:0]const u8) ?[]u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return null; + defer _ = libc.close(fd); + var out: std.ArrayListUnmanaged(u8) = .empty; + var buf: [4096]u8 = undefined; + while (true) { + const k = libc.read(fd, &buf, buf.len); + if (k <= 0) break; + out.appendSlice(gpa, buf[0..@intCast(k)]) catch return null; + } + return out.toOwnedSlice(gpa) catch null; } /// A .patch looked at opens a +Diff, whose rows are made from files read @@ -1313,7 +1871,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .screen_up => { if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); }, - .output => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit => {}, } } const s = rp.echo.stats; @@ -1591,9 +2149,8 @@ pub fn main(init: std.process.Init) !void { var seeds: u64 = 4; var first: u64 = 0; var steps: usize = 120; - var clients: u16 = 3; + var clients: u16 = 5; var rtts: []const u64 = &.{ 30, 80, 207 }; - var shared = false; var echo_mode = false; var flood_mb: u64 = 8; var screen_dir: ?[]const u8 = null; @@ -1601,10 +2158,6 @@ pub fn main(init: std.process.Init) !void { 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 (std.mem.eql(u8, name, "--echo")) { echo_mode = true; continue; @@ -1637,13 +2190,15 @@ pub fn main(init: std.process.Init) !void { } var failed = !try diffCase(dir); if (!try plumbCase(dir)) failed = true; - 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("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, 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); + var join_lines: std.ArrayList(u8) = .empty; + defer join_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); + for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .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, @@ -1671,9 +2226,12 @@ pub fn main(init: std.process.Init) !void { t.screens_checked, t.screens_wrong, }); - if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0) failed = true; + try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>5}/{d:<5} {d:>7}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.agree, t.differ, t.resizes }); + if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 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}); + std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left; quiet checks of the session's digest agreed/differed; resizes the windows posted\n", .{}); + std.debug.print(" rtt joins refused rejoined detached agree/differ resizes\n{s}", .{join_lines.items}); if (failed) std.process.exit(1); } |
