summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-19 08:10:53 -0300
committerGabriel Schneider <[email protected]>2026-11-19 11:40:11 -0300
commit3f0261245d69e015d4caea0432aefa97747d02ad (patch)
tree602c3c21858cef0c2a9c97530c7782931cc9f612
parentd2f854de898cb84776e9f56ece0ec9e9c548e27d (diff)
downloadpardes-3f0261245d69e015d4caea0432aefa97747d02ad.tar.gz
pardes-3f0261245d69e015d4caea0432aefa97747d02ad.zip
replicas: the soak runs THE client loop, the one the terminal and the window run (the reorganisation's runners, step 10b, its second part; the user's rule: replica bugs caught by a soak that does what real use does, twice hidden by a hand-written imitation): each client of test/replicas.zig is runtime/client.zig's Loop over a frontend of the soak's own (a terminal's or a window's by turns: it draws no pixels but counts its frames and keeps the facts a window reads; a window's size posted from its own pass; a terminal holds a key already one pass in four, so no copy then; its wait is the delayed link's next message, a wake it asks for one timer at a time on the soak's clock), driven as a loop woken from outside (Loop.pass up to its wait, Loop.woken after what woke it), so its mirrors of the two loops are deleted (Client.draw, own, within, pass, and the quiet check imitated on the soak's clock: the link's own quietCheck now runs, its clock the soak's through Link.now as Echo.now is); its host has every entry (replica.everyEntry, which 12b's FullHost is now too: pty_resize, watch_file, watch_theme, open_link, pipe, search and the rest do nothing unless the soak's), and an input whose stop's name replica.may_wait does not list fails the run, said with its input (replica.mayWait; the soak's random inputs cannot be named as the walk names them, so by the name alone): the soak found seven names the list did not have, all a far client's by design, now rows with why (Search's rows, a session worker's: `search`; a +Preview's file, the session's disk: `preview`; a kind whose state is its own on the session, a PDF's, its search, a place in it, its word, its open and its close: five rows on a new pane kind `addon`, which the walk does not stand in and never judges stale); the stops by name, the wakes asked and the frames drawn are a line per rtt; the leftovers go (Stats.unspeculated and its column, Proc with enter and current: the distrusted list is the client's, the stale comment about config.tab_now); and a new check, the frame corpus through a client (corpusCase): the corpus's scenes (a wheel, a click, a jump, TaglineSize, a markdown file, three columns, a dirty pane, InactiveDim, WindowOpacity, ligatures, Zerox, a resize) typed into a session's own view drawn by its own pump and, the same, through the client loop into a client's view of a second session of the same files, the session's unit back at once; after each, the two frames a frontend draws from (cells, cursor, chrome, regions, the facts beside them, the placements) are the same: 22 scenes, 25 frames own and 24 through the client, every one the same. Gate: the soak on the shared loop (--clients 5, 4 seeds) diverged 0, unequal 0, deltas wrong 0, quiet checks 489/0, 556/0, 700/0, mispredicted 32/36/43, stopped 87/43/81 of 1784/1806/1977 at rtt 30/80/207 (pty_write 54/9/47, the kinds' 20/19/20, resolve 6/8/4, search 2/4/4, the authority's own state 3/2/3, close a terminal 0/0/3, kind 1/0/0, detach 1/1/0), unlisted 0, 216 s (the base's 230 s); tui core-test 836/979 (143 skipped), shell-test 1014/1017, term-test 15/15, pane-test 183/184, kitty-test 45/45, behaviour-test 275/275 and --replay 275/275, process-test 2 of 144 failed (lspcomplete and lspcompletemoved, the base's); gui unit-test 1612/1616 with the base's BaselineHarnessMismatch; daemon.py plain, --far, --games, --window-clients, --upgrade from pardes-tree's pfx-base to this and back; the macOS library for Linux and aarch64-macos and the FreeBSD tui configure; rollback-bench runs; gate-w run3-2 against tree1: frames 77/77 byte-identical in Debug, the alternated windows' pictures identical in all 10 runs, corpus2x -0.055% (PASS), perfops 97 counts within 0.1% (largest image-frame on large +0.031%); its unit-test 1608/1616: the gate was started in the background (`&`), so SIGINT was ignored down to its test shells and the four host_io tests whose Ctrl-C must end a foreground job failed; the same unit-test run detached but not so (setsid, no terminal) 1612/1616 with the base's BaselineHarnessMismatch only
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--build.zig1
-rw-r--r--build/tests.zig4
-rw-r--r--core/replica.zig134
-rw-r--r--runtime/client.zig20
-rw-r--r--test/replicas.zig578
5 files changed, 514 insertions, 223 deletions
diff --git a/build.zig b/build.zig
index a97933c7..b81390c4 100644
--- a/build.zig
+++ b/build.zig
@@ -330,6 +330,7 @@ pub fn build(b: *std.Build) void {
.root_set = root_set,
.core_wire = core_set.wire,
.core_module = core_module,
+ .core_runtime = core_set.runtime,
.core_cfg = core_cfg,
.exe = exe,
.ghostty_vt_for_tests = a.ghostty_vt,
diff --git a/build/tests.zig b/build/tests.zig
index fe9e1355..50d3dd02 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -16,6 +16,8 @@ pub fn add(b: *std.Build, c: struct {
/// The wire (abi/wire.zig) on the core's configuration: shell-test's.
core_wire: *std.Build.Module,
core_module: *std.Build.Module,
+ /// The runtime beside core_module: the client loop the soak runs.
+ core_runtime: *std.Build.Module,
/// core_module's configuration, for the test roots that run on its imports.
core_cfg: core.Core,
exe: *std.Build.Step.Compile,
@@ -146,7 +148,7 @@ pub fn add(b: *std.Build, c: struct {
// The replicas' soak, its clients showing a picture, a game of life and
// a PDF (docs/design.pdf) from these libraries, as a user's addons are
// loaded.
- const replicas = program(b, "pardes-replicas", "test/replicas.zig", c.target, c.optimize, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "term", .module = c.parts.term } });
+ const replicas = program(b, "pardes-replicas", "test/replicas.zig", c.target, c.optimize, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "runtime", .module = c.core_runtime }, .{ .name = "term", .module = c.parts.term } });
const run_replicas = b.addRunArtifact(replicas);
for ([_]?*std.Build.Step.Compile{ c.image_addon, life_lib, c.pdf_addon }) |l| if (l) |lib| {
run_replicas.addArg("--addon");
diff --git a/core/replica.zig b/core/replica.zig
index 31a06214..92e49df5 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -562,8 +562,6 @@ pub const Stats = struct {
speculated: u32 = 0,
/// Stopped at a host call, a syscall or an emulator: waits one RTT.
stopped: u32 = 0,
- /// Not tried: an event of the view's (a resize, the pointer), phase 4's.
- unspeculated: u32 = 0,
/// The authority's unit was the pending head, recorded the same.
fast: u32 = 0,
/// The copy put back: the head recorded otherwise (a guess of the clock
@@ -3008,6 +3006,9 @@ pub const Link = struct {
/// waits a while after each).
input_ns: u64 = 0,
asked_ns: u64 = 0,
+ /// The clock those read, when not the machine's: a simulation's (the
+ /// soak's, test/replicas.zig), as `Echo.now` is.
+ now: ?u64 = null,
/// How many of its own inputs the session recorded otherwise when it
/// last drew: a frame after one that draws something is a rollback that
/// may have been seen (counted so: an upper bound, the frame shows the
@@ -3035,6 +3036,10 @@ pub const Link = struct {
draws: u32 = 0,
again: u32 = 0,
+ fn time(c: *const Link) u64 {
+ return c.now orelse nowNs();
+ }
+
/// The test knobs the environment sets (PARDES_REPLICA_CHECK,
/// PARDES_TEST_DIVERGE).
pub fn fromEnv(c: *Link, gpa: Allocator, env: *const std.process.Environ.Map) !void {
@@ -3079,7 +3084,7 @@ pub const Link = struct {
pub fn input(c: *Link, ev: pardes.Event) void {
// Its notice read: a key of its own puts it away.
if (c.notice_len > 0 and (ev == .key or ev == .paste)) c.notice_len = 0;
- c.input_ns = nowNs();
+ c.input_ns = c.time();
const msg = c.r.input(ev) catch return;
if (!sendInput(c.fd, msg)) c.cut();
c.dirty = true;
@@ -3155,12 +3160,12 @@ pub const Link = struct {
pub fn quietCheck(c: *Link) ?u32 {
if (!c.changed or c.asked or !c.r.quiet()) return null;
const quiet_ns = 300 * std.time.ns_per_ms;
- const since = nowNs() -| @max(c.input_ns, c.asked_ns);
+ const since = c.time() -| @max(c.input_ns, c.asked_ns);
if (since < quiet_ns) return @intCast((quiet_ns - since) / std.time.ns_per_ms + 1);
c.changed = false;
c.asked = askCheck(c.fd);
if (!c.asked) c.cut();
- c.asked_ns = nowNs();
+ c.asked_ns = c.time();
return null;
}
@@ -5247,7 +5252,10 @@ test "a client's n in a kind's pane is a motion: it steps to the next place a re
/// The kinds of pane the walk below stands in: a file's, a plain kind's,
/// a shell's raw (its program has the keys) and a shell's in normal mode
/// (pardes's own keys over its history). `any` is a row's for all four.
-const On = enum { any, file, kind, shell, shell_normal };
+/// `addon`: a kind whose state is its own on the session (a PDF's), which
+/// the walk does not stand in (its Still has no search, place or word):
+/// the soak's (test/replicas.zig) PDF and pictures are, judged by name.
+const On = enum { any, file, kind, shell, shell_normal, addon };
/// What a far client may wait a round trip for (the user's line, P14: a
/// side effect on the system may be slow; motions, edits and layout are
@@ -5299,12 +5307,31 @@ const may_wait = [_]Wait{
.{ .what = "DumpConfig", .on = .any, .stop = "the authority's own state", .why = "the config file written" },
.{ .what = "ThemeFile *", .on = .any, .stop = "the authority's own state", .why = "a theme file, the session's" },
.{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" },
+ // A search's rows: the session's worker or its loop writes them, and
+ // whether it has a worker is not the client's to know (12a); a
+ // +Preview's text is read from the session's disk.
+ .{ .what = "Search *", .on = .any, .stop = "search", .why = "a search's rows, the session's worker's" },
+ .{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" },
+ // A kind's own state on the session (a PDF's document): asking it.
+ .{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" },
+ .{ .what = "*", .on = .addon, .stop = "a kind's address", .why = "a place in a kind's pane (`Look doc.pdf:3`): its own state" },
+ .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" },
+ .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" },
+ .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" },
} ++ (if (pardes.platform == .gui) [_]Wait{
// A window's view (the font words are a window's).
.{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
.{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
} else [_]Wait{});
+/// Whether a stop of that name (`Tape.poisoned_by`) is one `may_wait`
+/// lists for something: the soak's (test/replicas.zig) judge of its
+/// clients' inputs, which it cannot name as the walk does.
+pub fn mayWait(stop: []const u8) bool {
+ for (may_wait) |row| if (std.mem.eql(u8, row.stop, stop)) return true;
+ return false;
+}
+
/// The keys the walk types: every printable one, and the specials a
/// frontend reads; each plain, with Ctrl and with Alt.
const walk_keys = keys: {
@@ -5374,53 +5401,58 @@ fn keyName(buf: []u8, k: pardes.Key) []const u8 {
return std.fmt.bufPrint(buf, "{s}{u}", .{ mod, k.cp }) catch unreachable;
}
-/// A session's host with every entry a step may ask, each doing nothing:
-/// a client's step stops, or goes on, as against a real session's (a
-/// client's tape offers only the entries its session's host has). The
-/// loop's own (`now`, `wait_input`, the frame's) no step asks.
-const FullHost = struct {
- fn Noop(comptime F: type) type {
- const info = @typeInfo(@typeInfo(@typeInfo(F).optional.child).pointer.child).@"fn";
- const R = info.return_type.?;
- const P = info.param_types;
- return switch (P.len) {
- 1 => struct {
- fn f(_: ?*anyopaque) R {
- return std.mem.zeroes(R);
- }
- },
- 2 => struct {
- fn f(_: ?*anyopaque, _: P[1].?) R {
- return std.mem.zeroes(R);
- }
- },
- 3 => struct {
- fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?) R {
- return std.mem.zeroes(R);
- }
- },
- 4 => struct {
- fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?) R {
- return std.mem.zeroes(R);
- }
- },
- 5 => struct {
- fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?, _: P[4].?) R {
- return std.mem.zeroes(R);
- }
- },
- else => @compileError("a host entry of more arguments"),
- };
- }
- const vtable = table: {
- var v: pardes.Host.VTable = .{};
- for (@typeInfo(pardes.Host.VTable).@"struct".field_names) |name| {
- if (std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "wait_input") or std.mem.eql(u8, name, "present") or
- std.mem.eql(u8, name, "post_present") or std.mem.eql(u8, name, "poll_frame")) continue;
- @field(v, name) = &Noop(@FieldType(pardes.Host.VTable, name)).f;
+/// `v` with every entry a step may ask that it leaves out doing nothing
+/// (answering zero): a client's step stops, or goes on, as against a real
+/// session's (a client's tape offers only the entries its session's host
+/// has). The loop's own (`now`, `wait_input`, the frame's) no step asks.
+pub fn everyEntry(comptime v: pardes.Host.VTable) pardes.Host.VTable {
+ const Noop = struct {
+ fn Of(comptime F: type) type {
+ const info = @typeInfo(@typeInfo(@typeInfo(F).optional.child).pointer.child).@"fn";
+ const R = info.return_type.?;
+ const P = info.param_types;
+ return switch (P.len) {
+ 1 => struct {
+ fn f(_: ?*anyopaque) R {
+ return std.mem.zeroes(R);
+ }
+ },
+ 2 => struct {
+ fn f(_: ?*anyopaque, _: P[1].?) R {
+ return std.mem.zeroes(R);
+ }
+ },
+ 3 => struct {
+ fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?) R {
+ return std.mem.zeroes(R);
+ }
+ },
+ 4 => struct {
+ fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?) R {
+ return std.mem.zeroes(R);
+ }
+ },
+ 5 => struct {
+ fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?, _: P[4].?) R {
+ return std.mem.zeroes(R);
+ }
+ },
+ else => @compileError("a host entry of more arguments"),
+ };
}
- break :table v;
};
+ var all = v;
+ for (@typeInfo(pardes.Host.VTable).@"struct".field_names) |name| {
+ if (std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "wait_input") or std.mem.eql(u8, name, "present") or
+ std.mem.eql(u8, name, "post_present") or std.mem.eql(u8, name, "poll_frame")) continue;
+ if (@field(all, name) == null) @field(all, name) = &Noop.Of(@FieldType(pardes.Host.VTable, name)).f;
+ }
+ return all;
+}
+
+/// A session's host with every entry a step may ask, each doing nothing.
+const FullHost = struct {
+ const vtable = everyEntry(.{});
fn host() pardes.Host {
return .{ .vtable = &vtable };
}
diff --git a/runtime/client.zig b/runtime/client.zig
index 28ed6a52..7ba9e790 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -142,8 +142,7 @@ pub fn Loop(comptime Frontend: type) type {
var done: std.atomic.Value(bool) = .init(false);
const reader = try std.Thread.spawn(.{}, read, .{ l, s, &done });
while (!link.quit) {
- const ms = l.before() orelse break;
- l.fe.wait(l, ms);
+ if (!l.pass()) break;
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
@@ -182,6 +181,23 @@ pub fn Loop(comptime Frontend: type) type {
l.fe.ended();
}
+ /// A pass up to its wait, and the wait: false when the frontend
+ /// ended the loop.
+ pub fn pass(l: *L) bool {
+ const ms = l.before() orelse return false;
+ l.fe.wait(l, ms);
+ return true;
+ }
+
+ /// The loop of a frontend that is woken from outside (the soak's,
+ /// test/replicas.zig, whose clock and link are a simulation's):
+ /// what woke it taken already (`input`, `take`), the rest of the
+ /// pass and the next up to its wait, as `run` goes round.
+ pub fn woken(l: *L) void {
+ l.after();
+ if (!l.link.quit) _ = l.pass();
+ }
+
/// A pass up to its wait: the frontend's own work, its predicted
/// echo judged and caught up (once a frame), its view drawn if
/// anything changed (else its own motion moved on), and how long
diff --git a/test/replicas.zig b/test/replicas.zig
index 857dcd75..2d199c60 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -1,7 +1,7 @@
//! pardes-replicas: a session and its clients in one process
-//! (core/replica.zig), each a process of its own for what a process holds
-//! (`Proc`): the session's own frontend typing in its view and drawing it,
-//! and each client (a terminal's loop or a window's, by turns) joined from
+//! (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
@@ -40,6 +40,7 @@ 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;
@@ -101,8 +102,6 @@ const Host = struct {
h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {};
}
- fn ignore(_: ?*anyopaque, _: []const u8) void {}
-
fn now(ctx: ?*anyopaque) u64 {
const h: *Host = @ptrCast(@alignCast(ctx.?));
return h.now_ns;
@@ -127,8 +126,10 @@ const Host = struct {
j.land(h.core.?);
}
- const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .job = job };
- const clocked_vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .now = now, .detach = detach, .job = job };
+ // 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 };
@@ -198,7 +199,13 @@ const Totals = struct {
inputs: u64 = 0,
speculated: u64 = 0,
stopped: u64 = 0,
- unspeculated: 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,
+ stops: [32]struct { name: []const u8 = "", n: u64 = 0 } = @splat(.{}),
units: u64 = 0,
fast: u64 = 0,
mispredicted: u64 = 0,
@@ -250,7 +257,11 @@ const Totals = struct {
t.inputs += s.inputs;
t.speculated += s.speculated;
t.stopped += s.stopped;
- t.unspeculated += s.unspeculated;
+ 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;
@@ -314,8 +325,7 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const
5 => "Search Recent",
6, 7 => looks[random.uintLessThan(usize, looks.len)],
8 => "Del",
- // A tab's width: every pane's layout, and a process global
- // (config.tab_now) its step writes.
+ // A tab's width: every pane's layout.
9 => "Tab 2",
10 => "Tab 8",
11 => "Life",
@@ -407,31 +417,18 @@ fn screenHash(t: *screen_state.Terminal) u64 {
return h.hasher.final();
}
-/// What a client's process holds apart from the session's, where the soak
-/// runs them all in one: the kinds it caught breaking PA_PLAIN, handed to
-/// each core it joins with (`Options.distrusted`). No process global stands
-/// in for a core's state any more (the tab's width is the core's): `enter`
-/// and `current` are left for the loops' rewrite to delete.
-const Proc = struct {
- distrusted: pardes.Addon.Distrusted = .{},
-
- var current: ?*Proc = null;
-
- fn enter(p: *Proc) void {
- current = p;
- }
-};
-
-/// A client of the session: a process of its own (`proc`) whose loop is
-/// the terminal's (tui.zig `runClient`) or the window's (gui.zig
-/// `clientSession`), over the real `replica.Link` on a socket pair whose
-/// other end the soak reads as the session's Peer does (`drain`). It joins
-/// from the session's dump, may be refused (every view taken), leaves, and
-/// joins again for its view after a divergence.
+/// 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 },
- proc: Proc = .{},
- link: replica.Link = undefined,
+ loop: ClientLoop = undefined,
r: ?*replica.Replica = null,
fds: [2]c_int = .{ -1, -1 },
check: [:0]u8 = undefined,
@@ -458,11 +455,11 @@ const Client = struct {
left: usize,
cols: u16,
rows: u16,
- last_input: u64 = 0,
- asked_at: u64 = 0,
+ /// 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,
drew: bool = false,
- resize: ?pardes.Event = null,
/// What it types in a row (a search, a sweep).
script: Script = .{},
/// gui.zig `Client.posted`: a size posted once while it waits.
@@ -472,52 +469,82 @@ const Client = struct {
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,
- fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool {
- const cl: *Client = @ptrCast(@alignCast(ctx.?));
- cl.drew = true;
- cl.facts = surface.facts.*;
- return true;
- }
-
- /// tui.zig `Client.draw` (gui.zig's is the same): its own view drawn
- /// outside any step, its timings its own.
- fn draw(cl: *Client) void {
- const r = cl.r.?;
- cl.frames.mark_start = pardes.FrameStats.nowNs();
- cl.frames.mark_update = cl.frames.mark_start;
- cl.drew = false;
- cl.link.owed = !r.draw(.{ .ctx = cl, .f = present });
- cl.frames.mark_render = cl.frames.mark_update;
- cl.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed);
- cl.link.drawn(cl.drew);
+ /// 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.
- fn own(cl: *Client) void {
+ /// 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)) return;
- cl.resize = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } };
+ 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;
}
- /// The window's own pass over its frame, and what it posted applied.
- fn within(cl: *Client) void {
- if (cl.kind != .window) return;
- cl.own();
- if (cl.resize) |ev| {
- if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) {
- cl.link.input(ev);
- cl.resizes += 1;
- const r = cl.r.?;
- if (r.core().live == r.view) pardes.draw.facts(r.core(), &cl.facts);
- }
- cl.posted = ev.resize;
- } else cl.posted = null;
- cl.resize = null;
+ /// 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 };
}
};
+const ClientLoop = client_loop.Loop(Client);
const Queue = std.PriorityQueue(Msg, void, Msg.order);
@@ -596,45 +623,48 @@ fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void {
cl.got.shrinkRetainingCapacity(cl.got.items.len - at);
}
-/// The rest of a pass of the client's loop, after what woke it (an input
-/// applied and sent, a message of the stream taken): as the two loops do
-/// each time round (tui.zig `runClient`, gui.zig `clientSession`): its
-/// inputs settled, a rollback drawn again, then its predicted echo judged,
-/// its view drawn if anything changed (the rows it lacks asked after),
-/// the copy taken while idle, and the session's digest asked once quiet.
-fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void {
+/// 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;
- const link = &cl.link;
- r.settle();
- if (r.moved) {
- r.moved = false;
- link.dirty = true;
+ 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 });
}
- if (link.owed or r.echo.changed) link.dirty = true;
- if (r.diverged != null) link.quit = true;
- if (!link.quit) {
- cl.within();
- if (r.echoFrame()) link.dirty = true;
- if (link.dirty) cl.draw();
- // Idle, its frame drawn: the window whenever its wait is not 0,
- // the terminal unless an event is held already (one pass in four).
- if (cl.kind == .window or net.random.uintLessThan(u8, 4) != 0) r.ready();
- // `quietCheck`, on the soak's clock: 300 ms after its last input
- // and its last check, changed since and quiet, the digest asked.
- if (link.changed and !link.asked and r.quiet()) {
- const due = @max(cl.last_input, cl.asked_at) + 300_000;
- if (now >= due) {
- link.input_ns = 0;
- link.asked_ns = 0;
- _ = link.quietCheck();
- cl.asked_at = now;
- } else if (cl.wake_at < due) {
- cl.wake_at = due;
- try net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(c + 1), .bytes = &.{}, .gen = cl.live });
- }
- }
- }
- try drain(cl, c, net, now);
+}
+
+/// 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
@@ -642,7 +672,7 @@ fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void {
/// 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.link;
+ 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);
@@ -672,8 +702,6 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
fn run(r: Run, dir: []const u8, totals: *Totals) !void {
if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms });
- // Last: the processes' globals were this run's.
- defer Proc.current = null;
var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms);
const random = prng.random();
var host: Host = .{};
@@ -717,15 +745,10 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
// 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.
- var session: Proc = .{};
- session.enter();
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 {
- session.enter();
- a.deinit();
- }
+ defer a.deinit();
host.core = a.core;
var screens: replica.Screens = .init(gpa);
defer screens.deinit(a.core);
@@ -788,7 +811,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
defer for (clients[0..r.clients]) |*cl| {
- cl.proc.enter();
if (cl.r) |rp| rp.deinit();
_ = libc.close(cl.fds[0]);
_ = libc.close(cl.fds[1]);
@@ -799,8 +821,8 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
// The link is made at the first join (its replica the dump's).
var has_link: [8]bool = @splat(false);
defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) {
- cl.link.check = null;
- cl.link.deinit(gpa);
+ cl.loop.link.check = null;
+ cl.loop.link.deinit(gpa);
};
// What the shell's program prints: a full-screen program, a shell's
@@ -936,7 +958,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
switch (m.kind) {
// ---- the session ----
.own => {
- session.enter();
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);
@@ -953,7 +974,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1;
},
.to_authority, .echo, .output => {
- session.enter();
// 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;
@@ -1001,7 +1021,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
host.echo.clearRetainingCapacity();
},
.frame => {
- session.enter();
// 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
@@ -1030,7 +1049,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
.dial => {
// Peers.join at the session's next boundary: its view kept
// for it, or a new one, or refused when all are taken.
- session.enter();
try ses.pending(m.at, flooding);
const id = next_id;
const j = (try a.join(id, cl.back)) orelse {
@@ -1053,7 +1071,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
try ses.flush(m.at, c);
},
.check_up => {
- session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
const d = try gpa.alloc(u8, 8);
@@ -1062,7 +1079,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
},
.bye_up => {
// Peers.leave: its view kept for it (`again`) or closed.
- session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
cl.joined = false;
@@ -1070,7 +1086,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false);
},
.screen_up => {
- session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little);
if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer);
@@ -1082,7 +1097,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
// does), while it has keys left to type.
cl.back = null;
if (cl.r) |old| {
- cl.proc.enter();
try totals.add(&old.stats);
old.deinit();
cl.r = null;
@@ -1096,7 +1110,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
}
},
.dump => {
- cl.proc.enter();
cl.dialling = false;
cl.tries = 0;
// replica.join: the core it left let go once the new one
@@ -1105,7 +1118,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
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.proc.distrusted });
+ 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;
@@ -1117,18 +1130,24 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
cl.live = m.gen;
var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} };
if (!has_link[c]) {
- cl.link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check };
+ 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.link.test_diverge = 40;
+ if (c == 1) cl.loop.link.test_diverge = 40;
}
- cl.link.reset(rp, &j);
+ 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;
- // What it is, then its size, are its view's first inputs
- // (the window's size from its own pass over its view).
- cl.link.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } });
- if (cl.kind == .tty) cl.link.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } });
- cl.last_input = m.at;
- try pass(cl, c, &net, m.at);
+ // 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 => {
@@ -1139,15 +1158,13 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
j.run();
// A state job's answer: a step of the session's own.
if (j.draw == null) {
- session.enter();
- host.now_ns = std.time.ns_per_s + m.at * 1000;
+ 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)) {
- session.enter();
- pardes.Kind.landDraw(a.core, j);
+ pardes.Kind.landDraw(a.core, j);
continue;
}
const k = for (clients[0..r.clients], 0..) |*dc, k| {
@@ -1157,14 +1174,12 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
continue;
};
const dc = &clients[k];
- dc.proc.enter();
pardes.Kind.landDraw(dc.r.?.core(), j);
- dc.link.dirty = true;
- try pass(dc, k, &net, m.at);
- if (dc.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing);
+ 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 => {
- cl.proc.enter();
if (m.kind == .input and cl.left == 0) continue;
const rp = cl.r orelse if (m.kind == .input and cl.dialling) {
try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
@@ -1178,13 +1193,13 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
}
} 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.within();
- cl.link.input(ev);
- cl.last_input = m.at;
+ 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;
@@ -1192,11 +1207,11 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} });
}
},
- .to_replica => cl.link.take(.{ .unit = try gpa.dupe(u8, m.bytes) }),
+ .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.link.take(.{ .screen = try gpa.dupe(u8, m.bytes) });
+ 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 {
@@ -1213,27 +1228,32 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
}
};
},
- .checked => cl.link.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }),
- .wake => cl.wake_at = 0,
- .quit => cl.link.quit = true,
+ .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.link.quit = true;
- cl.link.gone = true;
+ cl.loop.link.quit = true;
+ cl.loop.link.gone = true;
},
else => unreachable,
}
- try pass(cl, c, &net, m.at);
- if (cl.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing);
+ 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;
- session.enter();
const want = replica.digestOf(a);
for (clients[0..r.clients], 1..) |*cl, id| {
totals.resizes += cl.resizes;
+ totals.wakes += cl.wakes;
+ 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);
@@ -1246,7 +1266,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
};
}
const rp = cl.r orelse continue;
- cl.proc.enter();
try totals.add(&rp.stats);
if (cl.live == 0) continue;
if (rp.diverged) |why| {
@@ -1280,7 +1299,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void {
}
}
}
- session.enter();
}
/// A typist: keys 50-200 ms apart, a pause now and then.
@@ -2468,19 +2486,22 @@ pub fn main(init: std.process.Init) !void {
}
var failed = !try diffCase(dir);
if (!try plumbCase(dir)) failed = true;
+ if (!try corpusCase(dir)) failed = true;
std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us });
- std.debug.print(" rtt inputs at-once stopped view units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{});
+ 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:>4} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{
+ 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.unspeculated, t.units,
+ 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,
@@ -2504,12 +2525,231 @@ pub fn main(init: std.process.Init) !void {
t.screens_checked,
t.screens_wrong,
});
+ try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} ", .{ rtt, t.unlisted, t.wakes, t.draws });
+ 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) failed = true;
+ 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: what stopped the clients' 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 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 };
+ }
+};
+
+/// 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;
+}