//! pardes-replicas: a session and its clients in one process //! (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 //! 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 the pty's bytes in the session's units: the //! session's shell pane runs a full-screen program and then a flood //! (`--flood` MB of `yes`, then as much of a `cat` of source text) while the //! clients type, and each client feeds its own emulators what its units //! carry, in the tape's order. //! //! 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] //! //! `--echo` types a corpus into a shell instead, with and without the //! predicted echo (core/term/echo.zig), and gates what it draws: below, at //! "predicted echo". //! //! Gates, per seed and RTT: no replica diverges (every confirmed unit's //! digests agree as it is replayed), and at quiescence every replica's //! digest and every file's text are the authority's, and every terminal //! the authority's, cell for cell. Reported per RTT: how inputs went //! (applied at once, stopped at a host call, left to the authority), how //! units were taken (fast path, rollback for a misprediction or another's //! input), what a speculative apply, a copy and a rollback cost against a //! frame, and a peer's unit bytes a second under the flood. const std = @import("std"); 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 term = @import("term"); 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; /// `--witness`: the witness judged at every run's end, not only after a /// divergence (`Witness`). var witness_always = false; /// `--pair`: client 0 is the session's pair client (Options.pair: a /// terminal's `pardes` as a client and its session): joined before the /// session's first effects, its core its own boot (replica.ownBoot), the /// welcome's digest its check (confirmBoot), the session's own frontend /// gone (no typist, its view the pair's). var pair_mode = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; /// A frontend's workers for pictures' draws (Kind.drawer, tui.zig /// `Shell.draw`): each draw asked of any core here runs `draw_us` later, /// as a worker's does, and lands on its core's loop then (`.draw`): /// after the speculation that asked it may have been rolled back. const Draws = struct { var jobs: std.ArrayListUnmanaged(*pardes.host_io.KindJob) = .empty; var net: ?*Net = null; var now: u64 = 0; const draw_us = 3_000; fn go(_: ?*anyopaque, j: *pardes.host_io.KindJob) bool { const n = net orelse return false; jobs.append(gpa, j) catch return false; n.send(.{ .at = now + draw_us, .n = 0, .kind = .draw, .who = 0, .bytes = &.{} }) catch { _ = jobs.pop(); return false; }; return true; } }; /// The authority's host: no frames drawn (a replica draws its own), and a /// pty that echoes what it is written, 2 ms later, as a shell's. const Host = struct { echo: std.ArrayListUnmanaged(struct { pane: u8, bytes: []u8 }) = .empty, /// 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, /// The session's clock (`run`'s: its loop's, tui.zig `clockNow`): the /// soak's time at a frame, an input of its own frontend's or a pty's /// read; a pump woken by a client's mail alone reads the last again. clocked: bool = false, now_ns: u64 = 0, /// Its core, and the view a step's Detach was typed in (tui.zig /// `detach`: a client's link ends; the session's own view's is its /// terminal's, which the soak has none of). core: ?*pardes.Pardes = null, detach_view: ?u8 = null, fn watched(ctx: ?*anyopaque) bool { const h: *Host = @ptrCast(@alignCast(ctx.?)); return h.draws; } fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { const pane = id.index(); const h: *Host = @ptrCast(@alignCast(ctx.?)); h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } fn now(ctx: ?*anyopaque) u64 { const h: *Host = @ptrCast(@alignCast(ctx.?)); return h.now_ns; } fn detach(ctx: ?*anyopaque) void { const h: *Host = @ptrCast(@alignCast(ctx.?)); h.detach_view = h.core.?.live; } /// 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`, `Authority.output`), /// 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). /// At the setup, before any client, at once inside this call. fn job(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void { const pane = id.index(); const h: *Host = @ptrCast(@alignCast(ctx.?)); const j = pardes.host_io.KindJob.take(h.core.?, pane, serial, token) orelse return; if (Draws.go(null, j)) return; j.run(); j.land(h.core.?); } // Every entry a step may ask (a client's tape offers only those its // session's host has): what is not the soak's does nothing. const vtable = replica.everyEntry(.{ .watched = watched, .pty_write = ptyWrite, .job = job }); const clocked_vtable = replica.everyEntry(.{ .watched = watched, .pty_write = ptyWrite, .now = now, .detach = detach, .job = job }); fn host(h: *Host) pardes.Host { return .{ .ctx = h, .vtable = if (h.clocked) &clocked_vtable else &vtable }; } }; const Kind = enum { input, to_authority, to_replica, echo, frame, output, 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, /// The session ended its link (a Detach typed in its view). 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, /// The session's words in a client's stream (a cut's: `Peer.send`). word, /// Room in the far link again: its Peer's writer goes on (`Soak.write`). drain, }; const Msg = struct { at: u64, n: u64, kind: Kind, who: u16, bytes: []u8, /// 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); return std.math.order(a.n, b.n); } }; const Link = struct { last: u64 = 0, /// When what was sent down it before has crossed (`Net.cross`). free: u64 = 0, /// When a message sent at `now` arrives: half the RTT, jitter on top, /// and never before the one sent ahead of it (a stream keeps order). fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 { const at = @max(l.last + 1, now + one_way + random.uintLessThan(u64, jitter + 1)); l.last = at; return at; } }; const Totals = struct { inputs: u64 = 0, speculated: u64 = 0, stopped: u64 = 0, /// Inputs that stopped at a name `replica.may_wait` does not list /// (`judgeStops`), and what stopped them all, a count a name. unlisted: u64 = 0, /// The wakes the clients' loops asked for, and the frames they drew. wakes: u64 = 0, draws: u64 = 0, /// The clients' views' yanks, pastes and links their frontends did. asked: [3]u64 = @splat(0), stops: [32]struct { name: []const u8 = "", n: u64 = 0 } = @splat(.{}), units: u64 = 0, fast: u64 = 0, mispredicted: u64 = 0, foreign: u64 = 0, rebases: u64 = 0, /// A client's digest compared with the session's (a unit's, quiet). checks: u64 = 0, copies: u64 = 0, copy_bytes: u64 = 0, divergences: u64 = 0, unequal: u64 = 0, spec_ns: std.ArrayListUnmanaged(u64) = .empty, copy_ns: std.ArrayListUnmanaged(u64) = .empty, rollback_ns: std.ArrayListUnmanaged(u64) = .empty, // Terminals. unit_bytes: u64 = 0, flood_us: u64 = 0, /// Kitty images a client held at quiescence, the session's pixels /// (`--bytes`, `images`). images_equal: u64 = 0, flood_unit_bytes: 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, /// A pair's client's own boot the session's core at its join (`--pair`), /// or not (its dump loaded instead, the fields that differ said). boots: u64 = 0, boots_unequal: 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, /// Clients let go by a Detach typed in their view. detach_words: u64 = 0, /// Panes of each plain kind the session opened (image, life). kind_panes: [3]u64 = @splat(0), /// The far client (`throttle_*`): its joins from a dump, the time between /// two from the flood's start on, and from the flood's end to the first /// frame of its final screen (us); the most the session's queue for it /// held (bytes); the clients the session cut off. far_joins: u64 = 0, far_gaps: std.ArrayListUnmanaged(u64) = .empty, far_final: std.ArrayListUnmanaged(u64) = .empty, queue_max: u64 = 0, cut: u64 = 0, /// How far behind the session each fell at most (Link.behind, ns), and /// how often it let its link go for it: the far client, and the others. far_behind: u64 = 0, far_lags: u64 = 0, near_behind: u64 = 0, near_lags: u64 = 0, /// What a join costs the replicas already there, ns of this process's /// clock: the session's join step (its reloads and its dump), and each /// client's unit that reloaded its terminals. join_session_ns: std.ArrayListUnmanaged(u64) = .empty, join_client_ns: std.ArrayListUnmanaged(u64) = .empty, fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; t.speculated += s.speculated; t.stopped += s.stopped; for (s.stops) |st| if (st.n > 0) for (&t.stops) |*have| if (have.n == 0 or std.mem.eql(u8, have.name, st.name)) { have.name = st.name; have.n += st.n; break; }; t.units += s.units; t.fast += s.fast; t.mispredicted += s.mispredicted; t.foreign += s.foreign; t.rebases += s.rebases; t.checks += s.checks; t.copies += s.copies; t.copy_bytes += s.copy_bytes; try t.spec_ns.appendSlice(gpa, s.spec_ns.items); try t.copy_ns.appendSlice(gpa, s.copy_ns.items); try t.rollback_ns.appendSlice(gpa, s.rollback_ns.items); } }; /// One client's next input: monkey.zig's mix, as events, and now and then /// a wheel over the shell pane, which scrolls its history into view; a /// file looked at (`looks`, its words) and a pane closed, the Panes and /// Recent pickers (the store's and Recent's rows, the authority's), a jump; /// a picture looked at, a game of life opened and a PDF looked at, at a /// page and at a search's hit (plain kinds a client runs as the session /// does, `looks` past the texts), the keys after going to its pane; a /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its /// wheel; a yank to the system clipboard and a paste from it; now and /// then a client's Detach. fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool, spare: bool) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; if (script.at < script.n) { script.at += 1; return script.evs[script.at - 1]; } switch (random.uintLessThan(u8, 46)) { 0...15 => { buf[0] = typed[random.uintLessThan(usize, typed.len)]; if (buf[0] == 'q' and script.space) buf[0] = 'r'; script.space = buf[0] == ' '; return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } }; }, 16...27 => { buf[0] = normal[random.uintLessThan(usize, normal.len)]; script.space = false; return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } }; }, 28...31 => { script.space = false; return .{ .key = .{ .cp = Key.escape } }; }, 32 => return .{ .key = .{ .cp = Key.enter } }, 33 => return .{ .key = .{ .cp = Key.backspace } }, 34 => return .{ .key = .{ .cp = switch (random.uintLessThan(u8, 4)) { 0 => Key.up, 1 => Key.down, 2 => Key.left, else => Key.right, } } }, 35 => { const n = random.intRangeAtMost(usize, 1, 24); for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)]; return .{ .paste = buf[0..n] }; }, 36 => return .{ .command = switch (random.uintLessThan(u8, 16)) { 0 => "Newcol", 1 => "Zerox", 2 => "Undo", 3 => "Redo", 4 => "Search Panes", 5 => "Search Recent", 6, 7 => looks[random.uintLessThan(usize, looks.len)], // Not the session's last panes: a Del of its last ends it, and // the run with it (`Soak.spare`). 8 => if (spare) "Del" else "Undo", // A tab's width: every pane's layout. 9 => "Tab 2", 10 => "Tab 8", 11 => "Life", // Its link ended by the session (the session's own view's, // its terminal's: none here). Not the far client's: the scene // waits for its screen after the flood. 12 => if (random.uintLessThan(u8, 4) == 0 and !far) "Detach" else "Undo", // The system clipboard, the client's own frontend's (client.zig // `asks`): a yank of the selection to it, a paste from it. 13 => "ClipYank", 14 => "ClipPaste", 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)) } }, 38 => return .{ .mouse = .{ .button = .left, .kind = .press, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } }, 39 => return .{ .mouse = .{ .button = .left, .kind = .release, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } }, // Out of a shell's tty mode and back: its text, a cursor and // selections over it. 40 => return .{ .key = .{ .cp = 'b', .ctrl = true } }, // A search in the pane with the keyboard (a PDF's `/` is its own): // `/`, a pattern, Enter. 41 => { script.* = .{ .n = 2, .evs = .{ .{ .paste = ([_][]const u8{ "the", "view", "pardes" })[random.uintLessThan(usize, 3)] }, .{ .key = .{ .cp = Key.enter } }, undefined } }; return .{ .key = .{ .cp = '/', .text = "/" } }; }, // A sweep of B1 over the PDF: a selection (or a page's pan, or nothing). 42 => { const at = aim.pdf orelse return .{ .key = .{ .cp = Key.escape } }; const x = at[0] + random.uintLessThan(u16, at[2]); const y = at[1] + random.uintLessThan(u16, at[3]); const x1 = at[0] + random.uintLessThan(u16, at[2]); const y1 = @min(at[1] + at[3] - 1, y + random.uintLessThan(u16, 3)); script.* = .{ .n = 2, .evs = .{ .{ .mouse = .{ .button = .left, .kind = .drag, .col = x1, .row = y1 } }, .{ .mouse = .{ .button = .left, .kind = .release, .col = x1, .row = y1 } }, undefined } }; return .{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }; }, // The wheel over the shell, which scrolls its history into view, // or over the PDF, which glides. else => { const over = if (random.boolean()) aim.shell else if (aim.pdf) |p| [2]u16{ p[0] + p[2] / 2, p[1] + p[3] / 2 } else aim.shell; const at = over orelse return .{ .key = .{ .cp = Key.escape } }; return .{ .mouse = .{ .button = if (random.uintLessThan(u8, 3) == 0) .wheel_down else .wheel_up, .kind = .press, .col = at[0], .row = at[1] } }; }, } } /// Where a typist's wheel and sweeps land in the session's view: the /// shell's middle, the PDF's body (x, y, w, h). const Aim = struct { shell: ?[2]u16, pdf: ?[4]u16 }; /// What a typist types in a row, after the first: a search's pattern and /// Enter, a sweep's drag and release. const Script = struct { evs: [3]pardes.Event = undefined, n: u8 = 0, at: u8 = 0, /// Its last key was a space: Space then q is Exit (config.zig's /// leader), which ends the session and the run with it. space: bool = false, }; fn writeFile(path: [:0]const u8, lines: usize) !void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return error.OpenFailed; defer _ = libc.close(fd); var line: [80]u8 = undefined; for (0..lines) |n| { const text = try std.fmt.bufPrint(&line, "const value_{d:0>4} = {d};\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; } } fn writeText(path: [:0]const u8, text: []const u8) !void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return error.OpenFailed; defer _ = libc.close(fd); 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, flood_mb: u64 }; /// The terminal pane's screen as a hash of a dump of its cells. fn screenHash(t: anytype) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); term.terminal.dumpScreen(t, &h.writer) catch {}; h.writer.flush() catch {}; return h.hasher.final(); } /// A client of the session: a process of its own whose loop is THE client /// loop (runtime/client.zig, the terminal's and the window's) over this /// frontend, a terminal's or a window's by turns: it draws no pixels but /// 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, 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, /// 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, /// What it wrote, read off the session's end: bytes not yet a frame. got: std.ArrayListUnmanaged(u8) = .empty, /// Its id and view at the session (its welcome's), and the view it /// joins again for (`back`, after a divergence). id: 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, dialling: bool = false, /// Refusals in a row, until it gives up (a person would). tries: u32 = 0, left: usize, cols: u16, rows: u16, /// The wake its loop's wait asked for (0: none: one at a time, as a /// real wait's timeout is; an earlier one replaces it), and how many. wake_at: u64 = 0, wakes: u64 = 0, /// Its view's yanks, pastes and links its frontend did. asked: [3]u64 = @splat(0), drew: bool = false, /// What it types in a row (a search, a sweep). script: Script = .{}, /// gui.zig `Client.posted`: a size posted once while it waits. posted: ?@FieldType(pardes.Event, "resize") = null, /// What its last frame showed beside the cells (gui.zig `Gui.facts`), /// and its frame timings (Pardes.frames), its own. facts: pardes.Facts = .{}, frames: pardes.FrameStats = .{}, resizes: u32 = 0, /// What its process holds apart from the session's: the kinds it /// caught breaking PA_PLAIN, handed to each core it joins with. distrusted: pardes.Addon.Distrusted = .{}, /// What stopped its inputs as last judged (`judgeStops`). stops: @FieldType(replica.Stats, "stops") = @splat(.{}), /// Its Peer's writer's (`Soak.write`): the batch swapped out of the /// session's queue for it (the Peers' allocator's), how much of it went /// down the link, whether a cut's words end it, a wake asked for room; /// how much of the queue carries the soak's clock (`Soak.stamp`). sending: std.ArrayListUnmanaged(u8) = .empty, at: usize = 0, last: bool = false, draining: bool = false, marked: usize = 0, /// The session's unit its last join's dump came after. join_seq: u32 = 0, /// Where it is (`clients[c]`), the net its wakes go through, and the /// soak's time now. c: usize = 0, net: *Net = undefined, now: u64 = 0, /// A join's first inputs: what it is, then its size (a window's from /// its own pass over its view, `own`). pub fn start(cl: *Client, l: *ClientLoop) void { l.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } }); if (cl.kind == .tty) l.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } }); } /// gui.zig's client pass over the frame it shows (Gui.facts): the /// window's size against the view's, a resize posted when they differ /// (once while it waits), its facts as its view is then. pub fn own(cl: *Client, l: *ClientLoop) bool { if (cl.kind != .window) return true; const v = &cl.facts; 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)) { cl.posted = null; return true; } const ev: pardes.Event = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } }; if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) { l.input(ev); cl.resizes += 1; const r = l.link.r; if (r.core().live == r.view) pardes.draw.facts(r.core(), &cl.facts); } cl.posted = ev.resize; return true; } /// No motion of its own. pub fn again(_: *Client, _: *ClientLoop) bool { return false; } /// A terminal holds a key already one pass in four (its queue had /// one): no copy is taken then. pub fn deadline(cl: *Client, _: *ClientLoop) u32 { return if (cl.kind == .tty and cl.net.random.uintLessThan(u8, 4) == 0) 0 else client_loop.forever; } /// Its wait is the next message for it; a wake it wants (a frame on /// while an echo is predicted, the quiet check) is one, on the soak's /// clock. pub fn wait(cl: *Client, _: *ClientLoop, ms: u32) void { if (ms == client_loop.forever or ms == 0) return; const due = cl.now + @as(u64, ms) * 1000; if (cl.wake_at != 0 and cl.wake_at <= due) return; cl.wake_at = due; cl.wakes += 1; cl.net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(cl.c + 1), .bytes = &.{}, .gen = cl.live }) catch {}; } pub fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { const cl: *Client = @ptrCast(@alignCast(ctx.?)); cl.drew = true; cl.facts = surface.facts.*; return true; } pub fn drawn(cl: *Client) client_loop.Drawn { defer cl.drew = false; return .{ .drew = cl.drew, .moving = false }; } /// What its view asked of its machine (client.zig `asks`), counted; /// its clipboard's answer a paste, as a frontend's comes. pub fn copy(cl: *Client, _: []const u8) void { cl.asked[0] += 1; } pub fn paste(cl: *Client, l: *ClientLoop) void { cl.asked[1] += 1; l.input(.{ .paste = "from the client's clipboard" }); } 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); 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(.{}), /// The far client, whose link is `throttle_*`'s. throttled: ?usize = null, /// When `bytes` sent at `now` down or up client `c`'s link `l` arrive: /// the far one's cross at its rate as the far stream's zstd at `level` /// makes them, after what was sent before them, then its delay. fn cross(net: *Net, l: *Link, c: usize, now: u64, bytes: []const u8, level: c_int) u64 { if (net.throttled != @as(?usize, c)) return l.arrive(net.random, now, net.one_way, net.jitter); l.free = @max(now, l.free) + zstdLen(bytes, level) * std.time.us_per_s / throttle_rate; return l.arrive(net.random, l.free, throttle_one_way, throttle_one_way / 20); } 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.cross(&net.down[c], c, now, bytes, if (kind == .dump) 6 else 3), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); } }; /// P32's far case: a link of 1 Mbit/s and 200 ms each way, what it carries /// counted as the far stream's zstd makes it (core/replica.zig `zstd`), the /// third client's (it joins before the flood); at most `throttle_window` of it ahead of /// what has crossed (its sockets' and the route's buffers), the rest in the /// session's queue for it, as a writer blocked on its socket leaves it. const throttle_rate: u64 = 125_000; const throttle_one_way: u64 = 200_000; const throttle_window: u64 = 64 << 10; extern fn ZSTD_compressBound(n: usize) usize; extern fn ZSTD_compress(dst: [*]u8, cap: usize, src: [*]const u8, n: usize, level: c_int) usize; extern fn ZSTD_isError(code: usize) c_uint; /// `bytes` through zstd at `level`, alone: the far stream's (3, and 6 for a /// join's), which a message shares with those before it. fn zstdLen(bytes: []const u8, level: c_int) u64 { const room = gpa.alloc(u8, ZSTD_compressBound(bytes.len)) catch return bytes.len; defer gpa.free(room); const n = ZSTD_compress(room.ptr, room.len, bytes.ptr, bytes.len, level); return if (ZSTD_isError(n) != 0) bytes.len else n; } /// 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.sfd, &buf, buf.len); if (k <= 0) break; try cl.got.appendSlice(gpa, buf[0..@intCast(k)]); } var at: usize = 0; while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { try net.send(.{ .at = net.cross(&net.up[c], c, now, cl.got.items[at..][0..f.total], 3), .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); } /// What woke client `c`'s loop taken (an input applied and sent, a message /// of the stream, a wake): the rest of its pass and the next up to its wait /// (`Loop.woken`, the loop the terminal and the window run), what stopped /// its inputs judged, and what it wrote read off its socket. fn woke(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run) !void { cl.now = now; cl.loop.link.now = now * 1000; if (cl.r == null) return; cl.loop.woken(); judgeStops(cl, c, totals, run_); try drain(cl, c, net, now); } /// A client's input that stopped at a name `replica.may_wait` does not /// list (what a far client may wait a round trip for, with why): the run /// fails, the input said. fn judgeStops(cl: *Client, c: usize, totals: *Totals, run_: Run) void { const r = cl.r orelse return; defer cl.stops = r.stats.stops; for (r.stats.stops, cl.stops) |now, was| { if (now.n == was.n or replica.mayWait(now.name)) continue; totals.unlisted += now.n - was.n; var buf: [160]u8 = undefined; const blocked = r.blocked orelse 0; const said = for (r.pending.items) |p| { if (p.seq != blocked) continue; const in = replica.parseInput(p.msg) orelse break "?"; break describe(&buf, in.event); } else "?"; std.debug.print("seed {d} rtt {d} ms: client {d}'s input {s} stopped at `{s}`, which may_wait does not list\n", .{ run_.seed, run_.rtt_ms, c + 1, said, now.name }); } } /// An input, in a line. fn describe(buf: []u8, ev: pardes.Event) []const u8 { return switch (ev) { .key => |k| std.fmt.bufPrint(buf, "key {u}{s}{s}", .{ k.cp, if (k.ctrl) " ctrl" else "", if (k.alt) " alt" else "" }), .command => |t| std.fmt.bufPrint(buf, "`{s}`", .{t[0..@min(t.len, 120)]}), .mouse => |m| std.fmt.bufPrint(buf, "mouse {t} {t} at {d},{d}", .{ m.button, m.kind, m.col, m.row }), .paste => |t| std.fmt.bufPrint(buf, "a paste of {d} bytes", .{t.len}), else => std.fmt.bufPrint(buf, "{t}", .{ev}), } catch "?"; } /// 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, typing: *usize) !void { 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(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); try drain(cl, c, net, now); cl.live = 0; if (link.lagged != 0) { if (net.throttled == @as(?usize, c)) totals.far_lags += 1 else totals.near_lags += 1; } if (r.diverged) |why| { if (link.put_off) totals.rejoined += 1 else { totals.divergences += 1; Witness.failed(c, why); 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.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); r.deinit(); cl.r = null; totals.detached += 1; // Let go before it typed all it had: the rest is never typed. if (link.gone) totals.detach_words += 1; if (cl.left > 0) { typing.* -= 1; cl.left = 0; } } /// The witness (a failure's report): the session's stream as its clients /// were sent it (units and blobs, in its order, each kept once as the /// first client's writer forwards it: no copy a client, no step: the /// clients' pace is the run's) and every join's dump with where in that /// stream its client began. At the run's end, only when a client diverged, /// a replica that speculates nothing replays it from the first dump on, /// every unit's digest compared: does the session's own tape bring a fresh /// core to the session's digests? Where it does not, the session's step /// read what its tape does not carry: the unit's records said, and the /// fields named against the next dump (or the session at the end). /// A loop inside one call that does not end (the soak's clock stands /// still: `Soak.watch` never runs): a thread that sees no message taken for /// `stuck_s` of the machine's clock says the last ones, has gdb print every /// thread's stack (the soak lets any process of its own trace it: `main`'s /// PR_SET_PTRACER), and ends the run. const Watchdog = struct { extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; const stuck_s = 240; var taken: std.atomic.Value(u64) = .init(0); var last: [8]struct { kind: Kind = .wake, who: u16 = 0, at: u64 = 0 } = @splat(.{}); fn took(m: Msg) void { const n = taken.fetchAdd(1, .monotonic); last[n % last.len] = .{ .kind = m.kind, .who = m.who, .at = m.at }; } fn said() void { const n = taken.load(.monotonic); std.debug.print(" the last messages taken (of {d}):", .{n}); for (0..@min(n, last.len)) |k| { const e = last[(n - 1 - k) % last.len]; std.debug.print(" {t} of {d} at {d} us;", .{ e.kind, e.who, e.at }); } std.debug.print("\n", .{}); } fn run() void { var was = taken.load(.monotonic); var still: u32 = 0; while (true) { var ts: libc.timespec = .{ .sec = 10, .nsec = 0 }; _ = libc.nanosleep(&ts, null); const now = taken.load(.monotonic); if (now != was) { was = now; still = 0; continue; } still += 10; if (still < stuck_s) continue; std.debug.print("watchdog: no message taken for {d} s of the machine's clock: a loop inside one call\n", .{still}); said(); var pid_buf: [16]u8 = undefined; const pid = std.fmt.bufPrintSentinel(&pid_buf, "{d}", .{libc.getpid()}, 0) catch unreachable; const argv = [_:null]?[*:0]const u8{ "gdb", "-batch", "-p", pid, "-ex", "thread apply all bt 30", null }; const child = libc.fork(); if (child == 0) { _ = libc.dup2(2, 1); _ = execvp("gdb", &argv); libc._exit(127); } if (child > 0) { var status: c_int = 0; _ = libc.waitpid(child, &status, 0); } libc._exit(3); } } }; /// At a client's mismatch only: its digest of every field, as the mismatch /// left its core, and the unit it parted on. The witness names the fields /// when its own replay of the kept stream comes to that unit (`judge`): /// nothing more on the session's step or the wire, so the run's timing is /// the untraced one. const Named = struct { const Parted = struct { c: usize, origin: u16, seq: u32, parts: []u64, terms: [pardes.MAX_PANES]Term }; /// A terminal pane's: its screen's digest, where the live view stands /// in it (the pane's, `scrolled_to`), and its grid. const Term = struct { content: u64 = 0, place: ?usize = null, grid: pardes.Term.Grid = .{} }; fn terms(p: *const pardes.Pardes) [pardes.MAX_PANES]Term { var out: [pardes.MAX_PANES]Term = @splat(.{}); for (p.panes, &out) |slot, *t| { const pane = slot orelse continue; const state = pane.terminal orelse continue; var a = pardes.walk.Hasher.init(0); state.digest(&a); t.* = .{ .content = a.final(), .place = pane.scrolled_to, .grid = pardes.Term.grid(state) }; } return out; } var parted: std.ArrayListUnmanaged(Parted) = .empty; fn reset() void { for (parted.items) |x| gpa.free(x.parts); parted.clearRetainingCapacity(); } /// Client `c` parted on `unit`: kept for the witness, said once. fn say(r: Run, c: usize, rp: *replica.Replica, unit: []const u8) void { const u = replica.parseUnit(unit) orelse return; const mine = gpa.create(pardes.tape.Parts) catch return; defer gpa.destroy(mine); const got = pardes.tape.digestParts(rp.core(), mine); parted.append(gpa, .{ .c = c, .origin = u.origin, .seq = u.seq, .parts = gpa.dupe(u64, got) catch return, .terms = terms(rp.core()) }) catch return; std.debug.print("seed {d} rtt {d} ms: client {d} parted on unit {d}/{d} ({d} bytes; {d} applied on top, {d} pending): its fields kept for the witness\n", .{ r.seed, r.rtt_ms, c + 1, u.origin, u.seq, u.tape.len, rp.applied, rp.pending.items.len }); } /// The witness at the end of unit `u`: each client that parted there, /// its fields against the witness's (the session's stream replayed). fn atUnit(tag: anytype, u: replica.Unit, rp: *replica.Replica, w: *std.Io.Writer) void { for (parted.items) |x| if (x.origin == u.origin and x.seq == u.seq) { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const theirs = arena.allocator().create(pardes.tape.Parts) catch return; const want = pardes.tape.digestParts(rp.core(), theirs); w.print("seed {d} rtt {d} ms: client {d} names: at unit {d}/{d}, against the witness's replay: {s}\n", tag ++ .{ x.c + 1, u.origin, u.seq, pardes.tape.partsDiffer(x.parts, want, arena.allocator()) }) catch {}; for (x.terms, terms(rp.core()), 0..) |a, b, id| if (a.place != b.place or a.content != b.content) { w.print(" pane {d}'s terminal: content {s}, view {s}; the client's {any} at {?d}; the witness's {any} at {?d}\n", .{ id, if (a.content == b.content) "equal" else "DIFFERS", if (a.place == b.place) "equal" else "DIFFERS", a.grid, a.place, b.grid, b.place }) catch {}; }; }; } }; const Witness = struct { const Sent = struct { blob: bool, bytes: []u8 }; const Dump = struct { c: usize, id: u16, view: u8, cols: u16, rows: u16, join_seq: u32, bytes: []u8, start: ?usize = null }; const Failure = struct { c: usize, why: []u8, at: usize }; var sent: std.ArrayListUnmanaged(Sent) = .empty; var dumps: std.ArrayListUnmanaged(Dump) = .empty; var failures: std.ArrayListUnmanaged(Failure) = .empty; /// Each client's place in `sent` (null: none yet since its join), and /// its join's dump. var at: [8]?usize = @splat(null); var dump_of: [8]usize = @splat(0); var broken: ?[]const u8 = null; fn joined(c: usize, cl: *const Client, bytes: []u8, join_seq: u32) void { dump_of[c] = dumps.items.len; at[c] = null; dumps.append(gpa, .{ .c = c, .id = cl.id, .view = cl.view, .cols = cl.cols, .rows = cl.rows, .join_seq = join_seq, .bytes = bytes }) catch @panic("witness: out of memory"); } /// A unit's origin and number. fn head(bytes: []const u8) u48 { return std.mem.readInt(u48, bytes[0..6], .little); } fn same(s: Sent, blob: bool, bytes: []const u8) bool { if (s.blob != blob or s.bytes.len != bytes.len) return false; // A unit's clock words are each client's (`Soak.stamp`). if (!blob) return head(s.bytes) == head(bytes) and std.mem.eql(u8, s.bytes[unit_head_len..], bytes[unit_head_len..]); return std.mem.eql(u8, s.bytes, bytes); } const unit_head_len = 22; /// Client `c`'s writer forwarded `bytes` (a unit or a blob piece). fn forwarded(c: usize, blob: bool, bytes: []const u8) void { // Its join is not kept (the run's end judged it). if (dump_of[c] >= dumps.items.len) return; const i = at[c] orelse place: { // Its first since its join: kept already (another's writer // forwarded it first), else the next. var i = sent.items.len; while (i > 0 and sent.items.len - i < 1 << 14) { i -= 1; if (same(sent.items[i], blob, bytes)) break :place i; } break :place sent.items.len; }; if (at[c] == null) dumps.items[dump_of[c]].start = i; if (i == sent.items.len) { sent.append(gpa, .{ .blob = blob, .bytes = gpa.dupe(u8, bytes) catch @panic("witness: out of memory") }) catch @panic("witness: out of memory"); } else if (broken == null and !same(sent.items[i], blob, bytes)) broken = "a client was sent another stream than the one kept"; at[c] = i + 1; } fn failed(c: usize, why: []const u8) void { failures.append(gpa, .{ .c = c, .why = gpa.dupe(u8, why) catch return, .at = at[c] orelse 0 }) catch {}; } fn reset() void { for (sent.items) |m| gpa.free(m.bytes); sent.clearRetainingCapacity(); for (dumps.items) |d| gpa.free(d.bytes); dumps.clearRetainingCapacity(); for (failures.items) |f| gpa.free(f.why); failures.clearRetainingCapacity(); at = @splat(null); broken = null; } /// A replica of dump `d`, as the soak's clients make theirs. /// The kinds the witness's replica distrusts: it keeps a pointer to /// them for its life (a local here was a stack slot gone by its first /// kind's call: an index of 0xAA..., the screen-state soak's panic). var distrusted: pardes.Addon.Distrusted = .{}; fn load(d: *const Dump) !*replica.Replica { distrusted = .{}; // No client's id: every unit is another's. const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); rp.guess = false; rp.core().echo = null; rp.t.local_files = true; return rp; } /// Each field of the core, its stream, its views and its panes whose /// digest differs between `a` and `b`, named (tape.zig's digestParts', /// by name), and each terminal's screen. fn fieldsDiffer(a: *const pardes.Pardes, b: *const pardes.Pardes, w: *std.Io.Writer) void { const walk = pardes.walk; const Each = struct { fn of(comptime T: type, x: *const T, y: *const T, prefix: []const u8, out: *std.Io.Writer) void { const names = comptime walk.fieldNames(T); var dx: [names.len]u64 = undefined; var dy: [names.len]u64 = undefined; _ = walk.fieldDigests(T, x, &dx); _ = walk.fieldDigests(T, y, &dy); for (names, dx, dy) |name, u, v| if (u != v) out.print("{s}{s} ", .{ prefix, name }) catch {}; } }; Each.of(pardes.Pardes, a, b, "", w); Each.of(pardes.Stream, &a.stream, &b.stream, "stream.", w); for (&a.views, &b.views, 0..) |*x, *y, k| if (x.* != null and y.* != null) { var buf: [24]u8 = undefined; Each.of(pardes.Pardes.View, &x.*.?, &y.*.?, std.fmt.bufPrint(&buf, "views[{d}].", .{k}) catch "", w); } else if ((x.* == null) != (y.* == null)) w.print("views[{d}] (one side only) ", .{k}) catch {}; for (a.panes, b.panes, 0..) |x, y, id| { if (x == null or y == null) { if ((x == null) != (y == null)) w.print("pane {d} (one side only) ", .{id}) catch {}; continue; } var buf: [24]u8 = undefined; Each.of(pardes.Pane, x.?, y.?, std.fmt.bufPrint(&buf, "pane {d}.", .{id}) catch "", w); if (x.?.terminal) |sx| if (y.?.terminal) |sy| { const ex = &pardes.Term.emulatorOf(sx).vt; const ey = &pardes.Term.emulatorOf(sy).vt; w.print("[pane {d}'s screen {s}] ", .{ id, if (screenHash(ex) == screenHash(ey)) "equal" else "DIFFERS" }) catch {}; }; } w.writeByte('\n') catch {}; } /// At the run's end (the session's core still whole), when a client /// diverged: the stream replayed from each dump on, as said above. fn judge(s: *Soak) void { if (failures.items.len == 0 and !witness_always) return; const on = pardes.tape.on; const trees = pardes.syntax.held_trees; pardes.tape.on = null; pardes.syntax.held_trees = null; defer { pardes.tape.on = on; pardes.syntax.held_trees = trees; } var out_buf: [1 << 14]u8 = undefined; // Streaming: a positional writer starts at offset 0, and over a log // file each judgement wrote over the run's first lines. var stderr = std.Io.File.stderr().writerStreaming(s.l.peers.io, &out_buf); const w = &stderr.interface; defer w.flush() catch {}; const tag = .{ s.r.seed, s.r.rtt_ms }; w.print("seed {d} rtt {d} ms: witness: {d} messages kept, {d} dumps{s}{s}\n", tag ++ .{ sent.items.len, dumps.items.len, if (broken != null) ": " else "", broken orelse "" }) catch {}; for (failures.items) |f| { const u: ?replica.Unit = if (f.at > 0 and !sent.items[f.at - 1].blob) replica.parseUnit(sent.items[f.at - 1].bytes) else null; w.print("seed {d} rtt {d} ms: witness: client {d} failed at message {d} (unit {d}/{d}): {s}\n", tag ++ .{ f.c + 1, f.at -| 1, if (u) |x| x.origin else 0, if (u) |x| x.seq else 0, f.why }) catch {}; } var d: usize = 0; while (d < dumps.items.len) { const from = &dumps.items[d]; const start = from.start orelse { d += 1; continue; }; const rp = load(from) catch |err| { w.print("seed {d} rtt {d} ms: witness: dump {d} does not load: {t}\n", tag ++ .{ d, err }) catch {}; d += 1; continue; }; defer rp.deinit(); var last0: u32 = from.join_seq; var parted: ?usize = null; var i = start; const end = end: while (i < sent.items.len) : (i += 1) { const m = sent.items[i]; if (m.blob) { rp.blobPiece(m.bytes); continue; } const u = replica.parseUnit(m.bytes) orelse continue; // A stretch no client was sent (none was joined): the stream // has a gap here. if (u.origin == 0 and u.seq != last0 + 1) break :end i; if (u.origin == 0) last0 = u.seq; rp.since_check = if (parted == null) 1 << 20 else 0; rp.confirm(m.bytes); if (parted == null) Named.atUnit(tag, u, rp, w); if (rp.diverged) |why| { if (parted == null) { parted = i; w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, after unit 0/{d}, message {d}) PARTS at message {d}, unit {d}/{d} ({d} bytes): {s}\n its records:\n", tag ++ .{ d, from.c + 1, from.join_seq, start, i, u.origin, u.seq, u.tape.len, why }) catch {}; pardes.tape.describe(u.tape, w); } // On over it, to the next dump, unchecked. gpa.free(rp.diverged.?); rp.diverged = null; rp.t.diverged = null; } // The next dump begins here: what differs then, by field. if (parted != null) for (dumps.items[d + 1 ..], d + 1..) |*next, k| if (next.start == i + 1) { const there = load(next) catch break; defer there.deinit(); w.print(" against dump {d} (after unit 0/{d}): ", .{ k, next.join_seq }) catch {}; fieldsDiffer(rp.core(), there.core(), w); break :end i + 1; }; } else i; if (parted == null) { w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, message {d}): messages to {d} replayed to the session's every digest{s}", tag ++ .{ d, from.c + 1, start, end, if (end == sent.items.len) "; at the end against the session: " else " (a gap: no client was joined)\n" }) catch {}; if (end == sent.items.len) fieldsDiffer(rp.core(), s.l.core, w); } else if (end == sent.items.len) { w.print(" at the end against the session: ", .{}) catch {}; fieldsDiffer(rp.core(), s.l.core, w); } // Next: the first dump that begins at or after where this one ended. const next = for (dumps.items[d + 1 ..], d + 1..) |x, k| { if (x.start) |st| if (st >= end) break k; } else dumps.items.len; d = next; } } }; /// 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, /// The flood: `yes`, then a `cat` (its first `yes_len` bytes `yes`). flood: []const u8, yes_len: usize, l: *SessionLoop = undefined, /// What failed inside the loop (its wait returns nothing): the run's. err: ?anyerror = null, /// `finish` ran: the session's loop ended at the run's end, not before. finished: bool = false, /// The session's `quit` after its last step (`sent`): an Exit's end. quit: bool = false, /// The last inputs the typists drew (who, as `describe` says them), /// said with an early end. drawn: [8]struct { who: u16 = 0, text: [48]u8 = undefined, len: u8 = 0 } = @splat(.{}), drawn_n: usize = 0, // ---- 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, /// `--pair`: the session's end of client 0's link, its first client's /// (`options`). pair_fd: c_int = -1, // ---- 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 } = .{}, 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 session's pty told the answers to the program's kitty query and /// its four images (`questions`, `images`, `kitty_oks`): each once, whatever the /// clients. kitty_answers: [kitty_oks.len]u32 = @splat(0), /// The temporary file and the shared memory object an image was shown /// by (`images`): gone once the session read them. media: *const Media = undefined, /// The session's unit with the flood's last bytes; the far client's /// last join, and whether it has shown the final screen; a join's step /// at worst. flood_seq: u32 = 0, far_joined: u64 = 0, far_final: bool = false, join_worst: u64 = 0, /// The watchdog's (`watch`): what the steps and checks made came to, and /// the soak's time it last moved. moved: u64 = 0, moved_at: u64 = 0, fn of(ctx: ?*anyopaque) *Soak { return @ptrCast(@alignCast(ctx.?)); } /// Its own view drawn after every pump, as a terminal's session draws /// its own (Core.render: drawn whenever a frame is owed and someone /// sees it, and a terminal is always seen). fn watchedHost(_: ?*anyopaque) bool { return !pair_mode; } fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { const pane = id.index(); const s = of(ctx); // Only the session's emulator answers its program: a client's // answers are its tape's, never written (`questions`). for (kitty_oks, &s.kitty_answers) |ok, *n| if (std.mem.indexOf(u8, bytes, ok) != null) { n.* += 1; }; 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, id: pardes.Pane.Id, serial: u32, token: u32) void { const pane = id.index(); 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 ---- /// A pair's: its first client on the link `run` made. pub fn options(s: *Soak, o: *pardes.Options) void { if (s.pair_fd >= 0) o.pair = s.pair_fd; } pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; 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); } cl.sending.deinit(s.l.peers.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); } /// 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| { // A pair's client joined at the loop's start. if (pair_mode and c == 0) continue; cl.dialling = true; const at: u64 = switch (c) { 0, 1 => s.random.uintLessThan(u64, 100_000), 2 => 1_200_000, // One joins in the middle of the flood, its emulators loaded // whole and every other side's reloaded. 3 => flood_at + 100_000, else => 2_000_000 + c * 100_000, }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } if (!pair_mode) 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. fn drew(s: *Soak, who: u16, ev: pardes.Event) void { const d = &s.drawn[s.drawn_n % s.drawn.len]; s.drawn_n += 1; d.who = who; d.len = @intCast(describe(&d.text, ev).len); } /// Panes enough that the Dels in flight (a typist's each) leave one. fn spare(s: *const Soak) bool { var n: usize = 0; for (s.l.core.panes) |slot| n += @intFromBool(slot != null); return n > 3; } pub fn sent(s: *Soak) void { defer s.quit = s.l.core.quit; 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.join_seq = ps.seq; cl.sending.clearRetainingCapacity(); cl.at = 0; cl.last = false; cl.marked = 0; // What the join cost the session's step (Peers.join's measure). s.join_worst = @max(s.join_worst, ps.join_ns); try s.totals.join_session_ns.append(gpa, ps.join_ns); ps.join_ns = 0; cl.gen += 1; cl.id = welcome.client; cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); 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.index() == k and !cl.shut) { cl.shut = true; }; s.detach_view = null; // The unit with the flood's last bytes: what the far client's final // screen shows. if (s.flood_end != 0 and s.flood_seq == 0) s.flood_seq = ps.seq; for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { if (cl.shut) { // What was queued for it is let go with its link. peer.out.clearRetainingCapacity(); try s.shut(cl, c); continue; } s.stamp(cl, peer); if (net.throttled == @as(?usize, c)) s.totals.queue_max = @max(s.totals.queue_max, peer.out.items.len); try s.write(cl, c); }; // 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(); } /// The units the session queued for client `cl` since, their heads /// carrying the soak's clock, the session's here (its host's `now`): /// what the client's lag is measured by. Its replica guesses no clock /// from them (`joined`: in process, both read one). fn stamp(s: *Soak, cl: *Client, peer: *replica.Peer) void { const out = peer.out.items; // A cut (Peer.send, past its limit) empties the queue for its words. var at = @min(cl.marked, out.len); while (pardes.wire.framed(out[at..]) catch null) |f| : (at += f.total) { if (f.tag != @backingInt(pardes.wire.ServerTag.unit)) continue; const head = at + f.total - f.payload.len; std.mem.writeInt(i64, out[head + 14 ..][0..8], @intCast(s.now * std.time.ns_per_us), .little); } cl.marked = at; } /// Client `c`'s Peer's writer (Peer.writeLoop's): the session's queue /// for it swapped out a batch at a time and handed down its link, a /// frame a message. The far link takes no more than `throttle_window` /// ahead of what has crossed: the rest waits in the queue, as it does /// for a writer blocked on its socket, until room comes (`.drain`). A /// cut's words end a batch, and its link after them. fn write(s: *Soak, cl: *Client, c: usize) !void { const peer = cl.peer orelse return; const net = s.net; const window_us = throttle_window * std.time.us_per_s / throttle_rate; while (true) { if (cl.at == cl.sending.items.len) { cl.sending.clearRetainingCapacity(); cl.at = 0; if (cl.last) return s.shut(cl, c); const io = s.l.peers.io; peer.lock.lockUncancelable(io); std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); cl.last = peer.cut; peer.lock.unlock(io); cl.marked = 0; if (cl.sending.items.len == 0) return; } if (net.throttled == @as(?usize, c) and net.down[c].free > s.now + window_us) { if (!cl.draining) try net.send(.{ .at = net.down[c].free - window_us, .n = 0, .kind = .drain, .who = @intCast(c + 1), .bytes = &.{} }); cl.draining = true; return; } const f = (try pardes.wire.framed(cl.sending.items[cl.at..])) orelse return error.TornFrame; cl.at += f.total; try s.forward(cl, c, f); } } /// One frame of client `c`'s stream, down its link. fn forward(s: *Soak, cl: *Client, c: usize, f: pardes.wire.Framed) !void { const net = s.net; const now = s.now; const flooding = now >= flood_at and s.flood_end == 0; switch (std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame) { .unit => { Witness.forwarded(c, false, f.payload); 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)); }, .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 => { Witness.forwarded(c, true, f.payload); try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)); }, .refused => try net.toClient(c, now, .word, cl.gen, try gpa.dupe(u8, (try pardes.wire.decodeServer(f.tag, f.payload)).refused)), else => return error.UnexpectedFrame, } } /// Client `c`'s link ended at the session's side (a Detach typed in its /// view, or the words of a cut sent): it hears its end and nothing after, /// and its reader's end is said (the next boundary lets it go). fn shut(s: *Soak, cl: *Client, c: usize) !void { cl.shut = true; cl.last = false; if (cl.read_done) return; cl.read_done = true; s.l.peers.post(.{ .gone = cl.peer.? }); try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); } pub fn upgradeAsked(_: *Soak) void {} 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: its step // comes after that output's. if (s.held) |m| { s.held = null; try s.own(m); return false; } var took_output = false; // What its boundary took is old news. _ = s.l.peers.urgent.swap(false, .acq_rel); while (true) { try s.watch(); 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); Watchdog.took(m); 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, .checked, .blob, .wake, .quit, .gone, .word => 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 = .at(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.flood, 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; // `yes` a read every 450 us, the `cat` a read every 4 ms // (1 MB/s: the far link falls behind, many seconds long). if (s.program.at < s.program.bytes.len) try net.send(.{ .at = m.at + if (m.who != 1) @as(u64, 3_000) else if (s.program.at < s.yes_len) @as(u64, 450) else 4_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) else if (m.who == 1) s.flood_end = m.at; core.update(.{ .output = .{ .pane = .at(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) return false; }, // Room in the far link: its Peer's writer goes on. .drain => { cl.draining = false; try s.write(cl, c); if (s.l.peers.urgent.swap(false, .acq_rel)) 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 (!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 = .at(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; // The far client refused before its screen after the // flood (a join again for its lag finds its view taken: // a join with no room lets an away one go): said, so // that "it left" says why. if (net.throttled == @as(?usize, c) and !s.far_final and cl.tries == 1) std.debug.print("seed {d} rtt {d} ms: the far client refused (every view taken), {d} keys left, try {d}\n", .{ s.r.seed, s.r.rtt_ms, cl.left, cl.tries }); if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.cross(&net.up[c], c, m.at + 500_000, &.{}, 3), .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, .checked, .blob, .wake, .quit, .gone, .word => { 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, net.throttled == @as(?usize, c), s.spare()); s.drew(@intCast(c + 1), ev); 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 => { if (net.throttled == @as(?usize, c) and !s.far_final and s.flood_seq != 0) if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0 and u.seq >= s.flood_seq) { s.far_final = true; try s.totals.far_final.append(gpa, m.at - s.flood_end); }; // A join's reloads on a replica there before it: // what its unit cost, on this process's clock. const reloads = pardes.Term.reloads.n; const t0 = monoNs(); const whole = rp.diverged == null; cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }); if (whole and rp.diverged != null and !cl.loop.link.put_off) Named.say(s.r, c, rp, m.bytes); if (pardes.Term.reloads.n != reloads) try s.totals.join_client_ns.append(gpa, monoNs() - t0); const behind = if (net.throttled == @as(?usize, c)) &s.totals.far_behind else &s.totals.near_behind; behind.* = @max(behind.*, cl.loop.link.behind); }, .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), .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, .client_frame, .check_up, .bye_up => unreachable, } } } /// No step of the session's and no unit or check of a client's for /// `stuck_us` of the soak's own clock: a loop that does not end. Every /// side's state said, and the run failed. fn watch(s: *Soak) !void { var moved: u64 = s.l.peers.seq; for (s.clients) |*cl| if (cl.r) |rp| { moved +%= rp.stats.units +% rp.stats.checks +% rp.pending.items.len; }; if (moved != s.moved) { s.moved = moved; s.moved_at = s.now; return; } // The soak's clock is a message's time: one due before it steps it back. if (s.now -| s.moved_at < stuck_us) return; std.debug.print("seed {d} rtt {d} ms: watchdog: nothing stepped or checked for {d} s of the soak's clock (since {d} us)\n", .{ s.r.seed, s.r.rtt_ms, stuck_us / std.time.us_per_s, s.moved_at }); s.report(); return error.Hung; } const stuck_us = 60 * std.time.us_per_s; /// Every side's state, for a run that hangs: the session's and each /// client's, what each waits on and holds, and the last messages taken. fn report(s: *Soak) void { const ps = &s.l.peers; const core = s.l.core; std.debug.print(" session: unit 0/{d}, needs_frame {any}, next wake {?d} (now {d} ns), quit {any}; the net {d} in flight, the next {s}; typing {d}, own left {d}, frames left {d}, flood at {d} of {d} (ended {d}), held {any}\n", .{ ps.seq, core.needs_frame, core.nextWake(), s.now_ns, core.quit, s.net.q.count(), if (s.net.q.peek()) |n| @tagName(n.kind) else "none", s.typing, s.own_left, s.frames_left, s.program.at, s.program.bytes.len, s.flood_end, s.held != null }); for (s.clients, 1..) |*cl, id| { std.debug.print(" client {d} ({t}): live {d} gen {d} dialling {any} left {d} wake_at {d}", .{ id, cl.kind, cl.live, cl.gen, cl.dialling, cl.left, cl.wake_at }); if (cl.peer) |p| std.debug.print(", its queue at the session {d} B, sending {d}/{d}, shut {any} draining {any}", .{ p.out.items.len, cl.at, cl.sending.items.len, cl.shut, cl.draining }); if (cl.r) |rp| std.debug.print(", replica: units {d} checks {d} pending {d} applied {d} blocked {?d} since {d} copy {any} diverged {any}, link quit {any} asked {any} behind {d} ms", .{ rp.stats.units, rp.stats.checks, rp.pending.items.len, rp.applied, rp.blocked, rp.since.items.len, rp.copy.held, rp.diverged != null, cl.loop.link.quit, cl.loop.link.asked, cl.loop.link.behind / std.time.ns_per_ms }); std.debug.print("\n", .{}); } Watchdog.said(); } /// 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, false, s.spare()); s.drew(0, ev); core.toView(.at(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 = if (pair_mode and c == 0 and !s.has_link[0]) try s.booted(cl, m.bytes) else try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; // In process: its clock reads are the session's machine's, and the // units' heads carry the soak's clock (`stamp`). rp.guess = false; if (s.net.throttled == @as(?usize, c)) { s.totals.far_joins += 1; if (m.at >= flood_at and s.far_joined != 0) try s.totals.far_gaps.append(gpa, m.at - s.far_joined); s.far_joined = m.at; if (!s.far_final and s.flood_seq != 0 and cl.join_seq >= s.flood_seq) { s.far_final = true; try s.totals.far_final.append(gpa, m.at - s.flood_end); } } // Its terminals its own emulators, fed what the units carry. rp.core().echo = null; 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 = &.{} }); } /// A pair's client's replica: its core its own boot from the options /// the session was started with (`run`'s), as the pair's client makes /// it (replica.ownBoot), kept when the welcome's digest is its own /// (confirmBoot); else the session's dump, loaded, and the fields of /// the two cores that differ said. fn booted(s: *Soak, cl: *Client, dump: []const u8) !*replica.Replica { s.totals.boots += 1; const boot = try replica.Replica.initBoot(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .distrusted = &cl.distrusted }); if (boot.digest() == cl.digest) { boot.id = cl.id; boot.view = cl.view; return boot; } defer boot.deinit(); s.totals.boots_unequal += 1; const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, dump, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); var buf: [4096]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); Witness.fieldsDiffer(boot.core(), rp.core(), &w); std.debug.print("seed {d} rtt {d} ms: the pair's own boot is not the session's core at its join; differ: {s}", .{ s.r.seed, s.r.rtt_ms, w.buffered() }); return rp; } /// 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 { s.finished = true; const totals = s.totals; const core = s.l.core; totals.flood_us += s.flood_end -| flood_at; const want = pardes.tape.digestOf(core); totals.cut += s.l.peers.cut; std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); }; for (&s.media.temp, &s.media.object) |*temp, *object| { for ([_][:0]const u8{ temp, object }, [_]bool{ libc.access(temp, libc.F_OK) == 0, shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDONLY }), 0) >= 0 }) |name, left| if (left) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: {s}, an image's medium, is still there\n", .{ s.r.seed, s.r.rtt_ms, name }); }; } 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; Witness.failed(id - 1, why); 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, // and its kitty images the session's, pixel for pixel. 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 }); } const theirs = imagesHash(state); if (!std.mem.eql(u64, &theirs, &imagesHash(mine))) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: client {d}'s kitty images in terminal {d} are not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); } else for (theirs) |h| { if (h != 0) totals.images_equal += 1; } } // ...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 }); } } } Witness.judge(s); } }; 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 }); Witness.reset(); defer Witness.reset(); Named.reset(); defer Named.reset(); var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var paths: [3][256:0]u8 = undefined; var look_lines: [8][300]u8 = undefined; var looks_buf: [8][]const u8 = undefined; for (&paths, look_lines[0..3], looks_buf[0..3], 0..) |*p, *l, *look, i| { const path = try std.fmt.bufPrintSentinel(p, "{s}/f{d}.zig", .{ dir, i }, 0); try writeFile(path, 60 + 40 * i); look.* = try std.fmt.bufPrint(l, "Look {s}", .{path}); } // A picture (the image addon's), when // the soak has their libraries (`--addon`). var picture: [256:0]u8 = undefined; var nlooks: usize = 3; const kinds = pardes.Addon.scan(); for (kinds) |l| if (std.mem.eql(u8, l.name, "image")) { const path = try std.fmt.bufPrintSentinel(&picture, "{s}/picture.ppm", .{dir}, 0); var ppm: std.ArrayListUnmanaged(u8) = .empty; defer ppm.deinit(gpa); try ppm.print(gpa, "P6\n64 48\n255\n", .{}); for (0..48) |y| for (0..64) |x| try ppm.appendSlice(gpa, &.{ @intCast(x * 4), @intCast(y * 5), @intCast((x + y) * 2) }); try writeText(path, ppm.items); looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{path}); nlooks += 1; }; // The PDF (`--pdf`, the pdf addon's), and two places in it: a page, a // search's hit on a page (a miss until a search found one there). const with_pdf = nlooks > 3 and pdf_path != null and for (kinds) |l| { if (std.mem.eql(u8, l.name, "pdf")) break true; } else false; if (with_pdf) for ([_][]const u8{ "", ":3", ":1:1" }) |at| { looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}{s}", .{ pdf_path.?, at }); nlooks += 1; }; var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20, .throttled = if (r.clients >= 3) 2 else null }; defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; defer { pardes.Kind.drawer = null; Draws.net = null; } 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)) }; // A pair's client is the terminal the session was started at the // size of (main.zig `pair`). if (pair_mode and c == 0) { cl.cols = 100; cl.rows = 30; } 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); } // 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` and of a `cat`, read 4 KB at a time as a pty gives it. const tui = try tuiStream(); defer gpa.free(tui); const session_only = try shellStream(); defer gpa.free(session_only); const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, questions }); defer gpa.free(shell_session); var media: Media = undefined; const shown = try images(dir, r.seed, &media); defer { gpa.free(shown); for (&media.temp, &media.object) |*temp, *object| { _ = libc.unlink(temp); _ = shm.shm_unlink(object); } } const yes_only = try yesStream(@intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); const flood = try catAfter(yes, yes.len); defer gpa.free(flood); 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, .flood = flood, .yes_len = yes.len, .own_left = r.steps, .typing = r.clients + @intFromBool(!pair_mode), .media = &media, }; // A pair's client's link, made before the session (main.zig `pair`): // its end handed to the session's options, the soak reading the other // as for a dial (`.dial`). if (pair_mode) { const cl = &clients[0]; 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; soak.pair_fd = cl.handed; } // 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; // The loop ends without the run's end too (runtime/session.zig): every // client gone at a boundary, the last by a close; or the session ended // (Exit, the last pane's Del). Said, and the run failed. if (!soak.finished) { std.debug.print("seed {d} rtt {d} ms: the session's loop ended before the run did: {s}; the clients:", .{ r.seed, r.rtt_ms, if (soak.quit) "the session ended (Exit, the last pane's Del)" else "every client gone at a boundary, the last by a close" }); for (soak.clients, 1..) |cl, k| std.debug.print(" {d} {s}{s}{s};", .{ k, if (cl.r == null) "none" else "joined", if (cl.dialling) " dialling" else "", if (cl.shut) " shut" else "" }); std.debug.print(" typing {d}, at {d} us; the last drawn (0 the session's own):", .{ soak.typing, soak.now }); for (0..@min(soak.drawn_n, soak.drawn.len)) |k| { const d = soak.drawn[(soak.drawn_n - 1 - k) % soak.drawn.len]; std.debug.print(" {d}: {s};", .{ d.who, d.text[0..d.len] }); } std.debug.print("\n", .{}); return error.EndedEarly; } } /// What `questions`'s kitty query and `images`'s four are answered with. const kitty_oks = [_][]const u8{ "\x1b_Gi=31;OK", "\x1b_Gi=5;OK", "\x1b_Gi=6;OK", "\x1b_Gi=7;OK", "\x1b_Gi=8;OK" }; /// The temporary files and the shared memory objects `images` shows its /// images by, which the session's emulator removes when it reads them. const Media = struct { temp: [2][300:0]u8, object: [2][64:0]u8 }; const shm = struct { extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: libc.mode_t) c_int; extern "c" fn shm_unlink(name: [*:0]const u8) c_int; extern "c" fn ftruncate(fd: c_int, len: i64) c_int; }; /// The pixels of each of `images`'s kept images a terminal holds, hashed /// (0: not held). fn imagesHash(state: *pardes.Term.State) [4]u64 { var out: [4]u64 = @splat(0); const screen = pardes.Term.emulatorOf(state).vt.screens.active; for (&out, 15..) |*h, id| if (screen.kitty_images.imageById(@intCast(id))) |img| { h.* = std.hash.Wyhash.hash(1, img.data.bytes() orelse continue); }; return out; } /// What the shell's program asks its terminal at the end of its session /// (`--bytes`): device attributes, the cursor's place, the cell's size in /// pixels, a kitty query. const questions = "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n$ "; /// What the flood's program shows at its end (`--bytes`; after it, so the /// clients still hold them at quiescence): kitty images shown (a=T) by /// direct data, by a file of the session's machine, by a temporary file /// (which its reader deletes) and by shared memory (which its reader /// unlinks), twice: answered (ids 5 to 8, `kitty_oks`), and kept (ids 15 /// to 18, q=1: the soak's tty echoes an answer back as output, and an /// echoed `ESC _ G i=5;OK` is a transmission of image 5 that fails and /// takes it away), the kept one by shared memory 1.4 MB, so its read /// crosses to a client by hash. Each medium is the session's to read and /// every client is handed its bytes (Term.media): each image in every /// client, pixel for pixel; the program answered once; each temporary file /// and object gone once. fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { var path_buf: [300]u8 = undefined; const path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/pixels.rgb", .{dir}, 0); try writeText(path, &@as([12]u8, @splat(0x7f))); var out: std.ArrayListUnmanaged(u8) = .empty; errdefer out.deinit(gpa); var b64: [3][400]u8 = undefined; const enc = std.base64.standard.Encoder; for (0..2, [_]u32{ 2, 600 }, [_][]const u8{ "", ",q=1" }) |round, side, quiet| { const temp = try std.fmt.bufPrintSentinel(&media.temp[round], "{s}/tty-graphics-protocol-{d}-{d}.rgb", .{ dir, seed, round }, 0); try writeText(temp, &@as([12]u8, @splat(0x3f))); const object = try std.fmt.bufPrintSentinel(&media.object[round], "/pardes-soak-{d}-{d}-{d}", .{ libc.getpid(), seed, round }, 0); const fd = shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); if (fd < 0) return error.ShmOpenFailed; defer _ = libc.close(fd); // Sized first: FreeBSD's write does not grow a shared memory object. if (shm.ftruncate(fd, side * side * 4) != 0) return error.WriteFailed; var row: [600 * 4]u8 = undefined; for (0..side) |y| { for (row[0 .. side * 4], 0..) |*c, i| c.* = @truncate(i * 7 + y * 13 + seed); if (libc.write(fd, &row, side * 4) != side * 4) return error.WriteFailed; } const id = 5 + 10 * round; try out.print(gpa, "\x1b_Ga=T,i={d},f=24,s=2,v=2{s};AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=T,i={d},t=f,f=24,s=2,v=2{s};{s}\x1b\\\r\n" ++ "\x1b_Ga=T,i={d},t=t,f=24,s=2,v=2{s};{s}\x1b\\\r\n\x1b_Ga=T,i={d},t=s,f=32,s={d},v={d},c=8,r=4{s};{s}\x1b\\\r\n", .{ id, quiet, id + 1, quiet, enc.encode(&b64[0], path), id + 2, quiet, enc.encode(&b64[1], temp), id + 3, side, side, quiet, enc.encode(&b64[2], object), }); } try out.appendSlice(gpa, "$ "); return out.toOwnedSlice(gpa); } /// `before`, then `n` bytes of what a `cat` of source text prints through a /// pty: this file's lines, CR LF after each, again and again. /// A shell's: prompts marked (OSC 133), colours of the three kinds, wide /// and combined graphemes, hyperlinks, tabs, a title and a directory, long /// lines that wrap, and a clear (ED2, ED3) now and then. fn shellStream() ![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); const w = &out.writer; try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07"); for (0..400) |i| { try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i}); try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 }); try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i}); if (i % 7 == 0) { for (0..12) |_| try w.writeAll("a long line that wraps "); try w.writeAll("\r\n"); } try w.writeAll("\x1b]133;D;0\x07"); if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J"); if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 }); } return out.toOwnedSlice(); } /// A full-screen program's: the alternate screen and its modes, a status /// line, a scrolling region scrolled both ways, lines inserted and /// deleted, cursor shapes, the kitty keyboard pushed and popped. fn tuiStream() ![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); const w = &out.writer; try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J"); for (0..300) |f| { try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f}); try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f }); if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m"); if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M"); try w.writeAll("\x1b[r"); try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 }); if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q"); } try w.writeAll("\x1b[= sh.line.len) return; sh.put(&.{c}); if (sh.cur < sh.len) { sh.put(sh.line[sh.cur..sh.len]); sh.print("\x1b[{d}D", .{sh.len - sh.cur}); } std.mem.copyBackwards(u8, sh.line[sh.cur + 1 .. sh.len + 1], sh.line[sh.cur..sh.len]); sh.line[sh.cur] = c; sh.len += 1; sh.cur += 1; } fn key(sh: *FakeShell, b: []const u8) void { const printable = b.len == 1 and b[0] >= 0x20 and b[0] < 0x7f; const eql = std.mem.eql; switch (sh.mode) { .prompt => if (printable) sh.insert(b[0]) else if (eql(u8, b, "\x7f")) { if (sh.cur == 0) return; if (sh.cur == sh.len) sh.put("\x08\x1b[K") else { sh.put("\x08"); sh.put(sh.line[sh.cur..sh.len]); sh.print(" \x1b[{d}D", .{sh.len - sh.cur + 1}); } std.mem.copyForwards(u8, sh.line[sh.cur - 1 .. sh.len - 1], sh.line[sh.cur..sh.len]); sh.len -= 1; sh.cur -= 1; } else if (eql(u8, b, "\x1b[D")) { if (sh.cur == 0) return; sh.put(b); sh.cur -= 1; } else if (eql(u8, b, "\x1b[C")) { if (sh.cur == sh.len) return; sh.put(b); sh.cur += 1; } else if (eql(u8, b, "\t")) { if (sh.cur != sh.len or std.mem.indexOfScalar(u8, sh.line[0..sh.len], ' ') != null) return; for ([_][]const u8{ "echo", "sudo", "sink", "cat", "vim" }) |cmd| { if (sh.len == 0 or sh.len >= cmd.len or !std.mem.startsWith(u8, cmd, sh.line[0..sh.len])) continue; for (cmd[sh.len..]) |ch| sh.insert(ch); sh.insert(' '); return; } } else if (eql(u8, b, "\r")) { var cmd_buf: [256]u8 = undefined; const cmd = cmd_buf[0..sh.len]; @memcpy(cmd, sh.line[0..sh.len]); sh.len = 0; sh.cur = 0; sh.put("\r\n\x1b]133;C;aid=pardes\x07"); if (cmd.len == 0) return sh.done(0); if (std.mem.startsWith(u8, cmd, "echo")) { sh.print("{s}\r\n", .{std.mem.trimStart(u8, cmd[4..], " ")}); sh.done(0); } else if (std.mem.startsWith(u8, cmd, "sudo")) { sh.put("[sudo] password for you: "); sh.mode = .password; } else if (eql(u8, cmd, "vim")) { sh.put("\x1b[?1049h\x1b[2J\x1b[H~\r\n~\r\n~\x1b[H"); sh.mode = .vim; } else if (eql(u8, cmd, "sink")) { sh.mode = .sink; } else if (eql(u8, cmd, "cat")) { sh.mode = .cat; } else { sh.print("fake: unknown command: {s}\r\n", .{cmd}); sh.done(127); } } else if (eql(u8, b, "\x03")) { sh.put("^C\r\n"); sh.done(130); }, .password => if (eql(u8, b, "\r")) { sh.put("\r\nsudo: 1 incorrect password attempt\r\n"); sh.done(1); } else if (eql(u8, b, "\x03")) { sh.put("^C\r\n"); sh.done(130); }, .vim => if (sh.vim_n > 0) { if (eql(u8, b, "\r")) { const quit = eql(u8, sh.vim_cmd[0..sh.vim_n], ":q"); sh.vim_n = 0; if (quit) { sh.put("\x1b[?1049l"); sh.done(0); } } else if (printable and sh.vim_n < sh.vim_cmd.len) { sh.vim_cmd[sh.vim_n] = b[0]; sh.vim_n += 1; } } else if (eql(u8, b, "i")) { sh.mode = .vim_insert; } else if (eql(u8, b, ":")) { sh.vim_cmd[0] = ':'; sh.vim_n = 1; }, .vim_insert => if (eql(u8, b, "\x1b")) { sh.mode = .vim; } else if (printable) sh.put(b), .sink => if (eql(u8, b, "\x03")) { sh.put("^C\r\n"); sh.done(130); }, .cat => if (printable) { sh.put(b); if (sh.len < sh.line.len) { sh.line[sh.len] = b[0]; sh.len += 1; } } else if (eql(u8, b, "\x7f")) { if (sh.len == 0) return; sh.put("\x08 \x08"); sh.len -= 1; } else if (eql(u8, b, "\r")) { sh.print("\r\n{s}\r\n", .{sh.line[0..sh.len]}); sh.len = 0; } else if (eql(u8, b, "\x04") and sh.len == 0) { sh.done(0); } else if (eql(u8, b, "\x03")) { sh.put("^C\r\n"); sh.done(130); }, } } }; /// The authority's host: each pty write tagged with the client input that /// made it. const EchoHost = struct { writes: std.ArrayListUnmanaged(struct { seq: u32, bytes: []u8 }) = .empty, current: u32 = 0, fn watched(_: ?*anyopaque) bool { return false; } fn ptyWrite(ctx: ?*anyopaque, _: pardes.Pane.Id, bytes: []const u8) void { const h: *EchoHost = @ptrCast(@alignCast(ctx.?)); h.writes.append(gpa, .{ .seq = h.current, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } fn ignore(_: ?*anyopaque, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore }; fn host(h: *EchoHost) pardes.Host { return .{ .ctx = h, .vtable = &vtable }; } }; const Typed = struct { seq: u32, section: u8, at: u64, printable: bool, /// What was predicted: the cell (its row in the active area) and the /// cursor after it. pred: ?struct { x: u16, y: u16, cp: u21 } = null, pcur: ?struct { x: u16, y: u16 } = null, /// The shell's mode as it took the key; whether it printed anything for /// it; the authority's last unit before that (its echo is in a later one). mode: ?FakeShell.Mode = null, echoed: bool = false, unit_before: u32 = 0, /// The authority's screen right after its echo: its cursor and the /// cursor's row; whether that is what was predicted. after: ?struct { x: u16, y: u16, row: [128]u21 } = null, truth: ?bool = null, /// Its prediction drawn: first, and in how many frames. first_visible: ?u64 = null, visible_frames: u32 = 0, /// The client's emulator showing its echo, first. seen: ?u64 = null, }; const EchoTotals = struct { keys: u64 = 0, echo_keys: u64 = 0, latency: std.ArrayListUnmanaged(u64) = .empty, predicted: u64 = 0, unpredicted: u64 = 0, confirmed: u64 = 0, mispredicted: u64 = 0, cursor_missed: u64 = 0, right: u64 = 0, wrong: u64 = 0, wrong_shown: u64 = 0, wrong_frames: u64 = 0, wrong_max: u64 = 0, secret_frames: u64 = 0, alt_predicted: u64 = 0, divergences: u64 = 0, unequal: u64 = 0, /// The replica's frame drawn while it shows a prediction (its core's /// render, the tty's and the GUI's), and the overlay's part of it (ns); /// cells drawn otherwise than predicted. render_ns: std.ArrayListUnmanaged(u64) = .empty, paint_ns: std.ArrayListUnmanaged(u64) = .empty, drawn_frames: u64 = 0, paint_wrong: u64 = 0, sec: [sections.len]Section = @splat(.{}), const Section = struct { keys: u64 = 0, predicted: u64 = 0, wrong_frames: u64 = 0, latency: std.ArrayListUnmanaged(u64) = .empty }; fn deinit(et: *EchoTotals) void { for (&et.sec) |*x| x.latency.deinit(gpa); et.latency.deinit(gpa); et.render_ns.deinit(gpa); et.paint_ns.deinit(gpa); } }; fn cellCp(state: *pardes.Term.State, x: u16, y: u16) u21 { const ci = pardes.Term.emulatorOf(state).vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return 0x10ffff; const cp = ci.cell.codepoint(); return if (cp == 0) ' ' else cp; } /// A key's prediction against the authority's screen right after its echo, /// once both are known (a key typed behind one not predicted is predicted /// after the authority has it). fn judgeTruth(k: *Typed) void { if (k.truth != null) return; const pc = k.pcur orelse return; const after = k.after orelse return; var ok = after.x == pc.x and after.y == pc.y; if (k.pred) |cell| ok = ok and cell.y == after.y and cell.x < after.row.len and after.row[cell.x] == cell.cp; k.truth = ok; if (trace and !ok) std.debug.print("key {d} in {t} predicted cursor {d},{d} cell {any}; the authority's cursor {d},{d}\n", .{ k.seq, k.mode.?, pc.x, pc.y, k.pred, after.x, after.y }); } fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { var prng = std.Random.DefaultPrng.init(seed *% 0x9e3779b97f4a7c15 +% rtt_ms); const random = prng.random(); var host: EchoHost = .{}; defer { for (host.writes.items) |w| gpa.free(w.bytes); host.writes.deinit(gpa); } var sh: FakeShell = .{}; defer sh.out.deinit(gpa); const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host()); defer a.deinit(); const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0)); defer rp.deinit(); rp.core().echo = &rp.echo; rp.echo.on = on; const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; var corpus: Corpus = .{ .random = random }; defer corpus.steps.deinit(gpa); try corpus.build(); var typed: std.ArrayListUnmanaged(Typed) = .empty; defer typed.deinit(gpa); var t: Totals = .{}; defer { t.spec_ns.deinit(gpa); t.copy_ns.deinit(gpa); t.rollback_ns.deinit(gpa); } 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 = rtt_ms * 1000 / 2; const jitter = one_way / 10; var up: [1]Link = @splat(.{}); var down: [1]Link = @splat(.{}); // The last of the authority's own units the replica fed its emulator. var fed: u32 = 0; // The shell's first prompt. sh.put(prompt_bytes); a.output(.{ .output = .{ .pane = .at(shell), .bytes = sh.out.items } }); sh.out.clearRetainingCapacity(); var next_step: usize = 0; try push(&queue, &n, .{ .at = corpus.steps.items[0].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} }); try push(&queue, &n, .{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); try push(&queue, &n, .{ .at = random.uintLessThan(u64, frame_us), .n = 0, .kind = .client_frame, .who = 1, .bytes = &.{} }); // Two clocks tick while anything else moves, and a second after. var periodic: usize = 2; var left: [2]u32 = .{ 60, 60 }; var frame_arena: std.heap.ArenaAllocator = .init(gpa); defer frame_arena.deinit(); var made: std.ArrayListUnmanaged(Echo.Predicted) = .empty; defer made.deinit(gpa); rp.echo.log = &made; while (queue.pop()) |m| { defer if (m.bytes.len > 0) gpa.free(m.bytes); rp.echo.now = m.at * 1000; // What it predicted in the last event's calls (a key typed, or the // keys behind one it did not, at a unit, a delta or a frame). defer { const top = rp.echo.tops[shell]; for (made.items) |pr| { const k = &typed.items[pr.seq - 1]; if (trace) { const sc = pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt.screens.active.cursor; std.debug.print("{d} ms ({t}): key {d} predicted {any} cursor {d}; acked {d} wait {d} nd {d}; the screen's cursor {d},{d}\n", .{ m.at / 1000, m.kind, pr.seq, pr.cell, pr.cursor.x, rp.echo.acked, rp.echo.wait, rp.echo.nd, sc.x, sc.y }); } if (pr.cell) |cell| k.pred = .{ .x = cell.x, .y = @intCast(cell.row - top), .cp = cell.cp }; k.pcur = .{ .x = pr.cursor.x, .y = @intCast(pr.cursor.row - top) }; judgeTruth(k); } made.clearRetainingCapacity(); } switch (m.kind) { .input => { const step = corpus.steps.items[next_step]; next_step += 1; const msg = try gpa.dupe(u8, try rp.input(.{ .key = step.key })); const seq = rp.next_seq - 1; try typed.append(gpa, .{ .seq = seq, .section = step.section, .at = m.at, .printable = step.key.text.len == 1 }); if (trace) std.debug.print("{d} ms: key {d} typed: '{s}' cp {x}\n", .{ m.at / 1000, seq, step.key.text, step.key.cp }); try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .to_authority, .who = 1, .bytes = msg }); if (next_step < corpus.steps.items.len) try push(&queue, &n, .{ .at = m.at + corpus.steps.items[next_step].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} }); }, .to_authority => { if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); host.current = (replica.parseInput(m.bytes) orelse return error.BadInput).seq; const unit = try a.take(m.bytes); host.current = 0; try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter); for (host.writes.items) |w| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = shell, .bytes = w.bytes, .seq = w.seq }); host.writes.clearRetainingCapacity(); }, .echo => { const ty: ?*Typed = if (m.seq > 0) &typed.items[m.seq - 1] else null; const state = a.core.panes[shell].?.terminal.?; if (ty) |k| { k.mode = sh.mode; k.unit_before = a.seq; } sh.key(m.bytes); if (sh.out.items.len > 0) { a.output(.{ .output = .{ .pane = .at(shell), .bytes = sh.out.items } }); sh.out.clearRetainingCapacity(); if (ty) |k| k.echoed = true; } if (ty) |k| { const cur = pardes.Term.emulatorOf(state).vt.screens.active.cursor; k.after = .{ .x = @intCast(cur.x), .y = @intCast(cur.y), .row = undefined }; for (&k.after.?.row, 0..) |*cp, x| cp.* = cellCp(state, @intCast(x), @intCast(cur.y)); judgeTruth(k); } }, .frame => { if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; left[0] = if (busy) 60 else left[0] -| 1; if (left[0] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }) else periodic -= 1; }, .client_frame => { _ = rp.echoFrame(); const core = rp.core(); const drawn = rp.echo.visible(core) and core.panes[shell].?.body.mode == .tty; if (drawn and rp.echo.n > 0) { // Drawn as the client draws it: each cell where it was // predicted. _ = frame_arena.reset(.retain_capacity); core.needs_frame = true; const t0 = pardes.FrameStats.nowNs(); const surf = try core.render(frame_arena.allocator()); try et.render_ns.append(gpa, pardes.FrameStats.nowNs() - t0); const body = surf.region(.body, shell).?.rect; const top = rp.echo.tops[shell]; for (rp.echo.cells[0..rp.echo.n]) |cell| { if (cell.row < top or surf.at(body.x + cell.x, body.y + @as(u16, @intCast(cell.row - top))).text[0] != cell.cp) et.paint_wrong += 1; } const t1 = pardes.FrameStats.nowNs(); rp.echo.paint(core, surf, core.panes[shell].?, shell, body.x, body.w, body.y, body.h, true); try et.paint_ns.append(gpa, pardes.FrameStats.nowNs() - t1); et.drawn_frames += 1; } if (drawn) for (rp.echo.cells[0..rp.echo.n]) |cell| { const k = &typed.items[cell.seq - 1]; k.visible_frames += 1; if (k.first_visible == null) { k.first_visible = m.at; if (trace) { const st = core.panes[shell].?.terminal.?; std.debug.print("{d} ms: key {d} ('{u}') drawn: trusted {} doubt {} phase {t} sem {t}\n", .{ m.at / 1000, cell.seq, cell.cp, rp.echo.trusted, rp.echo.doubt, pardes.Term.emulatorOf(st).stream.handler.phase, pardes.Term.emulatorOf(st).vt.screens.active.cursor.semantic_content }); } } }; for (typed.items) |*k| if (k.echoed and k.seen == null and fed > k.unit_before) { k.seen = m.at; }; const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; left[1] = if (busy) 60 else left[1] -| 1; if (left[1] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .client_frame, .who = 1, .bytes = &.{} }) else periodic -= 1; }, .to_replica => { rp.confirm(m.bytes); rp.settle(); if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0) { fed = u.seq; }; }, .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } } const s = rp.echo.stats; et.predicted += s.predicted; et.unpredicted += s.unpredicted; et.confirmed += s.confirmed; et.mispredicted += s.mispredicted; et.cursor_missed += s.cursor_missed; for (typed.items) |k| { et.keys += 1; const sec = &et.sec[k.section]; sec.keys += 1; if (k.pcur != null) sec.predicted += 1; if (k.visible_frames > 0 and k.truth != true) sec.wrong_frames += k.visible_frames; if (k.truth) |ok| { if (ok) et.right += 1 else et.wrong += 1; } const md = k.mode orelse .prompt; if (md == .password or md == .sink) et.secret_frames += k.visible_frames; if ((md == .vim or md == .vim_insert) and k.pcur != null) et.alt_predicted += 1; if (k.visible_frames > 0 and k.truth != true) { if (trace) std.debug.print("seed {d}: key {d} at {d} ms in {t} drawn {d} frames, truth {?}, predicted {any} cursor {any}, the authority after it {any}\n", .{ seed, k.seq, k.at / 1000, md, k.visible_frames, k.truth, k.pred, k.pcur, if (k.after) |af| .{ af.x, af.y } else null }); et.wrong_shown += 1; et.wrong_frames += k.visible_frames; et.wrong_max = @max(et.wrong_max, k.visible_frames); } if (k.printable and k.echoed and (md == .prompt or md == .cat)) { const seen = k.seen orelse std.math.maxInt(u64); const drawn = if (k.first_visible != null and k.truth == true) @min(k.first_visible.?, seen) else seen; if (drawn == std.math.maxInt(u64)) { std.debug.print("seed {d} rtt {d} ms: a key's echo was never drawn\n", .{ seed, rtt_ms }); et.unequal += 1; continue; } et.echo_keys += 1; try et.latency.append(gpa, drawn - k.at); try sec.latency.append(gpa, drawn - k.at); if (trace and drawn - k.at > 2 * frame_us) std.debug.print("key {d} at {d} ms in {t}: drawn after {d} ms, {s}\n", .{ k.seq, k.at / 1000, md, (drawn - k.at) / 1000, if (k.pcur == null) "not predicted" else if (k.first_visible == null) "predicted, not drawn" else if (k.truth != true) "predicted wrong" else "predicted, drawn late" }); } } if (rp.diverged) |why| { et.divergences += 1; std.debug.print("seed {d} rtt {d} ms: the replica diverged: {s}\n", .{ seed, rtt_ms, why }); } else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) { et.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the replica at quiescence: {s}\n", .{ seed, rtt_ms, if (rp.quiet()) "another digest" else "inputs still pending" }); } if (screenHash(&pardes.Term.emulatorOf(a.core.panes[shell].?.terminal.?).vt) != screenHash(&pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt)) { et.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the shell at quiescence is not the authority's\n", .{ seed, rtt_ms }); } } fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { var failed = false; var draw_lines: std.ArrayList(u8) = .empty; defer draw_lines.deinit(gpa); std.debug.print("predicted echo: one client typing the corpus into a shell, {d} seeds a cell; from a key to its character on the client's screen (ms, frames at 60 Hz)\n", .{seeds}); std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal\n", .{}); var by_section: std.ArrayList(u8) = .empty; defer by_section.deinit(gpa); var off: [sections.len][2]u64 = undefined; for (rtts) |rtt| for ([_]bool{ false, true }) |on| { var et: EchoTotals = .{}; defer et.deinit(); for (first..first + seeds) |seed| try runEcho(seed, rtt, on, &et); const ms = struct { fn f(us: u64) f64 { return @as(f64, @floatFromInt(us)) / 1000; } }.f; std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7}\n", .{ rtt, if (on) "on" else "off", et.keys, et.echo_keys, ms(pct(et.latency.items, 50)), ms(pct(et.latency.items, 90)), ms(pct(et.latency.items, 100)), et.predicted, et.unpredicted, et.right, et.wrong, et.confirmed, et.mispredicted, et.cursor_missed, et.wrong_shown, et.wrong_frames, et.wrong_max, et.secret_frames, et.alt_predicted, et.divergences, et.unequal, }); for (&et.sec, &off, sections) |*x, *o, name| { const p50 = pct(x.latency.items, 50) / 1000; const p90 = pct(x.latency.items, 90) / 1000; if (!on) { o.* = .{ p50, p90 }; continue; } try by_section.print(gpa, "{d:>4} {s:<14} {d:>5} {d:>9} {d:>7} {d:>4} -> {d:<4} {d:>4} -> {d:<4} {d:>12}\n", .{ rtt, name, x.keys, x.predicted, x.latency.items.len, o[0], p50, o[1], p90, x.wrong_frames }); } if (on) try draw_lines.print(gpa, "{d:>4} {d:>12} {d:>6}/{d:<6} {d:>5}/{d:<5} {d:>10}\n", .{ rtt, et.drawn_frames, pct(et.render_ns.items, 50) / 1000, pct(et.render_ns.items, 99) / 1000, pct(et.paint_ns.items, 50), pct(et.paint_ns.items, 99), et.paint_wrong }); if (et.divergences > 0 or et.unequal > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true; }; std.debug.print("by part of the corpus (all seeds): keys typed, predicted, echoed (the latency sample); key to its character on the screen, ms, without -> with; frames a wrong prediction was drawn\n rtt part keys predicted echoed p50 off/on p90 off/on drawn-wrong\n{s}", .{by_section.items}); std.debug.print("the client's frames drawn with a prediction shown: its render (us) and the overlay's part (ns); cells drawn otherwise than predicted\n rtt frames-drawn render p50/p99 paint p50/p99 drawn-wrong\n{s}", .{draw_lines.items}); return !failed; } fn secs(us: u64) f64 { return @as(f64, @floatFromInt(us)) / std.time.us_per_s; } fn msOf(ns: u64) f64 { return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; } fn pct(samples: []u64, p: usize) u64 { if (samples.len == 0) return 0; std.mem.sort(u64, samples, {}, std.sort.asc(u64)); return samples[@min(samples.len - 1, samples.len * p / 100)]; } pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); // A loop that does not end names itself (`Watchdog`): its gdb, a child, // may trace this process. _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PTRACER), std.math.maxInt(usize), 0, 0, 0); if (std.Thread.spawn(.{}, Watchdog.run, .{})) |th| th.detach() else |_| {} var seeds: u64 = 4; var first: u64 = 0; var steps: usize = 120; var clients: u16 = 5; var rtts: []const u64 = &.{ 30, 80, 207 }; var echo_mode = false; var flood_mb: u64 = 8; var rtt_buf: [8]u64 = undefined; var addons: std.ArrayListUnmanaged([]const u8) = .empty; defer addons.deinit(gpa); var i: usize = 1; while (i < args.len) : (i += 1) { const name = args[i]; if (std.mem.eql(u8, name, "--echo")) { echo_mode = true; continue; } if (std.mem.eql(u8, name, "--witness")) { witness_always = true; continue; } if (std.mem.eql(u8, name, "--pair")) { pair_mode = true; continue; } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { var whole: [libc.PATH_MAX]u8 = undefined; pdf_path = try init.arena.allocator().dupe(u8, std.mem.span(libc.realpath(try init.arena.allocator().dupeSentinel(u8, value, 0), &whole) orelse return error.NoPdf)); } else if (std.mem.eql(u8, name, "--rtt")) { var it = std.mem.tokenizeScalar(u8, value, ','); var k: usize = 0; while (it.next()) |v| : (k += 1) rtt_buf[k] = try std.fmt.parseInt(u64, v, 10); rtts = rtt_buf[0..k]; } else return error.UnknownOption; } trace = libc.getenv("PARDES_REPLICA_TRACE") != null; if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff; var dir_buf: [256]u8 = undefined; const tmp = std.mem.span(libc.getenv("TMPDIR") orelse "/tmp"); const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) }); try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir); // 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 // installed, read by the session's core and its clients' alike. var data_buf: [300]u8 = undefined; const data = try std.fmt.bufPrintSentinel(&data_buf, "{s}/data", .{dir}, 0); var lib_dir_buf: [300]u8 = undefined; const lib_dir = try std.fmt.bufPrint(&lib_dir_buf, "{s}/pardes/addons", .{data}); try std.Io.Dir.cwd().createDirPath(init.io, lib_dir); for (addons.items) |lib| { var to: [600]u8 = undefined; var from: [600]u8 = undefined; var whole: [libc.PATH_MAX]u8 = undefined; const at = libc.realpath(try std.fmt.bufPrintSentinel(&from, "{s}", .{lib}, 0), &whole) orelse return error.NoAddon; if (libc.symlink(at, try std.fmt.bufPrintSentinel(&to, "{s}/{s}", .{ lib_dir, std.Io.Dir.path.basename(lib) }, 0)) != 0) return error.NoAddon; } if (setenv("XDG_DATA_HOME", data, 1) != 0) return error.NoDataDir; if (echo_mode) { if (!try echoMain(seeds, first, rtts)) std.process.exit(1); return; } 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 and as much of a cat 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; defer term_lines.deinit(gpa); var join_lines: std.ArrayList(u8) = .empty; defer join_lines.deinit(gpa); var stop_lines: std.ArrayList(u8) = .empty; defer stop_lines.deinit(gpa); var far_lines: std.ArrayList(u8) = .empty; defer far_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); if (pair_mode) std.debug.print("rtt {d}: the pair's client booted its own core {d} times, {d} of them not the session's at its join\n", .{ rtt, t.boots, t.boots_unequal }); if (t.boots_unequal > 0) t.unequal += t.boots_unequal; 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, t.stopped, t.units, t.fast, rollbacks, t.mispredicted, t.foreign, @as(f64, @floatFromInt(rollbacks)) * 100 / @as(f64, @floatFromInt(@max(t.inputs, 1))), t.rebases, pct(t.spec_ns.items, 50) / 1000, pct(t.spec_ns.items, 99) / 1000, pct(t.copy_ns.items, 50) / 1000, pct(t.copy_ns.items, 99) / 1000, t.copy_bytes / @max(t.copies, 1) / 1024, pct(t.rollback_ns.items, 50) / 1000, pct(t.rollback_ns.items, 99) / 1000, t.divergences, t.unequal, }); const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6; try term_lines.print(gpa, "{d:>4} {d:>9.0} {d:>9}\n", .{ rtt, @as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), t.unit_bytes >> 10, }); try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ rtt, t.far_joins, t.far_lags, secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), secs(pct(t.far_final.items, 50)), secs(pct(t.far_final.items, 100)), t.queue_max >> 10, t.cut, msOf(pct(t.join_session_ns.items, 50)), msOf(pct(t.join_session_ns.items, 100)), msOf(pct(t.join_client_ns.items, 50)), msOf(pct(t.join_client_ns.items, 100)), t.join_client_ns.items.len, msOf(t.far_behind), msOf(t.near_behind), t.near_lags, }); // The far client shows the final screen in every run, and the near // ones never fall behind with it. if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; if (t.divergences > 0 or t.unequal > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{}); std.debug.print(" rtt unit B/s units KB\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 (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); std.debug.print(" rtt joins lags refresh s final s queue KB cut session ms client ms behind far/near ms\n{s}", .{far_lines.items}); if (failed) std.process.exit(1); } // ---- the frame corpus through a client ---- /// A frame as a frontend reads it (10a: the window and the terminal draw /// from these alone): its cells, cursor, chrome and regions, and the facts /// beside them. const Shown = struct { cells: std.ArrayListUnmanaged(pardes.Cell) = .empty, regions: std.ArrayListUnmanaged(pardes.Region) = .empty, cols: u16 = 0, rows: u16 = 0, cursor: @FieldType(pardes.Surface, "cursor") = null, chrome: @FieldType(pardes.Surface, "chrome") = .{}, facts: pardes.Facts = .{}, placements: u32 = 0, frames: u32 = 0, fn take(sh: *Shown, s: *const pardes.Surface) void { sh.cells.clearRetainingCapacity(); sh.cells.appendSlice(gpa, s.cells) catch {}; sh.regions.clearRetainingCapacity(); sh.regions.appendSlice(gpa, s.regions[0..s.nregions]) catch {}; sh.cols = s.cols; sh.rows = s.rows; sh.cursor = s.cursor; sh.chrome = s.chrome; sh.facts = s.facts.*; sh.placements = @intCast(s.placements.items.len); sh.frames += 1; } fn deinit(sh: *Shown) void { sh.cells.deinit(gpa); sh.regions.deinit(gpa); } /// What differs between two frames, or null. fn differ(a: *const Shown, b: *const Shown, buf: []u8) ?[]const u8 { if (a.cols != b.cols or a.rows != b.rows) return std.fmt.bufPrint(buf, "the size {d}x{d} against {d}x{d}", .{ a.cols, a.rows, b.cols, b.rows }) catch "the size"; var cells: usize = 0; var first: usize = 0; // As a frontend reads a cell (Cell.visuallyEqual, glide.sameRow): // its text up to `len`, its style, or that it is blank. The bytes // of `text` past `len` are whatever its cell held before // (Surface.set copies the grapheme's own): no frontend reads them. for (a.cells.items, b.cells.items, 0..) |x, y, i| if (!x.visuallyEqual(&y)) { if (cells == 0) first = i; cells += 1; }; if (cells > 0) return std.fmt.bufPrint(buf, "{d} cells, the first at {d},{d}", .{ cells, first % a.cols, first / a.cols }) catch "cells"; if (!std.meta.eql(a.cursor, b.cursor)) return "the cursor"; if (!std.meta.eql(a.chrome, b.chrome)) return "the chrome"; if (a.regions.items.len != b.regions.items.len) return "the regions"; for (a.regions.items, b.regions.items) |x, y| if (!std.meta.eql(x, y)) return "a region"; if (!std.meta.eql(a.facts, b.facts)) return "the facts"; if (a.placements != b.placements) return "the placements"; return null; } }; /// A session's own frontend: what its pump presents, kept. const ShownHost = struct { shown: Shown = .{}, fn watched(_: ?*anyopaque) bool { return true; } fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool { const h: *ShownHost = @ptrCast(@alignCast(ctx.?)); h.shown.take(s); return true; } const vtable = replica.everyEntry(.{ .watched = watched, .present = present }); fn host(h: *ShownHost) pardes.Host { return .{ .ctx = h, .vtable = &vtable }; } }; /// A client's frontend that keeps what it presents, and has nothing of its /// own: the client loop's frames, as a frontend would be given them. const Shows = struct { shown: Shown = .{}, pub fn start(_: *Shows, l: *client_loop.Loop(Shows)) void { _ = l; } pub fn own(_: *Shows, _: *client_loop.Loop(Shows)) bool { return true; } pub fn again(_: *Shows, _: *client_loop.Loop(Shows)) bool { return false; } pub fn deadline(_: *Shows, _: *client_loop.Loop(Shows)) u32 { return client_loop.forever; } pub fn wait(_: *Shows, _: *client_loop.Loop(Shows), _: u32) void {} pub fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool { const f: *Shows = @ptrCast(@alignCast(ctx.?)); f.shown.take(s); return true; } pub fn drawn(_: *Shows) client_loop.Drawn { return .{ .drew = true, .moving = false }; } pub fn copy(_: *Shows, _: []const u8) void {} pub fn paste(_: *Shows, _: *client_loop.Loop(Shows)) void {} pub fn open(_: *Shows, _: []const u8) void {} }; /// The frame corpus's scenes (test/process/window.zig `corpus`, what a /// session's core makes of them: its files, a wheel, a click, a jump, the /// taglines' size, a markdown file, a picture, three columns, a dirty /// pane, InactiveDim, WindowOpacity, ligatures, a resize) typed twice: /// into a session's own view, drawn by its own pump as its own frontend's /// is, and into a client's view of another session of the same files, /// through the client loop (runtime/client.zig) and the session's units. /// After each, at rest, the two frames are the same: what a frontend draws /// from (10a) is the same through a client as its own. GPU pixels are not /// drawn here; the corpus's own gate (77 frames) proves the window draws /// these alike. fn corpusCase(dir: []const u8) !bool { var path_bufs: [5][300]u8 = undefined; const shapes = try std.fmt.bufPrintSentinel(&path_bufs[0], "{s}/shapes.zig", .{dir}, 0); var zig: std.ArrayListUnmanaged(u8) = .empty; defer zig.deinit(gpa); try zig.appendSlice(gpa, "const std = @import(\"std\");\n\npub const Shape = union(enum) {\n circle: f32,\n square: f32,\n};\n\npub fn main() void {\n var total: f32 = 0;\n"); for (0..80) |n| try zig.print(gpa, " total += {d}; // line {d}\n", .{ n, n }); try zig.appendSlice(gpa, " std.debug.print(\"{d}\\n\", .{total});\n}\n"); try writeText(shapes, zig.items); const notes = try std.fmt.bufPrintSentinel(&path_bufs[1], "{s}/notes.md", .{dir}, 0); try writeText(notes, "# Fallback faces and rules\n\n| name | glyphs |\n|------|--------|\n| cjk | 界面字 |\n| sym | ∮ ≠ ★ |\n\n┌──┬──┐\n│ a│ b│\n└──┴──┘\n"); const ligatures = try std.fmt.bufPrintSentinel(&path_bufs[2], "{s}/ligatures.zig", .{dir}, 0); try writeText(ligatures, "const a = b -> c; // => != <= >= == === !== |> <| :: ++ --\nconst fi = \"office flow staff\";\n"); var looks: [3][320]u8 = undefined; const Wheel = struct { fn at(button: @FieldType(@FieldType(pardes.Event, "mouse"), "button"), kind: @FieldType(@FieldType(pardes.Event, "mouse"), "kind"), col: u16, row: u16) pardes.Event { return .{ .mouse = .{ .button = button, .kind = kind, .col = col, .row = row } }; } }; const k = struct { fn of(cp: u21) pardes.Event { return .{ .key = .{ .cp = cp, .text = switch (cp) { 'g' => "g", 'j' => "j", else => "", } } }; } }; const steps = [_]pardes.Event{ Wheel.at(.wheel_down, .press, 40, 12), Wheel.at(.wheel_down, .press, 40, 12), Wheel.at(.wheel_down, .press, 40, 12), Wheel.at(.left, .press, 20, 10), Wheel.at(.left, .release, 20, 10), k.of('g'), k.of('g'), .{ .command = "TaglineSize 80" }, k.of('j'), k.of('j'), k.of('j'), .{ .command = try std.fmt.bufPrint(&looks[0], "Look {s}", .{notes}) }, .{ .command = "Newcol" }, .{ .command = "Newcol" }, .{ .command = "New" }, .{ .paste = "a dirty pane\n" }, .{ .command = "InactiveDim 40" }, .{ .command = "WindowOpacity 71" }, .{ .command = try std.fmt.bufPrint(&looks[1], "Look {s}", .{ligatures}) }, .{ .command = "Zerox" }, .{ .key = .{ .cp = Key.escape } }, .{ .resize = .{ .cols = 70, .rows = 20 } }, }; var own_host: ShownHost = .{}; defer own_host.shown.deinit(); var noop: Host = .{}; const options: pardes.Options = .{ .cols = 100, .rows = 22, .file = shapes }; const a = try replica.Authority.init(gpa, options, own_host.host()); defer a.deinit(); const b = try replica.Authority.init(gpa, options, noop.host()); defer b.deinit(); noop.core = b.core; _ = try b.unit(0, 0); const j = (try b.join(1, null)) orelse return error.NoView; defer gpa.free(j.dump); const rp = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 100, .rows = 22 }); defer rp.deinit(); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer for (fds) |fd| { _ = libc.close(fd); }; _ = libc.fcntl(fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); var shows: Shows = .{}; defer shows.shown.deinit(); var frames: pardes.FrameStats = .{}; var l: client_loop.Loop(Shows) = .{ .link = .{ .r = rp, .fd = fds[1] }, .fe = &shows, .frames = &frames }; const Both = struct { a: *replica.Authority, b: *replica.Authority, l: *client_loop.Loop(Shows), fd: c_int, /// `ev` into the session's own view, and through the client loop /// into the client's: the session's unit back to it, at once. fn step(s: @This(), ev: pardes.Event) !void { _ = try s.a.own(ev); s.l.input(ev); const r = s.l.link.r; if (try s.b.pending()) |batch| s.l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, batch) }); const msg = try gpa.dupe(u8, r.out.items); defer gpa.free(msg); s.l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, try s.b.take(msg)) }); s.l.woken(); var sink: [4096]u8 = undefined; while (libc.read(s.fd, &sink, sink.len) > 0) {} } }; const both: Both = .{ .a = a, .b = b, .l = &l, .fd = fds[0] }; // What each is, then its size: its view's first inputs. try both.step(.{ .frontend = .{ .windowed = false } }); try both.step(.{ .resize = .{ .cols = 100, .rows = 22 } }); var ok = true; var why: [120]u8 = undefined; for (steps, 0..) |ev, n| { try both.step(ev); if (!rp.quiet() or rp.diverged != null) { std.debug.print("corpus through a client: step {d} ({t}): the client is not the session's ({s})\n", .{ n, ev, rp.diverged orelse "inputs pending" }); ok = false; continue; } if (Shown.differ(&own_host.shown, &shows.shown, &why)) |what| { std.debug.print("corpus through a client: step {d} ({t}): the client's frame is not the own frontend's: {s}\n", .{ n, ev, what }); ok = false; } } std.debug.print("corpus through a client: {d} scenes, the own frontend drew {d} frames and the client {d}; {s}\n", .{ steps.len, own_host.shown.frames, shows.shown.frames, if (ok) "every scene's frame the same" else "FAILED" }); return ok; }