diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-19 13:16:15 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-19 15:09:19 -0300 |
| commit | 64b8951d198aa0dcd0a544abd6f103693b5205aa (patch) | |
| tree | cff708424e603229e4008d7e6aa0ed1af04b9fe3 /test | |
| parent | 280a2954152d3206f057055b0d59ca0ddc70485a (diff) | |
| download | pardes-64b8951d198aa0dcd0a544abd6f103693b5205aa.tar.gz pardes-64b8951d198aa0dcd0a544abd6f103693b5205aa.zip | |
replicas: the soak's session is THE session loop (the reorganisation's runners, step 10c, its second part; the user's rule: replica bugs caught by a soak that does what real use does): test/replicas.zig runs runtime/session.zig's Loop over a frontend of its own (Soak) whose host's wait_input is the soak's delayed net, with its clients' links in memory (Peers.threads false: the soak is each Peer's reader, Peer.take then a posted gone, and its writer, the welcome and the dump with its blobs put back then the Peer's queue, a frame a message down the link; a socket pair a dial, its dup handed as the daemon hands one, so a refusal, a Detach's shutdown and a let-go close are the real ones), so the session's pump, Peers.boundary's order (the pump's unit, then joins, inputs, checks and leaves as posted), Peers.input, join (its dump, pins, refusal), leave (a view kept or closed), detach and the teardown in the loop's order are the shipped ones, not Authority's imitation; what a soak's session opens is what run opens (the allocators and their Debug leak check, the workers, the addons' scan, the prompt files and a 9P listener, both in the soak's own runtime directory, XDG_RUNTIME_DIR set to it): no branch for a test in the loop; the two traps the agent before named are handled at the wait's end (the tape stepped, the session core's field and the held trees put back) and a third found (a client's own frame is drawn with no tape stepped, so client-side work inside the wait runs with tape.on null); the wait ends where a terminal's would (its own input, an echo, a client's post, a dial, a worker's draw, the core's timeout; a pty's output paced to the frame's tick, a person's input held behind it as tui.zig's split holds it); the run ends inside its last wait when nothing is in flight (every typist done, the flood over, two seconds of frames: the session's own wakes and the clients' quiet checks no longer taken, as each idle client's check wakes the session whose pump's unit asks the next check, a loop found here); core/replica.zig: Peers.threads, Peers.flushed (each terminal's version recorded after a flush), Peers.post and Peer.take pub; core/Kind.zig (a line the soak forced: its region allocator's leak check found it): a draw that lands after its pane closed is dropped, never kept in Kind.ready for the life of the process; replicas --clients 5 (4 seeds, Debug): diverged 0/0/0, unequal 0/0/0, deltas checked/wrong 1776/0 1832/0 1638/0, quiet checks 694/0 654/0 694/0, unlisted 0/0/0 at rtt 30/80/207 (inputs 1721/1864/1499, units 25712/27409/22491: a unit a pump now, as a session sends them); the corpus-through-a-client check fails at its step 21 (a resize) on the base as here; tui core-test 838/981 (143 skipped), shell-test 1017/1020 (the base's 1016/1019 and change 3's test), term-test 15/15, pane-test 183/184, kitty-test 45/45, behaviour-test 275/275 and --replay 275/275, process-test 2 of 144 failed (lspcomplete and lspcompletemoved, the base's; lsp-client failed once and passed again in the run), gui unit-test 1615/1619 and BaselineHarnessMismatch (the base's), replicas --clients 5 as above (the corpus through a client 22 scenes the same: its step 21 differs only when TMPDIR is a longer path, on the base too), daemon.py plain, --far, --window-clients, --upgrade both ways (pardes-tree's pfx-base) pass, --games failed in the gate's run (a client's keys at a kind's pane, as the base's do under load: reports/pardes-runners-d.md), cross_replay tui and gui 27 digests agree, macOS library (Linux and aarch64-macos) and FreeBSD tui build, rollback-bench runs (the suites run on this change with change 3 on top); the frame and perf gate against tree1 (run5-1, on the tree with both changes): PASS, frames 77/77 byte-identical, corpus2x -0.151% (bar 0.4%), the 97 per-operation counts within 0.1% (largest +0.031%)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'test')
| -rw-r--r-- | test/replicas.zig | 1458 |
1 files changed, 863 insertions, 595 deletions
diff --git a/test/replicas.zig b/test/replicas.zig index 69207970..7f7ca0b3 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1,6 +1,8 @@ //! pardes-replicas: a session and its clients in one process -//! (core/replica.zig): the session's own frontend typing in its view and -//! drawing it, and each client (THE client loop, runtime/client.zig, over a +//! (core/replica.zig): the session THE session loop (runtime/session.zig, +//! the terminal's and the window's) over a frontend of the soak's, its +//! clients' links in memory and its devices answered from memory, its own +//! frontend typing in its view and drawing it, and each client (THE client loop, runtime/client.zig, over a //! terminal's frontend or a window's, by turns, drawing no pixels) 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 @@ -41,11 +43,14 @@ const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; const client_loop = @import("runtime").client; +const session_loop = @import("runtime").session; const screen_state = @import("term").screen_state; const Echo = pardes.Echo; const Key = pardes.Key; const gpa = std.heap.c_allocator; +/// Its session's joins and leaves, said at `info`, are no news here. +pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; /// The PDF the soak opens (`--pdf`), absolute. @@ -163,6 +168,10 @@ const Kind = enum { gone, /// A picture's draw done on a worker, onto its loop (`Draws`). draw, + /// A frame a client wrote, up its link to its Peer; a blob of the + /// session's down it. + up, + blob, }; const Msg = struct { @@ -430,24 +439,33 @@ fn screenHash(t: *screen_state.Terminal) u64 { /// counts its frames and keeps the facts a window reads beside them, and /// its wait is the delayed link's next message for it (a wake it asks for /// goes through the net). Its link is 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. +/// pair, a new one a dial, whose other end the session's Peer holds (a dup) +/// and the soak reads as that Peer's reader would (`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 }, loop: ClientLoop = undefined, r: ?*replica.Replica = null, - fds: [2]c_int = .{ -1, -1 }, + /// Its link's socket pair: its own end (its Link's) and the session's, + /// which the soak reads (`drain`); the dup of the session's end handed + /// at its dial (`Peers.handed`), until the session's boundary took it. + cfd: c_int = -1, + sfd: c_int = -1, + handed: c_int = -1, + /// The session's Peer for it while that link is the session's; what + /// it is sent taken from its queue as its writer would (`Soak.sent`). + peer: ?*replica.Peer = null, + /// That link ended at the session's side: shut by it (a Detach typed + /// in its view, cut off) or its reader's end posted (`Soak.up`). + shut: bool = false, + read_done: bool = false, 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). + /// What it wrote, read off the session's end: bytes not yet a frame. 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). + /// Its id and view at the session (its welcome's), and the view it + /// joins again for (`back`, after a divergence). id: u16 = 0, - sid: u16 = 0, view: u8 = 0, back: ?u8 = null, digest: u64 = 0, @@ -455,7 +473,6 @@ const Client = struct { /// 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, @@ -565,6 +582,15 @@ const Client = struct { pub fn open(cl: *Client, _: []const u8) void { cl.asked[2] += 1; } + + /// Its link's socket pair let go (the link it had is over). + fn closeLink(cl: *Client) void { + for ([_]*c_int{ &cl.cfd, &cl.sfd }) |fd| if (fd.* >= 0) { + _ = libc.close(fd.*); + fd.* = -1; + }; + cl.got.clearRetainingCapacity(); + } }; const ClientLoop = client_loop.Loop(Client); @@ -593,53 +619,21 @@ const Net = struct { } }; -/// 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. +/// What client `c` wrote to its socket since (its inputs and their stamps, +/// its terminal messages, a check asked, its bye), read off the session's +/// end, a frame a message up its link: the session's Peer takes each as it +/// comes (`Soak.up`), as its reader thread would. fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { + if (cl.sfd < 0) return; var buf: [1 << 16]u8 = undefined; while (true) { - const k = libc.read(cl.fds[0], &buf, buf.len); + const k = libc.read(cl.sfd, &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 }); + while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { + try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); } 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); @@ -696,7 +690,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, const r = cl.r.?; const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(cl.fds[1], r.diverged != null); + if (!link.gone) replica.bye(link.fd, r.diverged != null); try drain(cl, c, net, now); cl.live = 0; if (r.diverged) |why| { @@ -722,15 +716,797 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, } } -fn run(r: Run, dir: []const u8, totals: *Totals) !void { +/// When the session's shell's program prints (`.output`): a full-screen +/// program, a shell's session, then the flood. +const tui_at: u64 = 400_000; +const session_at: u64 = 1_000_000; +const flood_at: u64 = 2_500_000; + +const SessionLoop = session_loop.Loop(Soak); + +/// The session's own frontend, a terminal's with its devices answered from +/// memory: THE session loop (runtime/session.zig, the terminal's and the +/// window's) runs over it. Its clients' links are in memory +/// (`Peers.threads` false): the soak is each Peer's reader (`up`) and +/// writer (`sent`). Its host is the soak's, and the host's wait +/// (`waitInput`) is the soak's net: the session's own typist, its shell's +/// program and echoes, its frames and its workers' draws, the clients' +/// dials and messages up their links end the wait as a terminal's events +/// do (tui.zig `waitInput`); every client's own loop runs inside it on what +/// comes down its link. The run ends inside its last wait, when nothing is +/// in flight: every client checked against the session there, its core +/// still whole. +const Soak = struct { + r: Run, + totals: *Totals, + random: std.Random, + net: *Net, + clients: []Client, + looks: []const []const u8, + with_pdf: bool, + /// What the shell's program prints (`.output`). + tui: []const u8, + shell_session: []const u8, + yes: []const u8, + l: *SessionLoop = undefined, + /// What failed inside the loop (its wait returns nothing): the run's. + err: ?anyerror = null, + + // ---- its host ---- + /// A pty that echoes what it is written, 2 ms later, as a shell's. + echo: std.ArrayListUnmanaged(struct { pane: u8, bytes: []u8 }) = .empty, + /// The session's clock (tui.zig `clockNow`): the soak's time at a + /// frame, an input of its own frontend's, a pty's read or a worker's + /// draw; a pump woken by a client's mail alone reads the last again. + now_ns: u64 = std.time.ns_per_s, + /// A client's view whose Detach a step took (tui.zig `detach`: + /// `Peers.detach` shut its link; the session's own view's is its + /// terminal's, which the soak has none of). + detach_view: ?u8 = null, + + // ---- the soak ---- + /// The soak's time (us): the last message's. + now: u64 = 0, + aim: Aim = .{ .shell = null, .pdf = null }, + shell: u8 = 0, + own_left: usize, + own_script: Script = .{}, + /// Typists not done: the session's own and every client's. + typing: usize, + frames_left: u32 = 0, + flood_end: u64 = 0, + program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}, + /// The session's version of each terminal, as its screen showed then. + versions: std.AutoHashMapUnmanaged(u64, u64) = .empty, + flood_deltas: [8]u64 = @splat(0), + kinds_seen: u32 = 0, + /// Each client's link made (its first join), and its replica's. + has_link: [8]bool = @splat(false), + /// An input of its own frontend's held for the next wait, a pty's + /// output taken in this one (tui.zig `split`). + held: ?Msg = null, + /// The step boundary after a frame's wake under the flood: what its + /// encoding cost. + framed: bool = false, + encode_ns: u64 = 0, + /// A Peer's queue, swapped out as its writer swaps it (the Peers' + /// allocator's). + sending: std.ArrayListUnmanaged(u8) = .empty, + /// This wait ended at its frame's tick: its pump draws. + at_frame: bool = false, + + fn of(ctx: ?*anyopaque) *Soak { + return @ptrCast(@alignCast(ctx.?)); + } + + /// Its own view drawn at its frame's tick (`.frame`), as the soak's + /// session always drew it; not after every pump, as a terminal's is: + /// drawn so, the soak finds a client's step replayed with a kind's call + /// more than the session's (reports/pardes-runners-d.md). + fn watchedHost(ctx: ?*anyopaque) bool { + return of(ctx).at_frame; + } + + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = of(ctx); + s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; + } + + fn nowHost(ctx: ?*anyopaque) u64 { + return of(ctx).now_ns; + } + + fn detach(ctx: ?*anyopaque) void { + const s = of(ctx); + const k = s.l.core.live; + if (s.l.peers.detach(k)) s.detach_view = k; + } + + /// A kind's job on a worker, as tui.zig's `job` runs one: its answer + /// the session's own step `draw_us` later (`.draw`), as a worker's is + /// its loop's event (with no `job`, Effect.perform runs it at once on + /// the core's side, inside the perform that asked it, where no tape + /// records it: a client replays that perform without it). + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { + const core = of(ctx).l.core; + const j = pardes.host_io.KindJob.take(core, pane, serial, token) orelse return; + if (Draws.go(null, j)) return; + j.run(); + j.land(core); + } + + /// The wait inside the session's pump (tui.zig `waitInput`), until + /// what a terminal's loop would wake for: the soak's net. What its + /// clients' steps leave process-wide (the tape stepped, its core's + /// field, the held trees a rollback epoch selects: replica.zig + /// `Stepping.end` puts no epoch back) is the session's again before + /// it returns. + fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { + const s = of(ctx); + const core = s.l.core; + const on = pardes.tape.on; + const field = core.tape; + const trees = pardes.syntax.held_trees; + const done = s.wait(timeout_ms) catch |err| fail: { + s.err = err; + break :fail true; + }; + pardes.tape.on = on; + core.tape = field; + pardes.syntax.held_trees = trees; + if (!done) return; + // Nothing in flight: the run's end, every client checked against + // the session as it is now. + if (s.err == null) s.finish() catch |err| { + s.err = err; + }; + core.quit = true; + } + + const vtable = replica.everyEntry(.{ .watched = watchedHost, .pty_write = ptyWrite, .now = nowHost, .detach = detach, .job = job, .wait_input = waitInput }); + + // ---- the session loop's frontend ---- + + pub fn options(_: *Soak, _: *pardes.Options) void {} + + pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { + s.l = l; + l.peers.threads = false; + l.peers.flushed = .{ .ctx = s, .f = flushed }; + const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; + l.core.host = host; + return host; + } + + /// After the clients were let go: the clients' processes end, and what + /// is still in flight goes. + pub fn close(s: *Soak, _: *SessionLoop) void { + for (Draws.jobs.items) |j| j.drop(); + Draws.jobs.clearRetainingCapacity(); + for (s.clients, s.has_link[0..s.clients.len]) |*cl, made| { + if (cl.r) |rp| rp.deinit(); + cl.r = null; + cl.closeLink(); + cl.got.deinit(gpa); + gpa.free(cl.check); + if (made) { + cl.loop.link.check = null; + cl.loop.link.deinit(gpa); + } + } + while (s.net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); + if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); + for (s.echo.items) |e| gpa.free(e.bytes); + s.echo.deinit(gpa); + s.versions.deinit(gpa); + s.sending.deinit(s.l.peers.gpa); + } + + pub fn resumePtys(_: *Soak, _: anytype) void {} + + /// The tty's own boot (a raw shell, a text pane under it), then three + /// files looked at, and the picture and the PDF in a column of their + /// own (plain kinds' panes every client joins with, loaded from its + /// dump, the file read by its path): 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. Then everyone starts. + pub fn start(s: *Soak, l: *SessionLoop) !void { + const core = l.core; + for (s.looks[0..3]) |look| s.setup(.{ .command = look }); + if (s.looks.len > 3) { + s.setup(.{ .command = "Newcol" }); + s.setup(.{ .command = s.looks[3] }); + } + if (s.with_pdf) s.setup(.{ .command = s.looks[4] }); + s.shell = for (core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + // Where a wheel over the shell lands in the session's view, which a + // client's view is a copy of as it joins; and the PDF's body there. + const sr = core.view().rects[s.shell]; + const pr = if (s.with_pdf) core.view().rects[core.view().active] else pardes.Rect{}; + s.aim = .{ + .shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null, + .pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } else null, + }; + const net = s.net; + // 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. + for (s.clients, 0..) |*cl, c| { + cl.dialling = true; + const at: u64 = switch (c) { + 0, 1 => s.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 = &.{} }); + } + try net.send(.{ .at = s.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 = &.{} }); + } + + /// A setup's command, before anyone looks: no tape, no client. + fn setup(s: *Soak, ev: pardes.Event) void { + s.l.core.update(ev); + s.l.core.settle(); + } + + /// After each step boundary (`Peers.boundary`: the pump's unit, the + /// clients' inputs, joins and leaves taken in): what a Peer's writer + /// would write, down each link; a join taken or refused; a link the + /// session shut; the echoes its steps asked of the shell. + pub fn sent(s: *Soak) void { + s.sentOrFail() catch |err| { + if (s.err == null) s.err = err; + s.l.core.quit = true; + }; + } + + fn sentOrFail(s: *Soak) !void { + const ps = &s.l.peers; + const core = s.l.core; + const net = s.net; + const now = s.now; + // Those let go in the boundary (Peers.leave, letGo): gone. + for (s.clients) |*cl| if (cl.peer) |was| { + const there = for (ps.list) |slot| { + if (slot) |p| if (p == was and p.id == cl.id) break true; + } else false; + if (!there) cl.peer = null; + }; + // A join taken (its Peer holds the dup handed) or refused (its dup + // closed, daemon.refuseReplica): its writer's join first (the + // welcome, then the dump with the session's blobs put back where + // they go: Peer.writeJoin), its far word read (`far` false: on + // this machine), and its pins let go at the next boundary. + for (s.clients, 0..) |*cl, c| if (cl.handed >= 0) { + defer cl.handed = -1; + const peer = for (ps.list) |slot| { + if (slot) |p| if (p.fd == cl.handed) break p; + } else { + s.totals.refused += 1; + try net.toClient(c, now, .refused, cl.gen, &.{}); + continue; + }; + const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + errdefer whole.deinit(gpa); + var pos: usize = 0; + for (peer.blobs.items) |b| { + try whole.appendSlice(gpa, peer.dump[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, peer.dump[pos..]); + var word: [16]u8 = undefined; + const far = try pardes.wire.encodeClient(&word, .{ .far = false }); + _ = peer.take(far[0], far[pardes.wire.header_len..]); + ps.post(.{ .joined = peer }); + cl.peer = peer; + cl.shut = false; + cl.read_done = false; + cl.gen += 1; + cl.id = welcome.client; + cl.view = welcome.view; + cl.digest = welcome.digest; + s.totals.joins += 1; + try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + }; + // A Detach typed in a client's view, or one cut off for its lag: its + // link shut, it hears its end and nothing after; its reader's end + // said (the next boundary lets it go). + if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view == k and !cl.shut) { + cl.shut = true; + }; + s.detach_view = null; + const flooding = now >= flood_at and s.flood_end == 0; + for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { + if (peer.cut) cl.shut = true; + const io = ps.io; + peer.lock.lockUncancelable(io); + std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &s.sending); + peer.lock.unlock(io); + defer s.sending.clearRetainingCapacity(); + if (cl.shut) { + if (!cl.read_done) { + cl.read_done = true; + ps.post(.{ .gone = peer }); + try net.toClient(c, now, .gone, cl.gen, &.{}); + } + continue; + } + var at: usize = 0; + while (try pardes.wire.framed(s.sending.items[at..])) |f| : (at += f.total) { + const tag = std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame; + switch (tag) { + .unit => { + s.totals.unit_bytes += f.payload.len; + if (flooding) s.totals.flood_unit_bytes += f.payload.len; + try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .screen => { + if (f.payload[5] == 1) { + s.totals.deltas += 1; + s.totals.delta_bytes += f.payload.len; + if (flooding) s.totals.flood_delta_bytes += f.payload.len; + } else s.totals.filled_bytes += f.payload.len; + try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .check => { + const d = try gpa.alloc(u8, 8); + std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); + try net.toClient(c, now, .checked, cl.gen, d); + }, + .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), + else => return error.UnexpectedFrame, + } + } + if (at != s.sending.items.len) return error.TornFrame; + }; + // The kinds' panes it has opened, each counted once. + for (core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen) { + s.kinds_seen = pane.serial; + for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); + }; + for (s.echo.items) |e| try net.send(.{ .at = now + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); + s.echo.clearRetainingCapacity(); + if (s.framed) { + s.framed = false; + if (now >= flood_at and (s.flood_end == 0 or now <= s.flood_end)) try s.totals.frame_ns.append(gpa, ps.screens.encode_ns - s.encode_ns); + } + } + + /// Each terminal at its version as the session's screen shows it now + /// (after a flush: `Peers.flushed`). + fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { + const s: *Soak = @ptrCast(@alignCast(ctx)); + for (&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; + _ = core.panes[id] orelse continue; + s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)) catch |err| { + s.err = err; + }; + }; + } + + pub fn upgradeAsked(_: *Soak) void {} + pub fn note(_: *Soak, _: anytype) void {} + /// No Restore is typed here (host_io.restoreCore is the session's own). + pub fn watched(_: *Soak) session_loop.Watched { + unreachable; + } + pub fn restoring(_: *Soak, _: *pardes.Pardes) void {} + pub fn restored(_: *Soak, _: *SessionLoop) void {} + + /// The session's clock moved to the soak's time. + fn clock(s: *Soak) void { + s.now_ns = std.time.ns_per_s + s.now * 1000; + } + + /// The net until the session's loop would wake: true when nothing is + /// in flight any more (the run's end). + fn wait(s: *Soak, timeout_ms: u32) !bool { + const core = s.l.core; + const net = s.net; + // An input of its own held while a pty's output was taken: the step + // after reads the terminal as the clients' deltas bring it. + if (s.held) |m| { + s.held = null; + try s.own(m); + return false; + } + var took_output = false; + s.at_frame = false; + // What its boundary took is old news. + _ = s.l.peers.urgent.swap(false, .acq_rel); + while (true) { + const next = net.q.peek() orelse return !took_output; + // Every typist done, the flood over and its frames' two seconds + // past: what is in flight is delivered and the run ends. The + // session's own wakes (a blink, a game of life's tick) and the + // clients' (their quiet checks) go on in a real session; here + // they are no longer taken. Each idle client's check wakes the + // session, whose pump's unit is a change that asks the next + // check: they would never stop. + const ending = s.typing == 0 and s.flood_end != 0 and s.frames_left == 0; + // The core's next wake (its timeout), on the soak's clock. + if (!ending and timeout_ms != 0 and next.at > s.now + @as(u64, timeout_ms) * 1000) { + s.now += @as(u64, timeout_ms) * 1000; + s.clock(); + return false; + } + const m = net.q.pop().?; + var kept = false; + defer if (!kept and m.bytes.len > 0) gpa.free(m.bytes); + s.now = m.at; + Draws.now = m.at; + // 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 = &s.clients[c]; + // A client's own process steps nothing of the session's: no + // tape is stepped in it between its steps (tape.enter's check), + // and no rollback epoch's trees are held. + const in_client = switch (m.kind) { + .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => true, + .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), + else => false, + }; + const session_on = pardes.tape.on; + const session_trees = pardes.syntax.held_trees; + if (in_client) { + pardes.tape.on = null; + pardes.syntax.held_trees = null; + } + defer if (in_client) { + pardes.tape.on = session_on; + pardes.syntax.held_trees = session_trees; + }; + switch (m.kind) { + // ---- the session ---- + .own => { + if (took_output) { + kept = true; + s.held = m; + return false; + } + try s.own(m); + return false; + }, + // A pty's read: its echo drawn at once (an input's), the + // program's output a frame a tick (tui.zig `waitInput`). + .echo => { + s.clock(); + core.update(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } }); + return false; + }, + .output => { + s.clock(); + // The program's next read, 4 KB, then the next a + // fraction of a millisecond on (ghostty's pace). + if (s.program.at == s.program.bytes.len) { + s.program = .{ .bytes = switch (m.who) { + 0 => s.tui, + 1 => s.yes, + else => s.shell_session, + } }; + } + const k = @min(s.program.bytes.len - s.program.at, if (m.who == 1) @as(usize, 4096) else 700); + const chunk = s.program.bytes[s.program.at..][0..k]; + s.program.at += k; + if (s.program.at < s.program.bytes.len) + 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) s.flood_end = m.at; + core.update(.{ .output = .{ .pane = s.shell, .bytes = chunk } }); + took_output = true; + }, + .frame => { + // Its own frontend's frame: its loop woken when output + // came, a frame is owed or the core's next wake is due. + s.clock(); + // Frames go on while anyone types or the flood runs, and + // two seconds after (a session with a clock wakes on: a + // blink, a kind's tick; what is in flight still comes). + const busy = s.typing > 0 or s.flood_end == 0; + s.frames_left = if (busy) 120 else s.frames_left -| 1; + if (s.frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); + if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) { + s.at_frame = true; + s.framed = true; + s.encode_ns = s.l.peers.screens.encode_ns; + return false; + } + }, + // A client's connection, handed over by the daemon (tui.zig + // `.replica`): joined at the session's next step boundary, + // on a socket pair of its own. + .dial => { + cl.closeLink(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + _ = libc.fcntl(fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); + cl.sfd = fds[0]; + cl.cfd = fds[1]; + cl.handed = libc.dup(fds[0]); + if (cl.handed < 0) return error.NoSocket; + s.l.peers.handed(cl.handed, cl.back); + return false; + }, + // What a client wrote, at the session's end of its link: its + // Peer's reader takes it (Peer.take), and a link it ends + // (its bye) is gone (its reader's end, posted). + .up => { + const peer = cl.peer orelse continue; + if (m.gen != cl.gen or cl.read_done or cl.shut) continue; + const f = (try pardes.wire.framed(m.bytes)) orelse return error.BadFrame; + if (ending and f.tag == @backingInt(pardes.wire.ClientTag.check)) continue; + if (f.tag == @backingInt(pardes.wire.ClientTag.screen_ack) and f.payload.len >= 22 and f.payload[5] == 2) + s.totals.fetched += std.mem.readInt(u64, f.payload[14..22], .little) - std.mem.readInt(u64, f.payload[6..14], .little); + if (!peer.take(f.tag, f.payload)) { + cl.read_done = true; + s.l.peers.post(.{ .gone = peer }); + } + // A reader's post wakes the loop (tui.zig `.replica_mail`): + // an input, a join, a check or a leave at once; a + // terminal's acknowledgement as a pty's output does, + // at the frame when output came in this wait. + if (s.l.peers.urgent.swap(false, .acq_rel)) return false; + if (s.l.peers.mail.load(.acquire) and !took_output) return false; + }, + .draw => { + // A worker's draw done, onto the loop of the core that + // asked it (tui.zig `.kind_job`): kept for its pane's + // next paint, a frame owed; one of a core gone since is + // let go. + const j = Draws.jobs.orderedRemove(0); + j.run(); + // A state job's answer: a step of the session's own. + if (j.draw == null) { + s.clock(); + core.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); + j.drop(); + return false; + } + if (j.draw == @as(?*const pardes.Pardes, core)) { + s.clock(); + pardes.Kind.landDraw(core, j); + return false; + } + const k = for (s.clients, 0..) |*dc, k| { + if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k; + } else { + j.drop(); + continue; + }; + const dc = &s.clients[k]; + pardes.Kind.landDraw(dc.r.?.core(), j); + // Into the core it holds while it joins again: its loop + // is not running (replica.join waits for the dump). + if (dc.live == 0) continue; + dc.loop.link.dirty = true; + try woke(dc, k, net, m.at, s.totals, s.r); + if (dc.loop.link.quit) try ended(dc, k, net, m.at, s.totals, s.r, &s.typing); + }, + // ---- 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| { + try s.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(s.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) s.typing -= 1; + cl.left = 0; + } + }, + .dump => try s.joined(cl, c, m), + .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => { + 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; + cl.now = m.at; + cl.loop.link.now = m.at * 1000; + switch (m.kind) { + .input => { + var buf: [64]u8 = undefined; + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script); + cl.loop.input(ev); + cl.left -= 1; + if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { + s.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.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.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.loop.take(.{ .screen = try std.heap.c_allocator.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) s.totals.resets += 1 else { + // Applied: the screen is the session's at that version. + s.totals.screens_checked += 1; + const want = s.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)) { + s.totals.screens_wrong += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the session's\n", .{ s.r.seed, s.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 (s.flood_end == 0 or m.at <= s.flood_end + net.one_way)) s.flood_deltas[c] += 1; + } + }; + }, + .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), + .wake => { + // One the next replaced is no wake. + if (m.at != cl.wake_at or ending) continue; + cl.wake_at = 0; + }, + .quit => cl.loop.link.quit = true, + .gone => { + cl.loop.link.quit = true; + cl.loop.link.gone = true; + }, + else => unreachable, + } + try woke(cl, c, net, m.at, s.totals, s.r); + if (cl.loop.link.quit) try ended(cl, c, net, m.at, s.totals, s.r, &s.typing); + }, + .to_authority, .screen_up, .client_frame, .check_up, .bye_up => unreachable, + } + } + } + + /// An input of its own frontend's, in the view it shows (the first: + /// tui.zig `Shell.apply` goes into `s.own`). + fn own(s: *Soak, m: Msg) !void { + const core = s.l.core; + s.clock(); + var buf: [64]u8 = undefined; + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script); + core.toView(0); + core.update(ev); + s.own_left -= 1; + if (s.own_left > 0) try s.net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else s.typing -= 1; + } + + /// Its dump at the client (replica.join): the core it left let go once + /// the new one is here, the dump loaded and checked by the digest, + /// then the loop's join (Loop.run): its first inputs, a pass up to its + /// wait. + fn joined(s: *Soak, cl: *Client, c: usize, m: Msg) !void { + const net = s.net; + cl.dialling = false; + cl.tries = 0; + if (cl.r) |old| { + try s.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, .distrusted = &cl.distrusted }); + cl.r = rp; + rp.stats.samples = true; + rp.t.local_files = true; + rp.echo.now = m.at * 1000; + if (!rp.loaded(cl.digest)) { + s.totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ s.r.seed, s.r.rtt_ms, m.who }); + } + cl.live = m.gen; + var j: replica.Joined = .{ .fd = cl.cfd, .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; + if (!s.has_link[c]) { + cl.loop = .{ .link = .{ .r = rp, .fd = cl.cfd, .check = cl.check }, .fe = cl, .frames = &cl.frames }; + s.has_link[c] = true; + if (c == 1) cl.loop.link.test_diverge = 40; + } + cl.c = c; + cl.net = net; + cl.now = m.at; + cl.wake_at = 0; + cl.stops = rp.stats.stops; + cl.loop.link.now = m.at * 1000; + cl.loop.link.reset(rp, &j); + cl.posted = null; + cl.start(&cl.loop); + _ = cl.loop.pass(); + judgeStops(cl, c, s.totals, s.r); + try drain(cl, c, net, m.at); + if (cl.left > 0 and cl.left == s.r.steps) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + } + + /// At quiescence: every client's digest the session's, its terminals + /// the session's cell for cell, its files' texts byte for byte. + fn finish(s: *Soak) !void { + const totals = s.totals; + const core = s.l.core; + totals.flood_us += s.flood_end -| flood_at; + for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; + const want = pardes.tape.digestOf(core); + for (s.clients, 1..) |*cl, id| { + totals.resizes += cl.resizes; + totals.wakes += cl.wakes; + for (&totals.asked, cl.asked) |*t, n| t.* += n; + if (s.has_link[id - 1]) totals.draws += cl.loop.link.draws; + // 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", .{ s.r.seed, s.r.rtt_ms, id, line }); + }; + } + const rp = cl.r orelse continue; + 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: client {d} diverged: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, why }); + } else if (!rp.quiet() or rp.digest() != want) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" }); + } + // At quiescence, every terminal the session's, cell for cell. + for (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(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } + } + // ...and every file's text the session's, byte for byte: a digest + // takes a text of 4 KiB and up by its length (core/walk.zig). + for (core.panes, 0..) |slot, pid| { + const f = (slot orelse continue).file orelse continue; + 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: client {d}'s text {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } + } + } + } +}; + +fn run(init: std.process.Init, 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; var look_lines: [8][300]u8 = undefined; var looks_buf: [8][]const u8 = undefined; @@ -763,89 +1539,22 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}{s}", .{ pdf_path.?, at }); nlooks += 1; }; - const looks = looks_buf[0..nlooks]; - // The tty's own boot (a raw shell, a text pane under it), then three - // 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. - host.clocked = true; - host.now_ns = std.time.ns_per_s; - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .addons = kinds }, host.host(), true); - defer a.deinit(); - host.core = a.core; - var screens: replica.Screens = .init(gpa); - defer screens.deinit(a.core); - for (&paths) |*path| { - var line: [300]u8 = undefined; - _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) }); - } - // The picture and the PDF in a column of their own: every client joins - // with them (a plain kind's pane loaded from a dump, its file read by - // its path), its keys go to the one it is in when it has them. - if (looks.len > 3) { - _ = try a.local(.{ .command = "Newcol" }); - _ = try a.local(.{ .command = looks[3] }); - } - if (with_pdf) _ = try a.local(.{ .command = looks[4] }); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - // Where a wheel over the shell lands in the session's view, which a - // client's view is a copy of as it joins; and the PDF's body there. - const sr = a.core.view().rects[shell]; - const pr = if (with_pdf) a.core.view().rects[a.core.view().active] else pardes.Rect{}; - const aim: Aim = .{ - .shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null, - .pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } 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); - } + defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; defer { pardes.Kind.drawer = null; Draws.net = null; - for (Draws.jobs.items) |j| j.drop(); - Draws.jobs.clearRetainingCapacity(); } - // 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| { - 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.loop.link.check = null; - cl.loop.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 @@ -856,472 +1565,24 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { 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; - 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); - - // The session's own typist, and every client's, until each is done. - var own_left = r.steps; - var own_script: Script = .{}; - 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 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, - host: *Host, - kinds_seen: *u32, - - /// A Detach its step took (Host.detach) in a client's view: that - /// client's link shut inside the step, before its unit goes - /// (Peers.detach), so it hears its end and not the unit; which it is. - fn detaching(s: @This(), now: u64) !?usize { - const k = s.host.detach_view orelse return null; - s.host.detach_view = null; - for (s.clients, 0..) |*cl, c| if (cl.joined and cl.view == k) { - cl.joined = false; - s.screens.dropPeer(cl.sid); - try s.net.toClient(c, now, .gone, cl.gen, &.{}); - return c; - }; - return null; - } - - /// ...and let go at the next boundary, its view closed (Peers.leave). - fn detached(s: @This(), c: ?usize, now: u64) !void { - const gone = c orelse return; - try s.unit(try s.a.leave(s.clients[gone].id, false), now, false); - } - - /// 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 { - // The kinds' panes it has opened, each counted once. - for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) { - s.kinds_seen.* = pane.serial; - for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); - }; - 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)); - }; - } + var soak: Soak = .{ + .r = r, + .totals = totals, + .random = random, + .net = &net, + .clients = clients[0..r.clients], + .looks = looks_buf[0..nlooks], + .with_pdf = with_pdf, + .tui = tui, + .shell_session = shell_session, + .yes = yes, + .own_left = r.steps, + .typing = r.clients + 1, }; - var kinds_seen: u32 = 0; - - const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals, .host = &host, .kinds_seen = &kinds_seen }; - - while (net.q.pop()) |m| { - defer if (m.bytes.len > 0) gpa.free(m.bytes); - Draws.now = m.at; - 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) { - // ---- the session ---- - .own => { - host.now_ns = std.time.ns_per_s + m.at * 1000; - var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, aim, looks, &own_script); - try ses.pending(m.at, flooding); - try ses.flush(m.at, null); - const u = try a.own(ev); - // Its own view's Detach is its terminal's: none here. - host.detach_view = null; - 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(); - 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 => { - // A pty's read wakes its loop as an input does; a client's - // mail alone leaves the clock where it was. - if (m.kind != .to_authority) host.now_ns = std.time.ns_per_s + m.at * 1000; - 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 => 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 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; - 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 (Peers.input). - try ses.pending(m.at, flooding); - try ses.flush(m.at, null); - break :in try a.take(m.bytes); - }, - }; - if (unit) |u| { - const gone = try ses.detaching(m.at); - try ses.unit(u, m.at, false); - try ses.detached(gone, m.at); - 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 => { - // Its own frontend's frame: its loop woken when a frame is - // owed or the core's next wake is due, a pump that advances - // its clock (what is due ticks: messages, glides, a kind's - // tick) and draws its view, as its host's loop paces it. - host.now_ns = std.time.ns_per_s + m.at * 1000; - if (a.core.needs_frame or (a.core.nextWake() orelse std.math.maxInt(u64)) <= host.now_ns) { - host.draws = true; - a.pump(); - host.draws = false; - } - try ses.pending(m.at, flooding); - const t0 = screens.encode_ns; - const before = totals.delta_bytes; - 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 anyone types or the flood runs, and two - // seconds after (a session with a clock wakes on: a blink, a - // kind's tick; what is in flight still comes, unpumped). - const busy = typing > 0 or flood_end == 0; - frames_left = if (busy) 120 else frames_left -| 1; - if (frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); - }, - .dial => { - // Peers.join at the session's next boundary: its view kept - // for it, or a new one, or refused when all are taken. - 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 => { - 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. - 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); - }, - .screen_up => { - 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, 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| { - 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.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, .distrusted = &cl.distrusted }); - 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.loop = .{ .link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }, .fe = cl, .frames = &cl.frames }; - has_link[c] = true; - if (c == 1) cl.loop.link.test_diverge = 40; - } - cl.c = c; - cl.net = &net; - cl.now = m.at; - cl.wake_at = 0; - cl.stops = rp.stats.stops; - cl.loop.link.now = m.at * 1000; - cl.loop.link.reset(rp, &j); - cl.posted = null; - // The loop's join (Loop.run): its first inputs, then a pass - // up to its wait. - cl.start(&cl.loop); - _ = cl.loop.pass(); - judgeStops(cl, c, totals, r); - try drain(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 = &.{} }); - }, - .draw => { - // A worker's draw done, onto the loop of the core that asked - // it (tui.zig `.kind_job`): kept for its pane's next paint, - // a frame owed; one of a core gone since is let go. - const j = Draws.jobs.orderedRemove(0); - j.run(); - // A state job's answer: a step of the session's own. - if (j.draw == null) { - host.now_ns = std.time.ns_per_s + m.at * 1000; - a.output(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); - j.drop(); - continue; - } - if (j.draw == @as(?*const pardes.Pardes, a.core)) { - pardes.Kind.landDraw(a.core, j); - continue; - } - const k = for (clients[0..r.clients], 0..) |*dc, k| { - if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k; - } else { - j.drop(); - continue; - }; - const dc = &clients[k]; - pardes.Kind.landDraw(dc.r.?.core(), j); - dc.loop.link.dirty = true; - try woke(dc, k, &net, m.at, totals, r); - if (dc.loop.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing); - }, - .input, .to_replica, .screen_down, .checked, .wake, .quit, .gone => { - 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; - cl.now = m.at; - cl.loop.link.now = m.at * 1000; - switch (m.kind) { - .input => { - var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, aim, looks, &cl.script); - cl.loop.input(ev); - 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.loop.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.loop.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.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), - .wake => { - // One the next replaced is no wake. - if (m.at != cl.wake_at) continue; - cl.wake_at = 0; - }, - .quit => cl.loop.link.quit = true, - .gone => { - cl.loop.link.quit = true; - cl.loop.link.gone = true; - }, - else => unreachable, - } - try woke(cl, c, &net, m.at, totals, r); - if (cl.loop.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing); - }, - .client_frame => {}, - } - } - totals.flood_us += flood_end -| flood_at; - for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d; - const want = replica.digestOf(a); - for (clients[0..r.clients], 1..) |*cl, id| { - totals.resizes += cl.resizes; - totals.wakes += cl.wakes; - for (&totals.asked, cl.asked) |*t, n| t.* += n; - if (has_link[id - 1]) totals.draws += cl.loop.link.draws; - // 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; - 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: 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: 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| { - 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(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) { - totals.unequal += 1; - 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 - // takes a text of 4 KiB and up by its length (core/walk.zig). - for (a.core.panes, 0..) |slot, pid| { - const f = (slot orelse continue).file orelse continue; - 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: client {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); - } - } - } + // The session: THE session loop, from its start to its end. + try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); + if (soak.err) |err| return err; } /// A typist: keys 50-200 ms apart, a pause now and then. @@ -2169,7 +2430,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, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob => {}, } } const s = rp.echo.stats; @@ -2486,6 +2747,9 @@ pub fn main(init: std.process.Init) !void { 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); + // Its session's socket goes there: a directory of its own alone. + var dir_z: [256]u8 = undefined; + _ = libc.chmod(try std.fmt.bufPrintSentinel(&dir_z, "{s}", .{dir}, 0), 0o700); defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {}; // Its own data directory, the only one its addon scan reads (never the // user's): the libraries it was given (`--addon`), as a user's are @@ -2510,6 +2774,10 @@ pub fn main(init: std.process.Init) !void { var failed = !try diffCase(dir); if (!try plumbCase(dir)) failed = true; if (!try corpusCase(dir)) failed = true; + // ...and its own runtime directory: its session's 9P socket and prompt + // files (runtime/session.zig opens them), never the user's. + var runtime_buf: [300]u8 = undefined; + if (setenv("XDG_RUNTIME_DIR", try std.fmt.bufPrintSentinel(&runtime_buf, "{s}", .{dir}, 0), 1) != 0) return error.NoRuntimeDir; 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 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; @@ -2520,7 +2788,7 @@ pub fn main(init: std.process.Init) !void { defer stop_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, .flood_mb = flood_mb }, dir, &t); + for (first..first + seeds) |seed| try run(init, .{ .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:>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, |
