//! pardes-replicas: a session and its clients in one process
//! (core/replica.zig): the session's own frontend typing in its view and
//! drawing it, and each client (THE client loop, runtime/client.zig, over a
//! 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 screen state (core/term/screen_state.zig): the session's
//! shell pane runs a full-screen program and then a `yes` flood (`--flood`
//! MB of it) while the clients type, its output stepped by the authority
//! and sent to each replica as deltas, once a frame and before any input
//! the authority steps, each replica acknowledging them over its link and
//! asking for the rows it scrolls back into and does not hold.
//!
//! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB]
//! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K]
//! zig build replicas -Dplatform=tui -Doptimize=ReleaseFast -- --screen-state
//!
//! `--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". `--screen-state` runs recorded pty streams through
//! screen_state's soak and measures its encoder: below, at screenState.
//!
//! 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; every delta a replica applies leaves its
//! terminal what the authority's was at that version, and at quiescence it
//! is the authority's, cell for cell. Reported per RTT: how inputs went
//! (applied at once, stopped at a host call, left to the authority), how
//! units were taken (fast path, rollback for a misprediction or another's
//! input), what a speculative apply, a copy and a rollback cost against a
//! frame, and the terminals': deltas a second, wire bytes a second under
//! the flood, encode a frame (every peer), apply a delta.
const std = @import("std");
const libc = std.c;
const pardes = @import("pardes");
const replica = pardes.replica;
const client_loop = @import("runtime").client;
const screen_state = @import("term").screen_state;
const Echo = pardes.Echo;
const Key = pardes.Key;
const gpa = std.heap.c_allocator;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
var trace = false;
/// The PDF the soak opens (`--pdf`), absolute.
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, pane: u8, bytes: []const u8) void {
const h: *Host = @ptrCast(@alignCast(ctx.?));
h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {};
}
fn 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, pane: u8, serial: u32, token: u32) void {
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,
screen_down,
screen_up,
client_frame,
/// The session's own frontend's input, in its own view.
own,
/// A client's join: its dial at the session, its dump (or refusal)
/// back; its check of the session's digest asked and answered; its
/// bye; a wake its loop asked for (`quietCheck`); its quit.
dial,
dump,
refused,
check_up,
checked,
bye_up,
wake,
quit,
/// 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,
};
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 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.
apply_ns: std.ArrayListUnmanaged(u64) = .empty,
frame_ns: std.ArrayListUnmanaged(u64) = .empty,
deltas: u64 = 0,
delta_bytes: u64 = 0,
unit_bytes: u64 = 0,
/// Deltas the replicas applied while the flood ran.
flood_deltas: u64 = 0,
flood_us: u64 = 0,
flood_delta_bytes: u64 = 0,
flood_unit_bytes: u64 = 0,
fetched: u64 = 0,
/// Bytes of rows sent before a step's unit, the step having read them.
filled_bytes: u64 = 0,
resets: u64 = 0,
screens_wrong: u64 = 0,
screens_checked: u64 = 0,
/// Joins from a dump, refused, again after a divergence put on it
/// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks.
joins: u64 = 0,
refused: u64 = 0,
rejoined: u64 = 0,
detached: u64 = 0,
agree: u64 = 0,
differ: u64 = 0,
/// Resizes the windows posted (each pass whose view's size is not
/// the window's: gui.zig `OwnView.run`).
resizes: u64 = 0,
/// 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),
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);
try t.apply_ns.appendSlice(gpa, s.apply_ns.items);
}
};
/// One client's next input: monkey.zig's mix, as events, and now and then
/// a wheel over the shell pane, which scrolls its history into view; 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) 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)];
return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
},
16...27 => {
buf[0] = normal[random.uintLessThan(usize, normal.len)];
return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
},
28...31 => return .{ .key = .{ .cp = Key.escape } },
32 => return .{ .key = .{ .cp = Key.enter } },
33 => return .{ .key = .{ .cp = Key.backspace } },
34 => return .{ .key = .{ .cp = switch (random.uintLessThan(u8, 4)) {
0 => Key.up,
1 => Key.down,
2 => Key.left,
else => Key.right,
} } },
35 => {
const n = random.intRangeAtMost(usize, 1, 24);
for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)];
return .{ .paste = buf[0..n] };
},
36 => return .{ .command = switch (random.uintLessThan(u8, 16)) {
0 => "Newcol",
1 => "Zerox",
2 => "Undo",
3 => "Redo",
4 => "Search Panes",
5 => "Search Recent",
6, 7 => looks[random.uintLessThan(usize, looks.len)],
8 => "Del",
// 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).
12 => if (random.uintLessThan(u8, 4) == 0) "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,
};
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 screen_state's dump of it.
/// The module's own replica behind the core's handle (Replica.screens).
fn replicaOf(r: *pardes.Term.Replica) *screen_state.Replica {
return @ptrCast(@alignCast(r));
}
/// The module's own track behind the core's handle (Screens.tracks).
fn trackOf(t: *pardes.Term.Track) *screen_state.Track {
return @ptrCast(@alignCast(t));
}
fn screenHash(t: *screen_state.Terminal) u64 {
var buf: [8192]u8 = undefined;
var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf);
screen_state.dumpScreen(t, &h.writer) catch {};
h.writer.flush() catch {};
return h.hasher.final();
}
/// 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 whose other end the soak reads as the session's Peer does
/// (`drain`). It joins from the session's dump, may be refused (every view
/// taken), leaves, and joins again for its view after a divergence.
const Client = struct {
kind: enum { tty, window },
loop: ClientLoop = undefined,
r: ?*replica.Replica = null,
fds: [2]c_int = .{ -1, -1 },
check: [:0]u8 = undefined,
/// The session's side of its socket: bytes not yet a whole frame, the
/// stamp before an input, and the inputs it took (Peer.seq).
got: std.ArrayListUnmanaged(u8) = .empty,
stamp: std.ArrayListUnmanaged(u8) = .empty,
seq: u32 = 0,
/// Its id and its terminals' peer at the session, and the view the
/// session made or keeps for it (`back`, joining again).
id: u16 = 0,
sid: u16 = 0,
view: u8 = 0,
back: ?u8 = null,
digest: u64 = 0,
/// Joins the session made for it (its side), and the one its replica
/// is of (0: none, its link ended).
gen: u32 = 0,
live: u32 = 0,
joined: bool = false,
dialling: bool = false,
/// Refusals in a row, until it gives up (a person would).
tries: u32 = 0,
left: usize,
cols: u16,
rows: u16,
/// 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(.{}),
/// 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;
}
};
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(.{}),
fn send(net: *Net, m: Msg) !void {
var mm = m;
mm.n = net.n;
net.n += 1;
try net.q.push(gpa, mm);
}
/// Down client `c`'s link (the session's stream to it), `bytes` its.
fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void {
try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen });
}
};
/// What client `c` wrote to its socket since (its inputs, its terminal
/// messages, a check asked, its bye), read off the other end as the
/// session's Peer reads it (`Peer.take`), up its link.
fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void {
var buf: [1 << 16]u8 = undefined;
while (true) {
const k = libc.read(cl.fds[0], &buf, buf.len);
if (k <= 0) break;
try cl.got.appendSlice(gpa, buf[0..@intCast(k)]);
}
const wire = pardes.wire;
var at: usize = 0;
while (try wire.framed(cl.got.items[at..])) |f| : (at += f.total) {
const frame = cl.got.items[at..][0..f.total];
const kind: Kind = switch (std.enums.fromInt(wire.ClientTag, f.tag) orelse return error.BadFrame) {
.stamp => {
cl.stamp.clearRetainingCapacity();
try cl.stamp.appendSlice(gpa, frame);
continue;
},
.screen_ack => .screen_up,
.check => .check_up,
.bye => .bye_up,
else => .to_authority,
};
var seq: u32 = 0;
const bytes: []u8 = switch (kind) {
.to_authority => in: {
// Its head (its id and seq at the session), its stamp, its event.
cl.seq += 1;
const msg = try gpa.alloc(u8, 6 + cl.stamp.items.len + frame.len);
std.mem.writeInt(u16, msg[0..2], cl.id, .little);
std.mem.writeInt(u32, msg[2..6], cl.seq, .little);
@memcpy(msg[6..][0..cl.stamp.items.len], cl.stamp.items);
@memcpy(msg[6 + cl.stamp.items.len ..], frame);
cl.stamp.clearRetainingCapacity();
if (replica.parseInput(msg) == null) return error.BadInput;
break :in msg;
},
.screen_up => try gpa.dupe(u8, f.payload),
.bye_up => bye: {
seq = @intFromBool((try wire.decodeClient(f.tag, f.payload)).bye.again);
break :bye &.{};
},
else => &.{},
};
try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .seq = seq, .gen = cl.gen });
}
std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]);
cl.got.shrinkRetainingCapacity(cl.got.items.len - at);
}
/// 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(cl.fds[1], r.diverged != null);
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {
if (link.put_off) totals.rejoined += 1 else {
totals.divergences += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ run_.seed, run_.rtt_ms, c + 1, why });
}
}
if (link.rejoins()) {
cl.back = r.view;
cl.dialling = true;
return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
try totals.add(&r.stats);
r.deinit();
cl.r = null;
totals.detached += 1;
// 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;
}
}
fn run(r: Run, dir: []const u8, totals: *Totals) !void {
if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms });
var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms);
const random = prng.random();
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var paths: [3][256:0]u8 = undefined;
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;
};
const looks = looks_buf[0..nlooks];
// The tty's own boot (a raw shell, a text pane under it), then three
// files looked at: the session's own frontend shows the first view
// and types in it; each client joins from a dump for a view of its own.
host.clocked = true;
host.now_ns = std.time.ns_per_s;
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .addons = kinds }, host.host(), true);
defer a.deinit();
host.core = a.core;
var screens: replica.Screens = .init(gpa);
defer screens.deinit(a.core);
for (&paths) |*path| {
var line: [300]u8 = undefined;
_ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) });
}
// The picture and the PDF in a column of their own: every client joins
// with them (a plain kind's pane loaded from a dump, its file read by
// its path), its keys go to the one it is in when it has them.
if (looks.len > 3) {
_ = try a.local(.{ .command = "Newcol" });
_ = try a.local(.{ .command = looks[3] });
}
if (with_pdf) _ = try a.local(.{ .command = looks[4] });
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
} else return error.NoShell;
// Where a wheel over the shell lands in the session's view, which a
// client's view is a copy of as it joins; and the PDF's body there.
const sr = a.core.view().rects[shell];
const pr = if (with_pdf) a.core.view().rects[a.core.view().active] else pardes.Rect{};
const aim: Aim = .{
.shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null,
.pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } else null,
};
var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 };
defer {
while (net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes);
net.q.deinit(gpa);
}
pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go };
Draws.net = &net;
defer {
pardes.Kind.drawer = null;
Draws.net = null;
for (Draws.jobs.items) |j| j.drop();
Draws.jobs.clearRetainingCapacity();
}
// The clients: terminals and windows by turns. The first two dial at
// once, the third late (the shell's program on), more later still
// (refused while every view is taken, dialling again until one is
// let go); the first leaves when it is done; the second is put off
// the session once (PARDES_TEST_DIVERGE) and joins again for its view.
var clients: [8]Client = undefined;
for (clients[0..r.clients], 0..) |*cl, c| {
cl.* = .{ .kind = if (c % 2 == 0) .tty else .window, .left = r.steps, .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) };
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &cl.fds) != 0) return error.NoSocket;
_ = libc.fcntl(cl.fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true })));
var name: [300]u8 = undefined;
cl.check = try gpa.dupeSentinel(u8, try std.fmt.bufPrint(&name, "{s}/check-{d}", .{ dir, c }), 0);
_ = libc.unlink(cl.check);
cl.dialling = true;
const at: u64 = switch (c) {
0, 1 => random.uintLessThan(u64, 100_000),
2 => 1_200_000,
else => 2_000_000 + c * 100_000,
};
try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
defer for (clients[0..r.clients]) |*cl| {
if (cl.r) |rp| rp.deinit();
_ = libc.close(cl.fds[0]);
_ = libc.close(cl.fds[1]);
cl.got.deinit(gpa);
cl.stamp.deinit(gpa);
gpa.free(cl.check);
};
// The link is made at the first join (its replica the dump's).
var has_link: [8]bool = @splat(false);
defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) {
cl.loop.link.check = null;
cl.loop.link.deinit(gpa);
};
// What the shell's program prints: a full-screen program, a shell's
// session (prompts, titles, directories, a clear now and then), then a
// flood of `yes`, read 4 KB at a time as a pty gives it.
const tui = try screen_state.tuiStream(gpa);
defer gpa.free(tui);
const shell_session = try screen_state.shellStream(gpa);
defer gpa.free(shell_session);
const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3));
defer gpa.free(yes);
const tui_at: u64 = 400_000;
const session_at: u64 = 1_000_000;
const flood_at: u64 = 2_500_000;
var flood_end: u64 = 0;
var program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{};
// The authority's version of each terminal, as its screen showed then.
var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty;
defer versions.deinit(gpa);
var flood_deltas: [8]u64 = @splat(0);
// The session's own typist, and every client's, until each is done.
var own_left = r.steps;
var own_script: Script = .{};
var typing: usize = r.clients + 1;
var next_id: u16 = 1;
try net.send(.{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} });
try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} });
try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} });
try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} });
try net.send(.{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
var frames_left: u32 = 0;
var owed: std.ArrayListUnmanaged([]u8) = .empty;
defer owed.deinit(gpa);
const Session = struct {
a: *replica.Authority,
screens: *replica.Screens,
clients: []Client,
net: *Net,
owed: *std.ArrayListUnmanaged([]u8),
versions: *std.AutoHashMapUnmanaged(u64, u64),
totals: *Totals,
host: *Host,
kinds_seen: *u32,
/// A Detach its step took (Host.detach) in a client's view: that
/// client's link shut inside the step, before its unit goes
/// (Peers.detach), so it hears its end and not the unit; which it is.
fn detaching(s: @This(), now: u64) !?usize {
const k = s.host.detach_view orelse return null;
s.host.detach_view = null;
for (s.clients, 0..) |*cl, c| if (cl.joined and cl.view == k) {
cl.joined = false;
s.screens.dropPeer(cl.sid);
try s.net.toClient(c, now, .gone, cl.gen, &.{});
return c;
};
return null;
}
/// ...and let go at the next boundary, its view closed (Peers.leave).
fn detached(s: @This(), c: ?usize, now: u64) !void {
const gone = c orelse return;
try s.unit(try s.a.leave(s.clients[gone].id, false), now, false);
}
/// The batch of its own steps as a unit, if any (`Authority.pending`).
fn pending(s: @This(), now: u64, flooding: bool) !void {
if (try s.a.pending()) |batch| try s.unit(batch, now, flooding);
}
/// A unit to every client joined (Peers.unit), after the rows of
/// its terminals its steps read that a client holds as holes.
fn unit(s: @This(), u: []const u8, now: u64, flooding: bool) !void {
// The kinds' panes it has opened, each counted once.
for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) {
s.kinds_seen.* = pane.serial;
for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name));
};
var rows: std.ArrayListUnmanaged([]u8) = .empty;
defer rows.deinit(gpa);
for (s.clients, 0..) |*cl, c| if (cl.joined) {
rows.clearRetainingCapacity();
try s.screens.fill(s.a.core, cl.sid, &rows);
for (rows.items) |bytes| {
s.totals.filled_bytes += bytes.len;
try s.net.toClient(c, now, .screen_down, cl.gen, bytes);
}
};
s.screens.filled(s.a.core);
// The sizes its steps gave terminals, after their rows.
pardes.panes.resizeDeferred(s.a.core);
for (s.clients, 0..) |*cl, c| if (cl.joined) {
s.totals.unit_bytes += u.len;
if (flooding) s.totals.flood_unit_bytes += u.len;
try s.net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, u));
};
}
/// What each client is owed of the terminals (`Screens.flush`).
fn flush(s: @This(), now: u64, only: ?usize) !void {
for (s.clients, 0..) |*cl, c| if (cl.joined and (only == null or only.? == c)) {
s.owed.clearRetainingCapacity();
try s.screens.flush(s.a.core, cl.sid, 0, s.owed);
for (s.owed.items) |bytes| {
s.totals.deltas += 1;
s.totals.delta_bytes += bytes.len;
try s.net.toClient(c, now, .screen_down, cl.gen, bytes);
}
};
// Each version as the authority's screen showed it.
for (&s.screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| {
const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version;
if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue;
_ = s.a.core.panes[id] orelse continue;
try s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt));
};
}
};
var kinds_seen: u32 = 0;
const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals, .host = &host, .kinds_seen = &kinds_seen };
while (net.q.pop()) |m| {
defer if (m.bytes.len > 0) gpa.free(m.bytes);
Draws.now = m.at;
const flooding = m.at >= flood_at and flood_end == 0;
// A client's message, but an echo's and an output's `who` (a pane,
// a program).
const c: usize = if (m.who == 0 or m.kind == .echo or m.kind == .output) 0 else m.who - 1;
const cl = &clients[c];
switch (m.kind) {
// ---- the session ----
.own => {
host.now_ns = std.time.ns_per_s + m.at * 1000;
var buf: [64]u8 = undefined;
const ev = nextEvent(random, &buf, aim, looks, &own_script);
try ses.pending(m.at, flooding);
try ses.flush(m.at, null);
const u = try a.own(ev);
// Its own view's Detach is its terminal's: none here.
host.detach_view = null;
try ses.unit(u, m.at, false);
try ses.flush(m.at, null);
for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes });
host.echo.clearRetainingCapacity();
own_left -= 1;
if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1;
},
.to_authority, .echo, .output => {
// A pty's read wakes its loop as an input does; a client's
// mail alone leaves the clock where it was.
if (m.kind != .to_authority) host.now_ns = std.time.ns_per_s + m.at * 1000;
const unit = switch (m.kind) {
.echo => echo: {
a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } });
break :echo null;
},
.output => out: {
// The program's next read, 4 KB, then the next a
// fraction of a millisecond on (ghostty's pace).
if (program.at == program.bytes.len) {
program = .{ .bytes = switch (m.who) {
0 => tui,
1 => yes,
else => shell_session,
} };
}
const k = @min(program.bytes.len - program.at, if (m.who == 1) @as(usize, 4096) else 700);
const chunk = program.bytes[program.at..][0..k];
program.at += k;
if (program.at < program.bytes.len)
try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} })
else if (m.who == 1) flood_end = m.at;
a.output(.{ .output = .{ .pane = shell, .bytes = chunk } });
break :out null;
},
else => in: {
if (!cl.joined or m.gen != cl.gen) break :in null;
// The authority's own steps since the last unit, and
// the terminals as they are: what the input's step
// reads, before it is stepped (Peers.input).
try ses.pending(m.at, flooding);
try ses.flush(m.at, null);
break :in try a.take(m.bytes);
},
};
if (unit) |u| {
const gone = try ses.detaching(m.at);
try ses.unit(u, m.at, false);
try ses.detached(gone, m.at);
try ses.flush(m.at, null);
}
for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes });
host.echo.clearRetainingCapacity();
},
.frame => {
// Its own frontend's frame: its loop woken when a frame is
// owed or the core's next wake is due, a pump that advances
// its clock (what is due ticks: messages, glides, a kind's
// tick) and draws its view, as its host's loop paces it.
host.now_ns = std.time.ns_per_s + m.at * 1000;
if (a.core.needs_frame or (a.core.nextWake() orelse std.math.maxInt(u64)) <= host.now_ns) {
host.draws = true;
a.pump();
host.draws = false;
}
try ses.pending(m.at, flooding);
const t0 = screens.encode_ns;
const before = totals.delta_bytes;
try ses.flush(m.at, null);
if (m.at >= flood_at and (flood_end == 0 or m.at <= flood_end)) {
totals.flood_delta_bytes += totals.delta_bytes - before;
try totals.frame_ns.append(gpa, screens.encode_ns - t0);
}
// Frames go on while anyone types or the flood runs, and two
// seconds after (a session with a clock wakes on: a blink, a
// kind's tick; what is in flight still comes, unpumped).
const busy = typing > 0 or flood_end == 0;
frames_left = if (busy) 120 else frames_left -| 1;
if (frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
},
.dial => {
// Peers.join at the session's next boundary: its view kept
// for it, or a new one, or refused when all are taken.
try ses.pending(m.at, flooding);
const id = next_id;
const j = (try a.join(id, cl.back)) orelse {
totals.refused += 1;
try net.toClient(c, m.at, .refused, cl.gen, &.{});
continue;
};
next_id += 1;
try ses.unit(j.unit, m.at, false);
cl.joined = true;
cl.gen += 1;
cl.id = id;
cl.seq = 0;
cl.view = j.view;
cl.digest = j.digest;
cl.sid = try screens.addPeer();
totals.joins += 1;
try net.toClient(c, m.at, .dump, cl.gen, j.dump);
// Its terminals afresh, after its dump and before any unit.
try ses.flush(m.at, c);
},
.check_up => {
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
const d = try gpa.alloc(u8, 8);
std.mem.writeInt(u64, d[0..8], replica.digestOf(a), .little);
try net.toClient(c, m.at, .checked, cl.gen, d);
},
.bye_up => {
// Peers.leave: its view kept for it (`again`) or closed.
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
cl.joined = false;
screens.dropPeer(cl.sid);
try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false);
},
.screen_up => {
if (!cl.joined or m.gen != cl.gen) continue;
if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little);
if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer);
},
// ---- a client ----
.refused => {
if (!cl.dialling) continue;
// Said and gone; started again a while later (a person
// does), while it has keys left to type.
cl.back = null;
if (cl.r) |old| {
try totals.add(&old.stats);
old.deinit();
cl.r = null;
}
cl.tries += 1;
if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else {
// Given up on: its keys are never typed.
cl.dialling = false;
if (cl.left > 0) typing -= 1;
cl.left = 0;
}
},
.dump => {
cl.dialling = false;
cl.tries = 0;
// replica.join: the core it left let go once the new one
// is here, the dump loaded and checked by the digest.
if (cl.r) |old| {
try totals.add(&old.stats);
old.deinit();
}
const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted });
cl.r = rp;
rp.stats.samples = true;
rp.t.local_files = true;
rp.echo.now = m.at * 1000;
if (!rp.loaded(cl.digest)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ r.seed, r.rtt_ms, m.who });
}
cl.live = m.gen;
var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} };
if (!has_link[c]) {
cl.loop = .{ .link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }, .fe = cl, .frames = &cl.frames };
has_link[c] = true;
if (c == 1) cl.loop.link.test_diverge = 40;
}
cl.c = c;
cl.net = &net;
cl.now = m.at;
cl.wake_at = 0;
cl.stops = rp.stats.stops;
cl.loop.link.now = m.at * 1000;
cl.loop.link.reset(rp, &j);
cl.posted = null;
// The loop's join (Loop.run): its first inputs, then a pass
// up to its wait.
cl.start(&cl.loop);
_ = cl.loop.pass();
judgeStops(cl, c, totals, r);
try drain(cl, c, &net, m.at);
if (cl.left > 0 and cl.left == r.steps) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
},
.draw => {
// A worker's draw done, onto the loop of the core that asked
// it (tui.zig `.kind_job`): kept for its pane's next paint,
// a frame owed; one of a core gone since is let go.
const j = Draws.jobs.orderedRemove(0);
j.run();
// A state job's answer: a step of the session's own.
if (j.draw == null) {
host.now_ns = std.time.ns_per_s + m.at * 1000;
a.output(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
j.drop();
continue;
}
if (j.draw == @as(?*const pardes.Pardes, a.core)) {
pardes.Kind.landDraw(a.core, j);
continue;
}
const k = for (clients[0..r.clients], 0..) |*dc, k| {
if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k;
} else {
j.drop();
continue;
};
const dc = &clients[k];
pardes.Kind.landDraw(dc.r.?.core(), j);
dc.loop.link.dirty = true;
try woke(dc, k, &net, m.at, totals, r);
if (dc.loop.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing);
},
.input, .to_replica, .screen_down, .checked, .wake, .quit, .gone => {
if (m.kind == .input and cl.left == 0) continue;
const rp = cl.r orelse if (m.kind == .input and cl.dialling) {
try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
continue;
} else continue;
if (m.kind == .input) {
// A key typed while it joins again waits for the link.
if (cl.live == 0) {
try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
continue;
}
} else if (m.kind != .quit and m.gen != cl.live) continue;
rp.echo.now = m.at * 1000;
cl.now = m.at;
cl.loop.link.now = m.at * 1000;
switch (m.kind) {
.input => {
var buf: [64]u8 = undefined;
const ev = nextEvent(random, &buf, aim, looks, &cl.script);
cl.loop.input(ev);
cl.left -= 1;
if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else {
typing -= 1;
// The first leaves once it is done.
if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} });
}
},
.to_replica => cl.loop.take(.{ .unit = try gpa.dupe(u8, m.bytes) }),
.screen_down => {
const pane = m.bytes[0];
const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0;
cl.loop.take(.{ .screen = try gpa.dupe(u8, m.bytes) });
if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| {
const now_seq = replicaOf(sc.rep).seq;
if (now_seq == was) totals.resets += 1 else {
// Applied: the screen is the authority's at that version.
totals.screens_checked += 1;
const want = versions.get(@as(u64, sc.serial) << 32 | now_seq);
const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt;
if (want == null or want.? != screenHash(vt)) {
totals.screens_wrong += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, now_seq });
}
// Deltas while the flood runs (an RTT/2 behind it).
if (m.at >= flood_at + net.one_way and (flood_end == 0 or m.at <= flood_end + net.one_way)) flood_deltas[c] += 1;
}
};
},
.checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }),
.wake => {
// One the next replaced is no wake.
if (m.at != cl.wake_at) continue;
cl.wake_at = 0;
},
.quit => cl.loop.link.quit = true,
.gone => {
cl.loop.link.quit = true;
cl.loop.link.gone = true;
},
else => unreachable,
}
try woke(cl, c, &net, m.at, totals, r);
if (cl.loop.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing);
},
.client_frame => {},
}
}
totals.flood_us += flood_end -| flood_at;
for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d;
const want = replica.digestOf(a);
for (clients[0..r.clients], 1..) |*cl, id| {
totals.resizes += cl.resizes;
totals.wakes += cl.wakes;
for (&totals.asked, cl.asked) |*t, n| t.* += n;
if (has_link[id - 1]) totals.draws += cl.loop.link.draws;
// Its quiet checks: what the session's digest was against its own.
if (readAll(cl.check)) |said| {
defer gpa.free(said);
var lines = std.mem.tokenizeScalar(u8, said, '\n');
while (lines.next()) |line| if (std.mem.startsWith(u8, line, "agree")) {
totals.agree += 1;
} else {
totals.differ += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s quiet check: {s}\n", .{ r.seed, r.rtt_ms, id, line });
};
}
const rp = cl.r orelse continue;
try totals.add(&rp.stats);
if (cl.live == 0) continue;
if (rp.diverged) |why| {
totals.divergences += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ r.seed, r.rtt_ms, id, why });
} else if (!rp.quiet() or rp.digest() != want) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ r.seed, r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" });
}
// At quiescence, every terminal the authority's, cell for cell.
for (a.core.panes, 0..) |slot, pid| {
const pane = slot orelse continue;
const state = pane.terminal orelse continue;
const mine = (rp.core().panes[pid] orelse {
totals.unequal += 1;
continue;
}).terminal orelse continue;
if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid });
}
}
// ...and every file's text the authority's, byte for byte: a digest
// takes a text of 4 KiB and up by its length (core/walk.zig).
for (a.core.panes, 0..) |slot, pid| {
const f = (slot orelse continue).file orelse continue;
const mine = if (rp.core().panes[pid]) |pane| pane.file else null;
if (mine == null or !std.mem.eql(u8, f.content, mine.?.content)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid });
}
}
}
}
/// A typist: keys 50-200 ms apart, a pause now and then.
fn typistGap(random: std.Random) u64 {
return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000);
}
/// A file's bytes, or null.
fn readAll(path: [:0]const u8) ?[]u8 {
const fd = libc.open(path, .{ .ACCMODE = .RDONLY });
if (fd < 0) return null;
defer _ = libc.close(fd);
var out: std.ArrayListUnmanaged(u8) = .empty;
var buf: [4096]u8 = undefined;
while (true) {
const k = libc.read(fd, &buf, buf.len);
if (k <= 0) break;
out.appendSlice(gpa, buf[0..@intCast(k)]) catch return null;
}
return out.toOwnedSlice(gpa) catch null;
}
/// A .patch looked at opens a +Diff, whose rows are made from files read
/// in the step (hunks.zig: the patch, the file each section names, its
/// declarations). Looked at by the authority, a replica replays the reads
/// the unit carries and makes the same +Diff; looked at as the replica's own
/// input, the first read poisons the speculation, which shows nothing and
/// waits for the authority's unit (no rollback of what it showed). Either
/// way the replica's digest and the +Diff's text are the authority's.
fn diffCase(dir: []const u8) !bool {
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var buf: [256]u8 = undefined;
const source = try std.fmt.bufPrintSentinel(&buf, "{s}/a.zig", .{dir}, 0);
try writeText(source, "// one\n// two\nconst S = struct {\n fn f() void {\n a();\n b();\n log();\n }\n};\n");
var pbuf: [256]u8 = undefined;
const patch = try std.fmt.bufPrintSentinel(&pbuf, "{s}/change.patch", .{dir}, 0);
try writeText(patch, "--- a.zig\n+++ a.zig\n@@ -3,4 +3,5 @@\n fn f() void {\n- c();\n+ a();\n b();\n+ log();\n }\n");
var lbuf: [300]u8 = undefined;
const look = try std.fmt.bufPrint(&lbuf, "Look {s}", .{patch});
var ok = true;
for ([_]bool{ false, true }) |own| {
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
if (own) {
const msg = try gpa.dupe(u8, try rp.input(.{ .command = look }));
defer gpa.free(msg);
if (rp.stats.stopped != 1) {
std.debug.print("diff: the replica's own look at a .patch was not stopped at its first read ({d} stopped, {d} applied)\n", .{ rp.stats.stopped, rp.stats.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
} else rp.confirm(try a.local(.{ .command = look }));
rp.settle();
const named = for (a.core.panes, 0..) |slot, pid| {
const f = (slot orelse continue).file orelse continue;
if (std.mem.endsWith(u8, f.path, "/+Diff")) break pid;
} else null;
const mine = if (named) |pid| if (rp.core().panes[pid]) |pane| pane.file else null else null;
if (named == null or mine == null or !std.mem.eql(u8, a.core.panes[named.?].?.file.?.content, mine.?.content) or
std.mem.indexOf(u8, mine.?.content, "a.zig:5 *") == null)
{
std.debug.print("diff: {s}: the replica holds no +Diff of the authority's\n", .{if (own) "its own look" else "the authority's look"});
ok = false;
}
if (rp.diverged) |why| {
std.debug.print("diff: {s}: the replica diverged: {s}\n", .{ if (own) "its own look" else "the authority's look", why });
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("diff: {s}: the replica's digest is not the authority's\n", .{if (own) "its own look" else "the authority's look"});
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("diff: {s}: {d} rollbacks\n", .{ if (own) "its own look" else "the authority's look", rp.stats.mispredicted + rp.stats.foreign });
ok = false;
}
}
std.debug.print("diff: a .patch looked at by the authority and as a replica's own input: {s}\n", .{if (ok) "the same +Diff" else "FAILED"});
return ok;
}
/// Looks the plumber takes (core/plumbing), each as the authority's input
/// and as a replica's own: a URL (its web port: no disk asked, so a
/// replica's own look speculates whole and is confirmed with no rollback),
/// and a commit hash in a git work tree (Diff's `git show`, its `.git`
/// asked at a read the unit carries). The replica's digest is the
/// authority's either way.
fn plumbCase(dir: []const u8) !bool {
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var gbuf: [256]u8 = undefined;
try std.Io.Dir.createDirAbsolute(std.Io.Threaded.global_single_threaded.io(), try std.fmt.bufPrint(&gbuf, "{s}/.git", .{dir}), .default_dir);
var nbuf: [256]u8 = undefined;
const notes = try std.fmt.bufPrintSentinel(&nbuf, "{s}/notes.txt", .{dir}, 0);
try writeText(notes, "fixed in 3f2a9c1, see https://ziglang.org\n");
var obuf: [300]u8 = undefined;
const open = try std.fmt.bufPrint(&obuf, "Look {s}", .{notes});
var ok = true;
for ([_][]const u8{ "Look https://ziglang.org", "Look 3f2a9c1" }) |look| for ([_]bool{ false, true }) |own| {
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
rp.confirm(try a.local(.{ .command = open }));
rp.settle();
const before = rp.stats;
const url = std.mem.indexOf(u8, look, "://") != null;
if (own) {
const msg = try gpa.dupe(u8, try rp.input(.{ .command = look }));
defer gpa.free(msg);
if (url and (rp.stats.stopped != before.stopped or rp.stats.speculated == before.speculated)) {
std.debug.print("plumb: {s}: the replica's own look did not speculate whole ({d} stopped, {d} applied)\n", .{ look, rp.stats.stopped, rp.stats.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
} else rp.confirm(try a.local(.{ .command = look }));
rp.settle();
const who = if (own) "its own look" else "the authority's look";
if (!url) {
const paged = for (a.core.panes) |slot| {
if ((slot orelse continue).command_pages) break true;
} else false;
if (!paged) {
std.debug.print("plumb: {s}: {s}: no git show paged\n", .{ look, who });
ok = false;
}
}
if (rp.diverged) |why| {
std.debug.print("plumb: {s}: {s}: the replica diverged: {s}\n", .{ look, who, why });
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("plumb: {s}: {s}: the replica's digest is not the authority's\n", .{ look, who });
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("plumb: {s}: {s}: {d} rollbacks\n", .{ look, who, rp.stats.mispredicted + rp.stats.foreign });
ok = false;
}
};
// A rule to a port a program reads (plumb/seemail), of a URL, which a
// look reads no disk for: whether the port is read is the authority's
// 9P state, asked through the tape. A replica's own look waits for the
// first answer, then guesses the last; the second look speculates whole
// and is confirmed with no rollback.
{
// The rule from the session's plumbing file, read at boot.
var pbuf: [256]u8 = undefined;
try writeText(try std.fmt.bufPrintSentinel(&pbuf, "{s}/plumbing", .{dir}, 0), "type is text\ndata matches 'https://letters/.*'\nplumb to seemail\n\ninclude basic\n");
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
rp.confirm(try a.local(.{ .command = open }));
rp.settle();
if (pardes.Plumb.portIndex(rp.core(), "seemail") == null) {
std.debug.print("plumb: a look to a port: the plumbing file's port is not the replica's\n", .{});
ok = false;
}
for (0..2) |n| {
const before = rp.stats;
const msg = try gpa.dupe(u8, try rp.input(.{ .command = "Look https://letters/42" }));
defer gpa.free(msg);
if (n == 1 and (rp.stats.stopped != before.stopped or rp.stats.speculated == before.speculated)) {
std.debug.print("plumb: a look to a port: the replica's second look did not speculate whole ({d} stopped, {d} applied)\n", .{ rp.stats.stopped - before.stopped, rp.stats.speculated - before.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
rp.settle();
}
if (rp.diverged) |why| {
std.debug.print("plumb: a look to a port: the replica diverged: {s}\n", .{why});
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("plumb: a look to a port: the replica's digest is not the authority's\n", .{});
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("plumb: a look to a port: {d} rollbacks\n", .{rp.stats.mispredicted + rp.stats.foreign});
ok = false;
}
}
std.debug.print("plumb: a URL, a commit hash and a look to a port read by programs, by the authority and as a replica's own input: {s}\n", .{if (ok) "the same session" else "FAILED"});
return ok;
}
fn push(q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, m: Msg) !void {
var mm = m;
mm.n = nn.*;
nn.* += 1;
try q.push(gpa, mm);
}
/// What each peer is owed of the terminals, onto its link (before the
/// authority steps an input, and once a frame); each version as the
/// authority's screen showed it.
fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *std.ArrayListUnmanaged([]u8), q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, now: u64, dl: []Link, rnd: std.Random, ow: u64, jt: u64, vs: *std.AutoHashMapUnmanaged(u64, u64), tot: *Totals) !void {
for (ps, 0..) |peer, c| {
list.clearRetainingCapacity();
// Terminals alone cross: the view is not read.
try sc.flush(core, peer, 0, list);
for (list.items) |bytes| {
tot.deltas += 1;
tot.delta_bytes += bytes.len;
try push(q, nn, .{ .at = dl[c].arrive(rnd, now, ow, jt), .n = 0, .kind = .screen_down, .who = @intCast(c + 1), .bytes = bytes });
}
}
// Each version as the authority's screen showed it.
for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| {
const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version;
if (trackOf(tr.track).version == 0 or vs.contains(key)) continue;
_ = core.panes[id] orelse continue;
try vs.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt));
};
}
/// A unit of the authority's to every replica, down its link: first the
/// rows of its terminals its step read that a replica holds as holes.
fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void {
var rows: std.ArrayListUnmanaged([]u8) = .empty;
defer rows.deinit(gpa);
for (down, peers, 1..) |*l, peer, who| {
rows.clearRetainingCapacity();
try screens.fill(core, peer, &rows);
for (rows.items) |bytes| {
totals.filled_bytes += bytes.len;
try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes });
n.* += 1;
}
}
screens.filled(core);
// The sizes its steps gave terminals, after their rows (Peers.unit).
pardes.panes.resizeDeferred(core);
totals.unit_bytes += unit.len * down.len;
if (flooding) totals.flood_unit_bytes += unit.len * down.len;
for (down, 1..) |*l, who| {
try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .to_replica, .who = @intCast(who), .bytes = try gpa.dupe(u8, unit) });
n.* += 1;
}
}
// ---- predicted echo (--echo): one client typing a corpus into a shell ----
//
// The authority's pty is a shell played here (`FakeShell`): a line editor at
// a prompt with pardes's OSC 133 marks and Tab completion, and the programs
// the corpus runs in it: a password prompt (no echo), vim (the alternate
// screen), a program that ignores what is typed, and `cat` (the kernel's
// plain echo, no marks). Each key's echo comes back 2 ms after the authority
// writes it, as a shell's. The client types at a typist's pace and in bursts;
// each of its frames (60 Hz, a phase of its own) is what its screen shows:
// the predicted echo where it is drawn (core/term/echo.zig), the screen state
// under it. Per key the shell echoed at a prompt or in cat: the time from
// the key to its character on that screen, with prediction and without. Per
// key predicted: whether the authority's screen, right after its echo,
// shows what was predicted where it was. Per key drawn wrong: its frames.
const ascii: [128][1]u8 = blk: {
var t: [128][1]u8 = undefined;
for (&t, 0..) |*c, i| c.* = .{@intCast(i)};
break :blk t;
};
const Step = struct { gap: u64, key: Key, section: u8 };
/// The corpus's parts, each a case of the gates.
const sections = [_][]const u8{ "typing", "a burst", "backspace", "left, right", "tab", "password", "vim", "ignores input", "cat", "typed ahead" };
const Corpus = struct {
steps: std.ArrayListUnmanaged(Step) = .empty,
random: std.Random,
extra: u64 = 0,
section: u8 = 0,
fn add(c: *Corpus, gap: u64, key: Key) !void {
try c.steps.append(gpa, .{ .gap = gap + c.extra, .key = key, .section = c.section });
c.extra = 0;
}
fn typing(c: *Corpus, text: []const u8, fast: bool) !void {
for (text) |ch| try c.add(if (fast) c.random.intRangeAtMost(u64, 12_000, 60_000) else c.random.intRangeAtMost(u64, 60_000, 180_000), .{ .cp = ch, .text = &ascii[ch] });
}
fn press(c: *Corpus, key: Key) !void {
try c.add(c.random.intRangeAtMost(u64, 80_000, 250_000), key);
}
fn pause(c: *Corpus) void {
c.extra += c.random.intRangeAtMost(u64, 500_000, 1_200_000);
}
fn build(c: *Corpus) !void {
const enter: Key = .{ .cp = Key.enter };
const bs: Key = .{ .cp = Key.backspace };
c.pause();
// At a prompt, at a typist's pace, then in a burst.
c.section = 0;
try c.typing("echo hello world", false);
try c.press(enter);
c.pause();
c.section = 1;
try c.typing("echo the quick brown fox jumps over", true);
try c.press(enter);
c.pause();
// Backspace.
c.section = 2;
try c.typing("ecoh", false);
try c.press(bs);
try c.press(bs);
try c.typing("ho fixed tpyo", false);
for (0..3) |_| try c.press(bs);
try c.typing("ypo", false);
try c.press(enter);
c.pause();
// Left and right over what was typed.
c.section = 3;
try c.typing("echo abc", false);
for ([_]u21{ Key.left, Key.left, Key.right, Key.right }) |k| try c.press(.{ .cp = k });
try c.typing("def", false);
try c.press(enter);
c.pause();
// Tab completion, typed straight on.
c.section = 4;
try c.typing("ec", false);
try c.press(.{ .cp = Key.tab });
try c.typing("tab completed", false);
try c.press(enter);
c.pause();
// A password prompt: nothing typed there may show.
c.section = 5;
try c.typing("sudo ls", false);
try c.press(enter);
c.pause();
try c.typing("hunter2", false);
try c.press(enter);
c.pause();
// vim: the alternate screen, never predicted.
c.section = 6;
try c.typing("vim", false);
try c.press(enter);
c.pause();
try c.typing("ihello from vim", false);
try c.press(.{ .cp = Key.escape, .shift = true });
try c.typing(":q", false);
try c.press(enter);
c.pause();
// A program that ignores what is typed.
c.section = 7;
try c.typing("sink", false);
try c.press(enter);
c.pause();
try c.typing("this goes nowhere", false);
try c.press(.{ .cp = 'c', .ctrl = true });
c.pause();
// cat: the kernel's plain echo.
c.section = 8;
try c.typing("cat", false);
try c.press(enter);
c.pause();
try c.typing("plain echo", false);
try c.press(enter);
try c.typing("a second line", false);
try c.press(enter);
try c.press(.{ .cp = 'd', .ctrl = true });
c.pause();
// Typed on before the next prompt.
c.section = 9;
try c.typing("echo one", false);
try c.press(enter);
try c.typing("echo two", false);
try c.press(enter);
c.pause();
}
};
const prompt_bytes = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
/// The shell on the authority's pty, a key a write (as forwardKey writes).
const FakeShell = struct {
mode: Mode = .prompt,
line: [256]u8 = undefined,
len: usize = 0,
cur: usize = 0,
vim_cmd: [8]u8 = undefined,
vim_n: usize = 0,
out: std.ArrayListUnmanaged(u8) = .empty,
const Mode = enum { prompt, password, vim, vim_insert, sink, cat };
fn put(sh: *FakeShell, bytes: []const u8) void {
sh.out.appendSlice(gpa, bytes) catch {};
}
fn print(sh: *FakeShell, comptime fmt: []const u8, args: anytype) void {
sh.out.print(gpa, fmt, args) catch {};
}
fn done(sh: *FakeShell, status: u8) void {
sh.print("\x1b]133;D;{d};aid=pardes\x07" ++ prompt_bytes, .{status});
sh.mode = .prompt;
sh.len = 0;
sh.cur = 0;
}
fn insert(sh: *FakeShell, c: u8) void {
if (sh.len + 1 >= 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, _: u8, 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 version of the screen before that.
mode: ?FakeShell.Mode = null,
echoed: bool = false,
version_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 screen state 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,
screens_wrong: 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(), true);
defer a.deinit();
var screens: replica.Screens = .init(gpa);
defer screens.deinit(a.core);
const peer = try screens.addPeer();
const peers = [_]u16{peer};
const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0), true);
defer rp.deinit();
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);
t.apply_ns.deinit(gpa);
t.frame_ns.deinit(gpa);
}
var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty;
defer versions.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(.{});
var owed: std.ArrayListUnmanaged([]u8) = .empty;
defer owed.deinit(gpa);
// The shell's first prompt.
sh.put(prompt_bytes);
a.output(.{ .output = .{ .pane = 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, &t, false, &screens, a.core, &peers);
try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t);
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, &t, false, &screens, a.core, &peers);
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.version_before = if (screens.tracks[shell]) |*tr| trackOf(tr.track).version else 0;
}
sh.key(m.bytes);
if (sh.out.items.len > 0) {
a.output(.{ .output = .{ .pane = 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, &t, false, &screens, a.core, &peers);
try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t);
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 });
}
}
};
const applied = if (rp.screens[shell]) |sc| replicaOf(sc.rep).seq else 0;
for (typed.items) |*k| if (k.echoed and k.seen == null and applied > k.version_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();
},
.screen_down => {
if (rp.screen(m.bytes)) |reply| {
const pane = m.bytes[0];
if (reply[5] == 1) {
const sc = rp.screens[pane].?;
if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| {
if (want != screenHash(&pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt)) t.screens_wrong += 1;
} else t.screens_wrong += 1;
}
try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, reply) });
}
if (rp.screenRequest()) |req| try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, req) });
},
.screen_up => {
if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer });
},
.output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw => {},
}
}
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;
et.screens_wrong += t.screens_wrong;
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 screens-wrong\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} {d:>13}\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, et.screens_wrong,
});
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.screens_wrong > 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 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)];
}
/// `--screen-state `: every recorded pty stream in `dir` (a
/// `-x` in its name sizes it, 80x24 otherwise) through
/// screen_state's soak at three seeds, then the encode's cost and the bytes
/// floods put on the wire (numbers from a ReleaseFast build).
fn screenState(io: std.Io, dir_path: []const u8, w: *std.Io.Writer) !void {
var dir = try std.Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true });
defer dir.close(io);
var it = dir.iterate();
var files: usize = 0;
var failed: usize = 0;
while (try it.next(io)) |entry| {
if (entry.kind != .file) continue;
const bytes = try dir.readFileAlloc(io, entry.name, gpa, .unlimited);
defer gpa.free(bytes);
var cols: u16 = 80;
var rows: u16 = 24;
if (std.mem.lastIndexOfScalar(u8, entry.name, '-')) |dash| {
const size = std.mem.sliceTo(entry.name[dash + 1 ..], '.');
if (std.mem.indexOfScalar(u8, size, 'x')) |x| {
cols = std.fmt.parseInt(u16, size[0..x], 10) catch cols;
rows = std.fmt.parseInt(u16, size[x + 1 ..], 10) catch rows;
}
}
files += 1;
for (0..3) |seed| {
const st = screen_state.soak(gpa, io, bytes, cols, rows, 128 * 1024, seed, seed != 0) catch |err| {
try w.print("screen-state {s} seed {d}: {s}\n", .{ entry.name, seed, @errorName(err) });
failed += 1;
continue;
};
if (seed == 0) try w.print("screen-state {s} {d}x{d}: {d} bytes, {d} deltas ({d} lost, {d} refused, {d} in flight at most), {d} wire bytes, {d} history rows checked, {d} fetched\n", .{ entry.name, cols, rows, bytes.len, st.deltas, st.lost, st.refused, st.most_in_flight, st.bytes, st.history_checked, st.fetched });
}
}
try w.print("screen-state corpus: {d} streams x 3 seeds, {d} failed\n", .{ files, failed });
try w.flush();
try encodeBench(io, w);
}
fn encodeBench(io: std.Io, w: *std.Io.Writer) !void {
const t = try gpa.create(screen_state.Terminal);
defer gpa.destroy(t);
t.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 });
defer t.deinit(gpa);
var stream = t.vtStream();
defer stream.deinit();
var enc: screen_state.Encoder = .init(gpa);
defer enc.deinit();
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
var line: [1024]u8 = undefined;
// A full 200x60 screen, every row new to the peer: each a blob.
var full: [200]u64 = undefined;
var same: [200]u64 = undefined;
var full_bytes: usize = 0;
var same_bytes: usize = 0;
var changes: u32 = 0;
for (&full, &same, 0..) |*f, *u, rep| {
for (0..60) |y| {
var lw: std.Io.Writer = .fixed(&line);
try lw.print("\x1b[{d};1H\x1b[0;3{d};4{d}m{d} {d} ", .{ y + 1, rep % 8, y % 8, rep, y });
while (lw.end < 190) try lw.writeAll("\x1b[1mbold\x1b[22m text ");
stream.nextSlice(lw.buffered());
}
changes += 1;
var tr: screen_state.Track = .init(gpa);
defer tr.deinit(gpa, t);
var peer: screen_state.Peer = .{};
defer peer.deinit(gpa);
out.clearRetainingCapacity();
var t0 = std.Io.Clock.awake.now(io).nanoseconds;
_ = try screen_state.encode(&enc, &tr, &peer, t, changes, "", &out.writer);
f.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0);
full_bytes = out.written().len;
// The same screen again as a new version: every row held.
out.clearRetainingCapacity();
t0 = std.Io.Clock.awake.now(io).nanoseconds;
_ = try screen_state.encode(&enc, &tr, &peer, t, changes + 1, "", &out.writer);
u.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0);
same_bytes = out.written().len;
}
std.mem.sort(u64, &full, {}, std.sort.asc(u64));
std.mem.sort(u64, &same, {}, std.sort.asc(u64));
try w.print("screen-state encode 200x60, every row new: p50 {d} us p99 {d} us, {d} bytes\n", .{ full[100] / 1000, full[198] / 1000, full_bytes });
try w.print("screen-state encode 200x60, nothing new: p50 {d} us p99 {d} us, {d} bytes\n", .{ same[100] / 1000, same[198] / 1000, same_bytes });
try w.flush();
// Floods: a second of output as fast as ghostty takes it, a frame every
// 16 ms: one version, a delta for each peer (the same bytes for peers
// at the same base), each replica applying its own at once. Under the C
// allocator, as a replica's.
try floods(io, w);
}
fn floods(io: std.Io, w: *std.Io.Writer) !void {
var enc: screen_state.Encoder = .init(gpa);
defer enc.deinit();
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
const yes = try screen_state.yesStream(gpa, 1 << 16);
defer gpa.free(yes);
const shell = try screen_state.shellStream(gpa);
defer gpa.free(shell);
for ([_]struct { name: []const u8, bytes: []const u8 }{ .{ .name = "yes", .bytes = yes }, .{ .name = "varied text", .bytes = shell } }) |flood| for ([_]usize{ 1, 3 }) |npeers| {
const a = try gpa.create(screen_state.Terminal);
defer gpa.destroy(a);
a.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 });
defer a.deinit(gpa);
var as = a.vtStream();
defer as.deinit();
var tr: screen_state.Track = .init(gpa);
defer tr.deinit(gpa, a);
var peers: [3]screen_state.Peer = @splat(.{});
var reps: [3]screen_state.Replica = @splat(.{});
var bs: [3]screen_state.Terminal = undefined;
for (bs[0..npeers]) |*b| b.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 32 << 20 });
defer for (bs[0..npeers], reps[0..npeers], peers[0..npeers]) |*b, *r, *peer| {
b.deinit(gpa);
r.deinit(gpa);
peer.deinit(gpa);
};
var applies: std.ArrayList(u64) = .empty;
defer applies.deinit(gpa);
var frames: std.ArrayList(u64) = .empty;
defer frames.deinit(gpa);
const start = std.Io.Clock.awake.now(io).nanoseconds;
var next = start;
var fed: u64 = 0;
var deltas: u64 = 0;
var wire: u64 = 0;
var version: u32 = 0;
while (true) {
const now = std.Io.Clock.awake.now(io).nanoseconds;
if (now - start >= std.time.ns_per_s) break;
as.nextSlice(flood.bytes);
version += 1;
fed += flood.bytes.len;
if (now < next) continue;
next += 16 * std.time.ns_per_ms;
var frame_ns: u64 = 0;
for (peers[0..npeers], reps[0..npeers], bs[0..npeers]) |*peer, *rep, *b| {
out.clearRetainingCapacity();
const e0 = std.Io.Clock.awake.now(io).nanoseconds;
if (!try screen_state.encode(&enc, &tr, peer, a, version, "", &out.writer)) continue;
frame_ns += @intCast(std.Io.Clock.awake.now(io).nanoseconds - e0);
const a0 = std.Io.Clock.awake.now(io).nanoseconds;
peer.ack((try rep.apply(gpa, io, b, out.written())).seq);
try applies.append(gpa, @intCast(std.Io.Clock.awake.now(io).nanoseconds - a0));
deltas += 1;
wire += out.written().len;
}
try frames.append(gpa, frame_ns);
}
std.mem.sort(u64, applies.items, {}, std.sort.asc(u64));
std.mem.sort(u64, frames.items, {}, std.sort.asc(u64));
const p = struct {
fn at(s: []const u64, q: usize) u64 {
return if (s.len == 0) 0 else s[@min(s.len - 1, s.len * q / 100)] / 1000;
}
}.at;
try w.print("screen-state flood of {s}, {d} peer(s): {d} MB/s of output, {d} deltas/s a peer, {d} wire bytes/s a peer ({d} a delta); encode a frame, all peers: p50 {d} us p99 {d} us; apply a delta p50 {d} us p99 {d} us\n", .{
flood.name, npeers, fed / 1_000_000, deltas / npeers, wire / npeers,
wire / @max(1, deltas), p(frames.items, 50), p(frames.items, 99), p(applies.items, 50),
p(applies.items, 99),
});
};
try w.flush();
}
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
var seeds: u64 = 4;
var first: u64 = 0;
var steps: usize = 120;
var clients: u16 = 5;
var rtts: []const u64 = &.{ 30, 80, 207 };
var echo_mode = false;
var flood_mb: u64 = 8;
var screen_dir: ?[]const u8 = null;
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 (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, "--screen-state")) screen_dir = value 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;
}
if (screen_dir) |d| {
var buf: [4096]u8 = undefined;
var out = std.Io.File.stderr().writer(init.io, &buf);
return screenState(init.io, d, &out.interface);
}
trace = libc.getenv("PARDES_REPLICA_TRACE") != null;
if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff;
var dir_buf: [256]u8 = undefined;
const tmp = std.mem.span(libc.getenv("TMPDIR") orelse "/tmp");
const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) });
try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir);
defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {};
// 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;
std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us });
std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{});
var term_lines: std.ArrayList(u8) = .empty;
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);
for (rtts) |rtt| {
var t: Totals = .{};
for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t);
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:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>9} {d:>6} {d:>6}/{d:<6}\n", .{
rtt,
@as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)),
@as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
@as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
pct(t.frame_ns.items, 50) / 1000,
pct(t.frame_ns.items, 99) / 1000,
pct(t.apply_ns.items, 50) / 1000,
pct(t.apply_ns.items, 99) / 1000,
t.fetched,
t.filled_bytes / 1024,
t.resets,
t.screens_checked,
t.screens_wrong,
});
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] });
if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true;
}
std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{});
std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items});
std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (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});
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;
for (a.cells.items, b.cells.items, 0..) |x, y, i| if (!std.meta.eql(x, 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(), true);
defer a.deinit();
const b = try replica.Authority.init(gpa, options, noop.host(), true);
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;
}