diff options
Diffstat (limited to 'test')
| -rw-r--r-- | test/replicas.zig | 578 |
1 files changed, 409 insertions, 169 deletions
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; +} |
