From 558051ca5525a4dade47ab6ef7794eefd848f7b2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 15:36:25 -0300 Subject: replicas: the soak loads addons (a picture, a PDF and a game of life as a user's libraries, in a data directory of its own; the picture open at the start, every client joining with it), its session has a clock (its loop's: a frame, its own input or a pty's read moves it, a client's mail does not; a frame pumps it, Authority.pump) and takes the Detach word (the client's link ended by the session, its view closed), pictures' draws land on their loop 3 ms after they are asked (Kind.drawer), and what it found: a client joined from a dump replayed a step that made a file's pane and said why it had no room for it by announcing to /log first (events.bootFirst read the session's log, p.fs, which a client's is not: a replica never announces there now; a test fails without it), and a Debug client's rollback put back a kind's Debug list of its allocations that a speculation had grown and freed on the page allocator (Slot.used now the slot's allocator's; the soak's seeds 0 and 2 at rtt 207 crashed without it); not fixed, reported: a client joined from a dump holding a PDF pane diverges at another client's key into it (pane N.addon, views[k].jumps); daemon.py --games, --window-clients (its PDF case run with the addons installed) pass on the base, process-test the base's two; replicas five clients diverged 0, unequal 0, checked/wrong 2143/0, 2000/0, 1846/0, quiet checks 554/0, 540/0, 706/0; three clients diverged 0; tui core-test 823/964, shell-test 999/1002, behaviour-test 274/274 and --replay 20 seeds 0 failures, pane-test 180/181, gui unit-test 1593/1597 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build/tests.zig | 13 +++ build/tools.zig | 6 -- src/Kind.zig | 10 +- src/ninep/events.zig | 5 +- src/replica.zig | 49 ++++++++++ test/replicas.zig | 260 +++++++++++++++++++++++++++++++++++++++++++++------ 6 files changed, 304 insertions(+), 39 deletions(-) diff --git a/build/tests.zig b/build/tests.zig index 6ed97299..b7c7a5e7 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -135,6 +135,19 @@ pub fn add(b: *std.Build, c: struct { const liar_mod = b.createModule(.{ .root_source_file = b.path("test/liar.zig"), .target = c.target, .optimize = c.optimize, .imports = &.{.{ .name = "addon", .module = c.addon_mod }} }); const liar_lib = b.addLibrary(.{ .name = "liar", .linkage = .dynamic, .root_module = liar_mod }); for ([_]*std.Build.Step.Compile{ snake_lib, life_lib, liar_lib }) |lib| addon_test_step.dependOn(&b.addInstallArtifact(lib, .{}).step); + // The replicas' soak, its clients showing a picture, a PDF and a game + // of life 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 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"); + run_replicas.addArtifactArg(lib); + }; + run_replicas.addArg("--pdf"); + run_replicas.addFileArg(b.path("docs/design.pdf")); + run_replicas.addPassthruArgs(); + run_replicas.has_side_effects = true; + b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); for ([_]*std.Build.Module{ snake_mod, life_mod, liar_mod, c.parts.image }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); // ...and the pdf addon's, which mupdf-check runs too (its script // opens docs/design.pdf, from the build root). diff --git a/build/tools.zig b/build/tools.zig index bcf073ef..9b18019b 100644 --- a/build/tools.zig +++ b/build/tools.zig @@ -162,12 +162,6 @@ pub fn add(b: *std.Build, c: struct { run_rollback_bench.has_side_effects = true; b.step("rollback-bench", "a replica's rollback copy (walked state, pinned blobs, walk time) for a typical and a big session, and a fork of the big one (-Doptimize=ReleaseFast)").dependOn(&run_rollback_bench.step); - 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 run_replicas = b.addRunArtifact(replicas); - run_replicas.addPassthruArgs(); - run_replicas.has_side_effects = true; - b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); - const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); if (c.optimize != .fast) { locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); diff --git a/src/Kind.zig b/src/Kind.zig index 233365c7..bf8f14d1 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -218,8 +218,10 @@ pub const Slot = struct { /// A client's join: its plain kind's file, until the pane is opened /// from it (dump.plainHere). file: ?[]u8 = null, - /// Debug: the kind's allocations, which paint must leave as they are - /// (the list the page allocator's: a region's first is slow in Debug). + /// Debug: the kind's allocations, which paint must leave as they are. + /// The slot's allocator's, as the slot is: a client's rollback puts + /// the list back with the slot that holds it (on the page allocator, + /// the list put back was one a speculation had grown and freed). used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {}, pub const Job = struct { token: u32, in: []u8 }; @@ -239,7 +241,7 @@ pub const Slot = struct { pub fn free(s: *Slot) void { for (&s.jobs) |*j| if (j.*) |job| s.gpa.free(job.in); s.gpa.free(s.selection); - if (checked) s.used.deinit(std.heap.page_allocator); + if (checked) s.used.deinit(s.gpa); if (s.shadow) |sh| sh.deinit(s.gpa); if (s.plain) |b| if (b.len > 0) s.gpa.free(b); s.arena.deinit(); @@ -1088,7 +1090,7 @@ pub const api: c.pa_api = .{ break :mem cl.slot.arena.allocator().alignedAlloc(u8, .@"16", @max(n, 1)) catch return null; }; @memset(mem, 0); - if (checked) cl.slot.used.append(std.heap.page_allocator, mem) catch {}; + if (checked) cl.slot.used.append(cl.slot.gpa, mem) catch {}; return mem.ptr; } }.f, diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 9e6df93d..2af86108 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -154,8 +154,11 @@ pub fn announce(p: *Pardes) void { /// The panes present at boot are the log's first records: something said /// before the first update ends (an init file's notice) waits for them. +/// The log is the session's (`p.fs`, the authority's): a replica client's, +/// joined from a dump, is empty, and its step must not announce (taped +/// reads, Recent's) where the session's, booted long ago, does not. fn bootFirst(p: *Pardes) void { - if (newest(p) == null) announce(p); + if (newest(p) == null and !pardes.tape.replaying()) announce(p); } /// Records ` `. diff --git a/src/replica.zig b/src/replica.zig index 3af1caac..2cbf0c0c 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -239,6 +239,18 @@ pub const Authority = struct { a.batched += 1; } + /// A pass of its host's loop with no input (a frame's wake): its pump + /// alone, its clock advanced and what is due ticked, into the open + /// batch. + pub fn pump(a: *Authority) void { + a.t.no_digest = true; + defer a.t.no_digest = false; + const was = Stepping.begin(&a.t, null); + a.core.pump(a.host) catch {}; + was.end(); + a.batched += 1; + } + /// The open batch as a unit, or null: what the host sends before it /// steps any other input, and once a frame. pub fn pending(a: *Authority) !?[]const u8 { @@ -4173,6 +4185,43 @@ test "a replica joined from the session's dump replays the units after it" { try std.testing.expectEqual(digestOf(a), r.digest()); } +test "a replica joined from a dump replays a step that opens a file's pane and says it has no room for it: its /log, empty, is not the session's" { + const gpa = std.testing.allocator; + // No rows for a second pane: the Look's pane of a kind is made, the + // placement says it has no room (a message in the step that made the + // pane, which was not in /log yet), and the pane goes. + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const zon = pardes.Kind.loadedOf(&Zon.ops, "/x/zon.so", @splat(9), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = 0, .kind = &zon } }); + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + var whole: [libc.PATH_MAX]u8 = undefined; + var look: [libc.PATH_MAX + 8]u8 = undefined; + const path = std.mem.span(libc.realpath("build.zig.zon", &whole) orelse return error.SkipZigTest); + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&look, "Look {s}", .{path}) })); + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expectEqual(digestOf(a), r.digest()); +} + +/// A kind of `.zon` files, for a replica's Look of one (a picture's, +/// as a kind's pane is made). +const Zon = struct { + const pa = pardes.Kind.c; + fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { + return pardes.Kind.api.alloc.?(4); + } + fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "zon".* ++ @as([13]u8, @splat(0)), .version = 1, .exts = ".zon" }), + .open = open, + .paint = paint, + }); +}; + test "a replica joined from a themed dump paints its taglines in the restored theme" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); diff --git a/test/replicas.zig b/test/replicas.zig index 8d4b2e38..29923379 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -45,8 +45,32 @@ const Echo = pardes.Echo; const Key = pardes.Key; const gpa = std.heap.c_allocator; +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; const frame_us = 16_667; +/// The PDF its clients look at (`--pdf`), when the build has the addon. +var pdf_path: ?[]const u8 = null; + +/// A frontend's workers for pictures' draws (Kind.drawer, tui.zig +/// `Shell.draw`): each draw asked of any core here runs `draw_us` later, +/// as a worker's does, and lands on its core's loop then (`.draw`): +/// after the speculation that asked it may have been rolled back. +const Draws = struct { + var jobs: std.ArrayListUnmanaged(*pardes.host_io.KindJob) = .empty; + var net: ?*Net = null; + var now: u64 = 0; + const draw_us = 3_000; + + fn go(_: ?*anyopaque, j: *pardes.host_io.KindJob) bool { + const n = net orelse return false; + jobs.append(gpa, j) catch return false; + n.send(.{ .at = now + draw_us, .n = 0, .kind = .draw, .who = 0, .bytes = &.{} }) catch { + _ = jobs.pop(); + return false; + }; + return true; + } +}; /// The authority's host: no frames drawn (a replica draws its own), and a /// pty that echoes what it is written, 2 ms later, as a shell's. @@ -56,6 +80,16 @@ const Host = struct { /// of its own does (Pardes.pump), what that writes in its core and /// none of the replicas' with it. draws: bool = false, + /// The session's clock (`run`'s: its loop's, tui.zig `clockNow`): the + /// soak's time at a frame, an input of its own frontend's or a pty's + /// read; a pump woken by a client's mail alone reads the last again. + clocked: bool = false, + now_ns: u64 = 0, + /// Its core, and the view a step's Detach was typed in (tui.zig + /// `detach`: a client's link ends; the session's own view's is its + /// terminal's, which the soak has none of). + core: ?*pardes.Pardes = null, + detach_view: ?u8 = null, fn watched(ctx: ?*anyopaque) bool { const h: *Host = @ptrCast(@alignCast(ctx.?)); @@ -69,10 +103,21 @@ const Host = struct { fn ignore(_: ?*anyopaque, _: []const u8) void {} + fn now(ctx: ?*anyopaque) u64 { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + return h.now_ns; + } + + fn detach(ctx: ?*anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + h.detach_view = h.core.?.live; + } + const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore }; + const clocked_vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .now = now, .detach = detach }; fn host(h: *Host) pardes.Host { - return .{ .ctx = h, .vtable = &vtable }; + return .{ .ctx = h, .vtable = if (h.clocked) &clocked_vtable else &vtable }; } }; @@ -99,6 +144,10 @@ const Kind = enum { bye_up, wake, quit, + /// The session ended its link (a Detach typed in its view). + gone, + /// A picture's draw done on a worker, onto its loop (`Draws`). + draw, }; const Msg = struct { @@ -176,6 +225,10 @@ const Totals = struct { /// Resizes the windows posted (each pass whose view's size is not /// the window's: gui.zig `OwnView.run`). resizes: u64 = 0, + /// Clients let go by a Detach typed in their view. + detach_words: u64 = 0, + /// Panes of each plain kind the session opened (image, pdf, life). + kind_panes: [3]u64 = @splat(0), fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -199,7 +252,10 @@ const Totals = struct { /// One client's next input: monkey.zig's mix, as events, and now and then /// a wheel over the shell pane, which scrolls its history into view; a /// file looked at (`looks`, its words) and a pane closed, the Panes and -/// Recent pickers (the store's and Recent's rows, the authority's), a jump. +/// Recent pickers (the store's and Recent's rows, the authority's), a jump; +/// a picture and a PDF looked at and a game of life opened (plain kinds a +/// client runs as the session does, `looks` past the texts), the keys +/// after going to its pane; now and then a client's Detach. fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const []const u8) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; @@ -226,7 +282,7 @@ fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)]; return .{ .paste = buf[0..n] }; }, - 36 => return .{ .command = switch (random.uintLessThan(u8, 12)) { + 36 => return .{ .command = switch (random.uintLessThan(u8, 14)) { 0 => "Newcol", 1 => "Zerox", 2 => "Undo", @@ -239,6 +295,10 @@ fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const // (config.tab_now) its step writes. 9 => "Tab 2", 10 => "Tab 8", + 11 => "Life", + // Its link ended by the session (the session's own view's, + // its terminal's: none here). + 12 => if (random.uintLessThan(u8, 4) == 0) "Detach" else "Undo", else => return .{ .key = .{ .cp = if (random.boolean()) 'o' else 'i', .ctrl = true } }, } }, 37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } }, @@ -520,10 +580,11 @@ fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void { /// Its link ended (it diverged, or it quits): its bye, and its join again /// for its view after a divergence (`Link.rejoins`), the core it leaves /// held until the dump comes, as `replica.join` holds it. -fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run) !void { +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; - replica.bye(cl.fds[1], r.diverged != null); + // Its link ended by the session (a Detach), it says nothing more. + if (!link.gone) replica.bye(cl.fds[1], r.diverged != null); try drain(cl, c, net, now); cl.live = 0; if (r.diverged) |why| { @@ -541,6 +602,12 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run) r.deinit(); cl.r = null; totals.detached += 1; + // Let go before it typed all it had: the rest is never typed. + if (link.gone) totals.detach_words += 1; + if (cl.left > 0) { + typing.* -= 1; + cl.left = 0; + } } fn run(r: Run, dir: []const u8, totals: *Totals) !void { @@ -555,29 +622,60 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { host.echo.deinit(gpa); } var paths: [3][256:0]u8 = undefined; - var look_lines: [3][300]u8 = undefined; - var looks: [3][]const u8 = undefined; - for (&paths, &look_lines, &looks, 0..) |*p, *l, *look, i| { + var look_lines: [5][300]u8 = undefined; + var looks_buf: [5][]const u8 = undefined; + for (&paths, look_lines[0..3], looks_buf[0..3], 0..) |*p, *l, *look, i| { const path = try std.fmt.bufPrintSentinel(p, "{s}/f{d}.zig", .{ dir, i }, 0); try writeFile(path, 60 + 40 * i); look.* = try std.fmt.bufPrint(l, "Look {s}", .{path}); } + // A picture (the image addon's) and the PDF (the pdf addon's), when + // the soak has their libraries (`--addon`). + var picture: [256:0]u8 = undefined; + var nlooks: usize = 3; + const kinds = pardes.Addon.scan(); + for (kinds) |l| if (std.mem.eql(u8, l.name, "image")) { + const path = try std.fmt.bufPrintSentinel(&picture, "{s}/picture.ppm", .{dir}, 0); + var ppm: std.ArrayListUnmanaged(u8) = .empty; + defer ppm.deinit(gpa); + try ppm.print(gpa, "P6\n64 48\n255\n", .{}); + for (0..48) |y| for (0..64) |x| try ppm.appendSlice(gpa, &.{ @intCast(x * 4), @intCast(y * 5), @intCast((x + y) * 2) }); + try writeText(path, ppm.items); + looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{path}); + nlooks += 1; + } else if (std.mem.eql(u8, l.name, "pdf")) if (pdf_path) |pdf| { + looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{pdf}); + nlooks += 1; + }; + const looks = looks_buf[0..nlooks]; // The tty's own boot (a raw shell, a text pane under it), then three // files looked at: the session's own frontend shows the first view // and types in it; each client joins from a dump for a view of its own. var session: Proc = .{}; session.enter(); - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); + 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(); } + host.core = a.core; var screens: replica.Screens = .init(gpa); defer screens.deinit(a.core); for (&paths) |*path| { var line: [300]u8 = undefined; _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) }); } + // The picture in a column of its own: every client joins with it (a + // plain kind's pane loaded from a dump, its file read by its path), its + // keys go to it when it has them. Not the PDF: a client joined from a + // dump that holds one diverges at another client's key into it + // (round 5's report: `pane N.addon`, `views[k].jumps`), open. + if (looks.len > 3) { + _ = try a.local(.{ .command = "Newcol" }); + _ = try a.local(.{ .command = looks[3] }); + } const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; @@ -591,6 +689,14 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { while (net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); net.q.deinit(gpa); } + pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; + Draws.net = &net; + defer { + pardes.Kind.drawer = null; + Draws.net = null; + for (Draws.jobs.items) |j| j.drop(); + Draws.jobs.clearRetainingCapacity(); + } // The clients: terminals and windows by turns. The first two dial at // once, the third late (the shell's program on), more later still // (refused while every view is taken, dialling again until one is @@ -668,6 +774,29 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { owed: *std.ArrayListUnmanaged([]u8), versions: *std.AutoHashMapUnmanaged(u64, u64), totals: *Totals, + host: *Host, + kinds_seen: *u32, + + /// A Detach its step took (Host.detach) in a client's view: that + /// client's link shut inside the step, before its unit goes + /// (Peers.detach), so it hears its end and not the unit; which it is. + fn detaching(s: @This(), now: u64) !?usize { + const k = s.host.detach_view orelse return null; + s.host.detach_view = null; + for (s.clients, 0..) |*cl, c| if (cl.joined and cl.view == k) { + cl.joined = false; + s.screens.dropPeer(cl.sid); + try s.net.toClient(c, now, .gone, cl.gen, &.{}); + return c; + }; + return null; + } + + /// ...and let go at the next boundary, its view closed (Peers.leave). + fn detached(s: @This(), c: ?usize, now: u64) !void { + const gone = c orelse return; + try s.unit(try s.a.leave(s.clients[gone].id, false), now, false); + } /// The batch of its own steps as a unit, if any (`Authority.pending`). fn pending(s: @This(), now: u64, flooding: bool) !void { @@ -677,6 +806,11 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { /// A unit to every client joined (Peers.unit), after the rows of /// its terminals its steps read that a client holds as holes. fn unit(s: @This(), u: []const u8, now: u64, flooding: bool) !void { + // The kinds' panes it has opened, each counted once. + for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) { + s.kinds_seen.* = pane.serial; + for ([_][]const u8{ "image", "pdf", "life" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); + }; var rows: std.ArrayListUnmanaged([]u8) = .empty; defer rows.deinit(gpa); for (s.clients, 0..) |*cl, c| if (cl.joined) { @@ -717,10 +851,13 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }; } }; - const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals }; + var kinds_seen: u32 = 0; + + const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals, .host = &host, .kinds_seen = &kinds_seen }; while (net.q.pop()) |m| { defer if (m.bytes.len > 0) gpa.free(m.bytes); + Draws.now = m.at; const flooding = m.at >= flood_at and flood_end == 0; // A client's message, but an echo's and an output's `who` (a pane, // a program). @@ -730,11 +867,15 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // ---- 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, wheel_at, &looks); + const ev = nextEvent(random, &buf, wheel_at, looks); try ses.pending(m.at, flooding); try ses.flush(m.at, null); - try ses.unit(try a.own(ev), m.at, false); + const u = try a.own(ev); + // Its own view's Detach is its terminal's: none here. + host.detach_view = null; + try ses.unit(u, m.at, false); try ses.flush(m.at, null); for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); host.echo.clearRetainingCapacity(); @@ -743,6 +884,9 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }, .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; const unit = switch (m.kind) { .echo => echo: { a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } }); @@ -778,7 +922,9 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }, }; if (unit) |u| { + const gone = try ses.detaching(m.at); try ses.unit(u, m.at, false); + try ses.detached(gone, m.at); try ses.flush(m.at, null); } for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); @@ -786,12 +932,14 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { }, .frame => { session.enter(); - // Its own frontend's frame: a pump that draws its view (and - // ticks: messages, streams) when one is owed or something is - // due, once a frame at most, as its host's loop paces it. - if (a.core.needs_frame or a.core.nextWake() != null) { + // Its own frontend's frame: its loop woken when a frame is + // owed or the core's next wake is due, a pump that advances + // its clock (what is due ticks: messages, glides, a kind's + // tick) and draws its view, as its host's loop paces it. + host.now_ns = std.time.ns_per_s + m.at * 1000; + if (a.core.needs_frame or (a.core.nextWake() orelse std.math.maxInt(u64)) <= host.now_ns) { host.draws = true; - a.output(.tick); + a.pump(); host.draws = false; } try ses.pending(m.at, flooding); @@ -802,9 +950,11 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { totals.flood_delta_bytes += totals.delta_bytes - before; try totals.frame_ns.append(gpa, screens.encode_ns - t0); } - // Frames go on while anything moves, and a second after. - const busy = typing > 0 or flood_end == 0 or net.q.count() > 0; - frames_left = if (busy) 60 else frames_left -| 1; + // Frames go on while anyone types or the flood runs, and two + // seconds after (a session with a clock wakes on: a blink, a + // kind's tick; what is in flight still comes, unpumped). + const busy = typing > 0 or flood_end == 0; + frames_left = if (busy) 120 else frames_left -| 1; if (frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); }, .dial => { @@ -910,7 +1060,31 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try pass(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 = &.{} }); }, - .input, .to_replica, .screen_down, .checked, .wake, .quit => { + .draw => { + // A worker's draw done, onto the loop of the core that asked + // it (tui.zig `.kind_job`): kept for its pane's next paint, + // a frame owed; one of a core gone since is let go. + const j = Draws.jobs.orderedRemove(0); + j.run(); + if (j.draw == @as(?*const pardes.Pardes, a.core)) { + session.enter(); + pardes.Kind.landDraw(a.core, j); + continue; + } + const k = for (clients[0..r.clients], 0..) |*dc, k| { + if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k; + } else { + j.drop(); + continue; + }; + const dc = &clients[k]; + 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); + }, + .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) { @@ -928,7 +1102,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { switch (m.kind) { .input => { var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, wheel_at, &looks); + const ev = nextEvent(random, &buf, wheel_at, looks); cl.within(); cl.link.input(ev); cl.last_input = m.at; @@ -963,10 +1137,14 @@ 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, + .gone => { + cl.link.quit = true; + cl.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); + if (cl.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing); }, .client_frame => {}, } @@ -1871,7 +2049,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .screen_up => { if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); }, - .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw => {}, } } const s = rp.echo.stats; @@ -2155,6 +2333,8 @@ pub fn main(init: std.process.Init) !void { var flood_mb: u64 = 8; var screen_dir: ?[]const u8 = null; var rtt_buf: [8]u64 = undefined; + var addons: std.ArrayListUnmanaged([]const u8) = .empty; + defer addons.deinit(gpa); var i: usize = 1; while (i < args.len) : (i += 1) { const name = args[i]; @@ -2165,7 +2345,9 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--rtt")) { + if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { + pdf_path = value; + } else if (std.mem.eql(u8, name, "--rtt")) { var it = std.mem.tokenizeScalar(u8, value, ','); var k: usize = 0; while (it.next()) |v| : (k += 1) rtt_buf[k] = try std.fmt.parseInt(u64, v, 10); @@ -2184,6 +2366,28 @@ pub fn main(init: std.process.Init) !void { const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) }); try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir); defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {}; + // Its own data directory, the only one its addon scan reads (never the + // user's): the libraries it was given (`--addon`), as a user's are + // installed, read by the session's core and its clients' alike. + var data_buf: [300]u8 = undefined; + const data = try std.fmt.bufPrintSentinel(&data_buf, "{s}/data", .{dir}, 0); + var lib_dir_buf: [300]u8 = undefined; + const lib_dir = try std.fmt.bufPrint(&lib_dir_buf, "{s}/pardes/addons", .{data}); + try std.Io.Dir.cwd().createDirPath(init.io, lib_dir); + for (addons.items) |lib| { + var to: [600]u8 = undefined; + var from: [600]u8 = undefined; + var whole: [libc.PATH_MAX]u8 = undefined; + const at = libc.realpath(try std.fmt.bufPrintSentinel(&from, "{s}", .{lib}, 0), &whole) orelse return error.NoAddon; + if (libc.symlink(at, try std.fmt.bufPrintSentinel(&to, "{s}/{s}", .{ lib_dir, std.Io.Dir.path.basename(lib) }, 0)) != 0) return error.NoAddon; + } + if (setenv("XDG_DATA_HOME", data, 1) != 0) return error.NoDataDir; + // The PDF by its whole path: a Look of another is the session's directory's. + var pdf_whole: [libc.PATH_MAX]u8 = undefined; + if (pdf_path) |pdf| { + var z: [600]u8 = undefined; + pdf_path = std.mem.span(libc.realpath(try std.fmt.bufPrintSentinel(&z, "{s}", .{pdf}, 0), &pdf_whole) orelse return error.NoPdf); + } if (echo_mode) { if (!try echoMain(seeds, first, rtts)) std.process.exit(1); return; @@ -2226,12 +2430,12 @@ pub fn main(init: std.process.Init) !void { t.screens_checked, t.screens_wrong, }); - try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>5}/{d:<5} {d:>7}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.agree, t.differ, t.resizes }); + try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, 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; } 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; quiet checks of the session's digest agreed/differed; resizes the windows posted\n", .{}); - std.debug.print(" rtt joins refused rejoined detached agree/differ resizes\n{s}", .{join_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; resizes the windows posted; the kinds' panes the session opened (image/pdf/life)\n", .{}); + std.debug.print(" rtt joins refused rejoined detached detach agree/differ resizes kinds\n{s}", .{join_lines.items}); if (failed) std.process.exit(1); } -- cgit v1.3 From f7fc58ee8ae9a88b09ee1c235b9986df8b1ef844 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 16:38:10 -0300 Subject: replica: a client compares its core's digest with the session's only where one is due, not at every confirmed input and every unit replayed (the edit row's +40%, a full walk of the core each time): once in check_every (32) confirmed units, on a unit that carries one with nothing applied on top (the fast path's catch-up, a replay, a rollback's), and once quiet 300 ms after a change (Link.quietCheck, now always, not only for PARDES_REPLICA_CHECK: another digest is a divergence, and it joins again; PARDES_TEST_DIVERGE is found so); a unit replayed by a rollback (since) compares none; a unit with no digest leaves the last one unknown (after a unit with a set record it was kept, stale, for the moved-nothing comparison); the authority in process records its digest at a unit's end as the session does; the session still records one a unit (a session's unit with none where its clock moved exposed a structural divergence after a kind is distrusted: daemon.py --games, a second rejoin, 'the tape's answer to addon is short'; not root-caused); the soak's mix without the PDF (round 5's open fault); replicas five clients diverged 0, unequal 0, the put-off client caught by a quiet check or a due one Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build/tests.zig | 7 ++-- src/replica.zig | 96 ++++++++++++++++++++++++++++++++++++++----------------- src/tape.zig | 4 +++ test/replicas.zig | 40 +++++++++-------------- 4 files changed, 89 insertions(+), 58 deletions(-) diff --git a/build/tests.zig b/build/tests.zig index b7c7a5e7..ff206438 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -135,16 +135,15 @@ pub fn add(b: *std.Build, c: struct { const liar_mod = b.createModule(.{ .root_source_file = b.path("test/liar.zig"), .target = c.target, .optimize = c.optimize, .imports = &.{.{ .name = "addon", .module = c.addon_mod }} }); const liar_lib = b.addLibrary(.{ .name = "liar", .linkage = .dynamic, .root_module = liar_mod }); for ([_]*std.Build.Step.Compile{ snake_lib, life_lib, liar_lib }) |lib| addon_test_step.dependOn(&b.addInstallArtifact(lib, .{}).step); - // The replicas' soak, its clients showing a picture, a PDF and a game - // of life from these libraries, as a user's addons are loaded. + // The replicas' soak, its clients showing a picture and a game of life + // from these libraries, as a user's addons are loaded (the PDF's too, + // whose pane it does not open: round 5's report). 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 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"); run_replicas.addArtifactArg(lib); }; - run_replicas.addArg("--pdf"); - run_replicas.addFileArg(b.path("docs/design.pdf")); run_replicas.addPassthruArgs(); run_replicas.has_side_effects = true; b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); diff --git a/src/replica.zig b/src/replica.zig index 2cbf0c0c..b6fbdfa0 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -43,6 +43,11 @@ const stamp_len = wire.header_len + 16; /// Confirmed units fast-pathed under one copy before it is taken afresh: /// a rollback replays them all. const rebase_after = 32; +/// A client compares its core's digest with the session's at most once in +/// this many confirmed units (a unit that carries one, its state the +/// confirmed one), and once quiet (`Link.quietCheck`): a full digest is a +/// walk of the whole core, an edit's worth of work. +const check_every = 32; fn header(buf: []u8, who: u16, seq: u32) void { std.mem.writeInt(u16, buf[0..2], who, .little); @@ -173,6 +178,8 @@ pub const Authority = struct { a.t.screen_state = screens; // One word a digest: every pty read is a unit. a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null; + // A digest at a unit's end, as the session's (Peers.unit). + a.t.no_digest = true; const was = Stepping.begin(&a.t, null); defer was.end(); a.core = try Pardes.init(gpa, opts); @@ -193,6 +200,9 @@ pub const Authority = struct { /// What was recorded since the last unit, as one (the boot's, a setup's /// done straight on the core). pub fn unit(a: *Authority, origin: u16, seq: u32) ![]const u8 { + const was = Stepping.begin(&a.t, null); + tape.recordDigest(&a.t); + was.end(); a.out.clearRetainingCapacity(); try a.out.appendNTimes(a.gpa, 0, unit_head); unitHeader(a.out.items, origin, seq); @@ -233,8 +243,6 @@ pub const Authority = struct { /// authority's rolls back a replica's pending inputs), and its digest /// once a unit. pub fn output(a: *Authority, ev: pardes.Event) void { - a.t.no_digest = true; - defer a.t.no_digest = false; a.apply(ev); a.batched += 1; } @@ -243,8 +251,6 @@ pub const Authority = struct { /// alone, its clock advanced and what is due ticked, into the open /// batch. pub fn pump(a: *Authority) void { - a.t.no_digest = true; - defer a.t.no_digest = false; const was = Stepping.begin(&a.t, null); a.core.pump(a.host) catch {}; was.end(); @@ -256,9 +262,6 @@ pub const Authority = struct { pub fn pending(a: *Authority) !?[]const u8 { if (a.batched == 0) return null; a.batched = 0; - const was = Stepping.begin(&a.t, null); - tape.recordDigest(&a.t); - was.end(); a.seq += 1; return try a.unit(0, a.seq); } @@ -637,6 +640,8 @@ pub const Stats = struct { foreign: u32 = 0, rebases: u32 = 0, units: u32 = 0, + /// Its digest compared with the session's (a unit's, or quiet). + checks: u32 = 0, /// The samples below kept: an in-process harness's replica, or a /// client's with PARDES_REPLICA_STATS. Without, nothing is: a client /// runs for days, and they grew a word an input and a delta. @@ -734,6 +739,8 @@ pub const Replica = struct { last_digest: std.ArrayListUnmanaged(u8) = .empty, /// Units of another's taken so, no rollback made. neutral: u32 = 0, + /// Confirmed units since its digest was last compared (`check_every`). + since_check: u32 = 0, /// What it shows changed since the host last drew it: a unit replayed /// on it, a rollback (a unit that confirmed what it applied, or moved /// nothing, changes nothing to draw). @@ -790,6 +797,7 @@ pub const Replica = struct { r.* = .{ .gpa = gpa, .id = id, .t = tape.memory(gpa), .stats = .{ .samples = true } }; r.t.screen_state = screens; r.t.core_gpa = r.epoch.allocator(); + r.t.checks = false; r.confirm(first); if (r.t.core == null) { r.deinit(); @@ -810,6 +818,7 @@ pub const Replica = struct { const r = try gpa.create(Replica); r.* = .{ .gpa = gpa, .id = id, .view = view, .t = tape.memory(gpa), .guess = true }; r.t.skips_render = true; + r.t.checks = false; // Its terminals are the session's deltas (Peers sends them). r.t.screen_state = true; errdefer { @@ -927,6 +936,7 @@ pub const Replica = struct { if (r.diverged != null) return; const u = parseUnit(msg) orelse return r.fail("a unit too short to read"); r.stats.units += 1; + r.since_check +|= 1; if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq); // A copy taken ahead (`ready`), nothing on top: it stays the point a // rollback goes back to, the unit replayed on it and kept in `since`, @@ -948,11 +958,9 @@ pub const Replica = struct { { r.stats.fast += 1; // The state it ends on, which a unit of another's that moves - // nothing ends on again (`neutral`). - if (lastDigest(u.tape)) |d| { - r.last_digest.clearRetainingCapacity(); - r.last_digest.appendSlice(r.gpa, d) catch {}; - } + // nothing ends on again (`neutral`); none, not known. + r.last_digest.clearRetainingCapacity(); + if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; if (r.pending.items[0].terminal and r.applied > 1) { // Right, but what it did read a terminal: replayed later (a // rollback's `since`) it would read the deltas that came @@ -969,17 +977,21 @@ pub const Replica = struct { r.applied -= 1; if (r.applied == 0) { // Nothing speculative on top any more: the state is the - // confirmed one, which its digest says. A step of its own - // that read what the session's did not (a frame's, a - // derived field's) shows here, at the input that did it, - // not at some later unit replayed. - if (lastDigest(u.tape)) |d| { + // confirmed one, which its digest says, when it carries one + // and a check is due. A step of its own that read what the + // session's did not (a frame's, a derived field's) shows at + // the next check, or quiet (`Link.quietCheck`). + if (r.checkDue()) if (lastDigest(u.tape)) |d| { + r.t.checks = true; r.t.check(d); + r.t.checks = false; + r.since_check = 0; + r.stats.checks += 1; if (r.t.diverged) |why| { trace(r.gpa, "replica {d}: its input {d} came to another state than the session's: {s}\n", .{ r.id, u.seq, why }, &.{u.tape}); return r.fail(why); } - } + }; // The copy stays the point a rollback goes back to, this // input kept to replay over it as a unit of the session's // that comes while idle is: a step writes some bytes of the @@ -997,10 +1009,12 @@ pub const Replica = struct { return r.keepSince(u.tape); } const ends = lastDigest(u.tape); - defer if (ends) |d| { + // None: where it ended is not known, and the next unit is not + // taken as moving nothing from it. + defer { r.last_digest.clearRetainingCapacity(); - r.last_digest.appendSlice(r.gpa, d) catch {}; - }; + if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; + } if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the @@ -1030,10 +1044,20 @@ pub const Replica = struct { for (c.panes, &serials) |slot, *n| n.* = if (slot) |pane| pane.serial else 0; for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; } - if (tape.replayUnit(&r.t, u.tape)) |why| { + // Its digest compared when one is due (the units kept since and + // replayed by a rollback were, if at all, as they came). + const check = ends != null and r.checkDue(); + r.t.checks = check; + const replayed = tape.replayUnit(&r.t, u.tape); + r.t.checks = false; + if (replayed) |why| { trace(r.gpa, "replica {d}: the unit of {d}/{d} diverged: {s}\n", .{ r.id, u.origin, u.seq, why }, &.{u.tape}); return r.fail(why); } + if (check) { + r.since_check = 0; + r.stats.checks += 1; + } if (u.origin == r.id) { if (r.pending.items.len == 0 or r.pending.items[0].seq != u.seq) return r.fail("the authority confirmed an input this replica did not send next"); if (r.blocked == u.seq) r.blocked = null; @@ -1058,6 +1082,11 @@ pub const Replica = struct { r.keepSince(u.tape); } + /// Its digest is due a comparison (`check_every`; every unit traced). + fn checkDue(r: *const Replica) bool { + return r.since_check >= check_every or std.c.getenv("PARDES_REPLICA_TRACE") != null; + } + fn fail(r: *Replica, why: []const u8) void { if (r.diverged == null) r.diverged = r.gpa.dupe(u8, why) catch return; } @@ -3072,9 +3101,10 @@ pub const Link = struct { /// The last frame was held for the frontend's answer (a terminal's /// FrameAck, a window's skipped image). owed: bool = false, - /// PARDES_REPLICA_CHECK=: once quiet a while after a change, the - /// session's digest is asked, and whether this replica's agrees is - /// written there, a line a check. + /// Once quiet a while after a change, the session's digest is asked + /// (`quietCheck`): another than this replica's is a divergence, and it + /// joins again. PARDES_REPLICA_CHECK=: whether they agree is + /// written there too, a line a check. check: ?[:0]const u8 = null, changed: bool = false, asked: bool = false, @@ -3227,7 +3257,7 @@ pub const Link = struct { /// window's test feed, sends a unit a frame; the check's own wakes it /// once). The wake it wants, ms. pub fn quietCheck(c: *Link) ?u32 { - if (c.check == null or !c.changed or c.asked or !c.r.quiet()) return null; + 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); if (since < quiet_ns) return @intCast((quiet_ns - since) / std.time.ns_per_ms + 1); @@ -3238,12 +3268,20 @@ pub const Link = struct { return null; } - /// The session's digest against this replica's, if it is quiet still. + /// The session's digest against this replica's, if it is quiet still: + /// another is a divergence (the replica joins again). fn checked(c: *Link, theirs: u64) void { c.asked = false; - const path = c.check orelse return; - if (!c.r.quiet() or c.put_off) return; + if (!c.r.quiet() or c.r.diverged != null) return; const mine = c.r.digest(); + c.r.stats.checks += 1; + c.r.since_check = 0; + if (mine != theirs) { + c.r.fail("its digest, quiet, is not the session's"); + c.quit = true; + } + const path = c.check orelse return; + if (c.put_off) return; var buf: [96]u8 = undefined; const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; appendTo(path, line); diff --git a/src/tape.zig b/src/tape.zig index 2875b156..9337ff9f 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -286,6 +286,9 @@ pub const Tape = struct { /// A digest only when asked (`recordDigest`): the replica stream's, /// one a unit, not one after each of its inputs. unit_digests: bool = false, + /// A digest record replayed is compared with the core's own; a replica + /// client's compares one now and then (src/replica.zig `check_every`). + checks: bool = true, /// A replica client's guess of the session's clocks for a speculation /// (src/replica.zig): its clock reads (a message's stamp, a file's /// mtime) answer this instead of the clocks here. @@ -570,6 +573,7 @@ pub const Tape = struct { /// A digest record's payload (a unit's last) against the core's own: a /// difference is `diverged`, its fields named when the record has them. pub fn check(t: *Tape, payload: []const u8) void { + if (!t.checks) return; var r: walk.Reader = .{ .bytes = payload }; const want = walk.decode([]const u64, &r, t.arena.allocator()) catch return; const p = t.core orelse return; diff --git a/test/replicas.zig b/test/replicas.zig index 29923379..bd759b03 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -48,8 +48,6 @@ const gpa = std.heap.c_allocator; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; const frame_us = 16_667; -/// The PDF its clients look at (`--pdf`), when the build has the addon. -var pdf_path: ?[]const u8 = null; /// A frontend's workers for pictures' draws (Kind.drawer, tui.zig /// `Shell.draw`): each draw asked of any core here runs `draw_us` later, @@ -190,6 +188,8 @@ const Totals = struct { mispredicted: u64 = 0, foreign: u64 = 0, rebases: u64 = 0, + /// A client's digest compared with the session's (a unit's, quiet). + checks: u64 = 0, copies: u64 = 0, copy_bytes: u64 = 0, divergences: u64 = 0, @@ -227,8 +227,8 @@ const Totals = struct { resizes: u64 = 0, /// Clients let go by a Detach typed in their view. detach_words: u64 = 0, - /// Panes of each plain kind the session opened (image, pdf, life). - kind_panes: [3]u64 = @splat(0), + /// Panes of each plain kind the session opened (image, life). + kind_panes: [2]u64 = @splat(0), fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -240,6 +240,7 @@ const Totals = struct { t.mispredicted += s.mispredicted; t.foreign += s.foreign; t.rebases += s.rebases; + t.checks += s.checks; t.copies += s.copies; t.copy_bytes += s.copy_bytes; try t.spec_ns.appendSlice(gpa, s.spec_ns.items); @@ -253,7 +254,7 @@ const Totals = struct { /// a wheel over the shell pane, which scrolls its history into view; a /// file looked at (`looks`, its words) and a pane closed, the Panes and /// Recent pickers (the store's and Recent's rows, the authority's), a jump; -/// a picture and a PDF looked at and a game of life opened (plain kinds a +/// a picture looked at and a game of life opened (plain kinds a /// client runs as the session does, `looks` past the texts), the keys /// after going to its pane; now and then a client's Detach. fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16, looks: []const []const u8) pardes.Event { @@ -629,7 +630,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try writeFile(path, 60 + 40 * i); look.* = try std.fmt.bufPrint(l, "Look {s}", .{path}); } - // A picture (the image addon's) and the PDF (the pdf addon's), when + // A picture (the image addon's), when // the soak has their libraries (`--addon`). var picture: [256:0]u8 = undefined; var nlooks: usize = 3; @@ -643,9 +644,6 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { try writeText(path, ppm.items); looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{path}); nlooks += 1; - } else if (std.mem.eql(u8, l.name, "pdf")) if (pdf_path) |pdf| { - looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{pdf}); - nlooks += 1; }; const looks = looks_buf[0..nlooks]; // The tty's own boot (a raw shell, a text pane under it), then three @@ -669,9 +667,9 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } // The picture in a column of its own: every client joins with it (a // plain kind's pane loaded from a dump, its file read by its path), its - // keys go to it when it has them. Not the PDF: a client joined from a - // dump that holds one diverges at another client's key into it - // (round 5's report: `pane N.addon`, `views[k].jumps`), open. + // keys go to it when it has them. Not a PDF: a client of a session that + // shows one diverges at a key into it (round 5's report: `pane N.addon`, + // `views[k].jumps`; `it breaks PA_PLAIN` after a key), open. if (looks.len > 3) { _ = try a.local(.{ .command = "Newcol" }); _ = try a.local(.{ .command = looks[3] }); @@ -809,7 +807,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // The kinds' panes it has opened, each counted once. for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) { s.kinds_seen.* = pane.serial; - for ([_][]const u8{ "image", "pdf", "life" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); + for ([_][]const u8{ "image", "life" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); }; var rows: std.ArrayListUnmanaged([]u8) = .empty; defer rows.deinit(gpa); @@ -2345,9 +2343,7 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { - pdf_path = value; - } else if (std.mem.eql(u8, name, "--rtt")) { + if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--rtt")) { var it = std.mem.tokenizeScalar(u8, value, ','); var k: usize = 0; while (it.next()) |v| : (k += 1) rtt_buf[k] = try std.fmt.parseInt(u64, v, 10); @@ -2382,12 +2378,6 @@ pub fn main(init: std.process.Init) !void { if (libc.symlink(at, try std.fmt.bufPrintSentinel(&to, "{s}/{s}", .{ lib_dir, std.Io.Dir.path.basename(lib) }, 0)) != 0) return error.NoAddon; } if (setenv("XDG_DATA_HOME", data, 1) != 0) return error.NoDataDir; - // The PDF by its whole path: a Look of another is the session's directory's. - var pdf_whole: [libc.PATH_MAX]u8 = undefined; - if (pdf_path) |pdf| { - var z: [600]u8 = undefined; - pdf_path = std.mem.span(libc.realpath(try std.fmt.bufPrintSentinel(&z, "{s}", .{pdf}, 0), &pdf_whole) orelse return error.NoPdf); - } if (echo_mode) { if (!try echoMain(seeds, first, rtts)) std.process.exit(1); return; @@ -2430,12 +2420,12 @@ pub fn main(init: std.process.Init) !void { t.screens_checked, t.screens_wrong, }); - try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + 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}\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] }); if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 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; resizes the windows posted; the kinds' panes the session opened (image/pdf/life)\n", .{}); - std.debug.print(" rtt joins refused rejoined detached detach agree/differ resizes kinds\n{s}", .{join_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)\n", .{}); + std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); if (failed) std.process.exit(1); } -- cgit v1.3 From 28921f1f793938b2d40a1a8fee43d3b1b0f7c4d2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 17:05:06 -0300 Subject: gui, panes: a window client posts its size once while its view is not that size yet (Client.posted, let go when the view is the window's or at a rejoin), not on every pass while the session has not taken it (the soak's windows posted 36 resizes at rtt 30 and 128 at 207 with three clients in round 4, 19 and 13 now; the soak's window clients do the same); and a screen-state client's speculation of a terminal's resize does what its replay does (the pane's selections, never the grid, which the session's next delta sizes), so a resize no longer stops and waits a round trip (the soak's stopped inputs 135 -> 59 at rtt 30, 120 -> 61 at 80); replicas five clients diverged 0, unequal 0, three clients diverged 0; tui core-test 823/964, shell-test 999/1002, behaviour --replay 20 seeds 0 failures, pane-test 180/181 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/gui/gui.zig | 11 ++++++++++- src/panes.zig | 4 +++- test/replicas.zig | 12 +++++++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/gui/gui.zig b/src/gui/gui.zig index a8816494..4f6a58c2 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1216,6 +1216,10 @@ const Client = struct { inbox: std.ArrayListUnmanaged(replica.Said) = .empty, taken: std.ArrayListUnmanaged(replica.Said) = .empty, ended: bool = false, + /// The size the window last posted while its view is not that size + /// yet (the session has not taken it, or speculation stopped at it): + /// posted once, not again each pass while it waits. + posted: ?@FieldType(pardes.Event, "resize") = null, fn deinit(cl: *Client) void { cl.pending.deinit(cl.gpa); @@ -1330,7 +1334,11 @@ const OwnView = struct { if (scrollRows(g, v.in, v.s.gpa)) v.s.client.?.link.dirty = true; if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.client.?.link.dirty = true; const geom = windowCells(g); - if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| v.in.post(ev); + const cl = v.s.client.?; + if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { + if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) v.in.post(ev); + cl.posted = ev.resize; + } else cl.posted = null; if (v.pointer) refreshPresentedPointer(g, v.in); runDemo(g, v.in, core); if (v.s.test_mode) { @@ -1424,6 +1432,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ g.hit_core = core; frame_probe = &core.frames; link.reset(r, &joined); + client.posted = null; client.ended = false; // ponytail: why it joined again is the window's title (and its // log) until a key, where a terminal's client draws it over its diff --git a/src/panes.zig b/src/panes.zig index 237693fa..e9c9b1d3 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -945,7 +945,9 @@ pub const Pane = struct { /// replica by its authority (the next delta says), on such an authority /// once the step's unit is out (`resizeDeferred`). pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { - if (tape.authorityOnly("resize a terminal")) return; + // A screen-state client's speculation does what its replay does + // (its selections, never the grid): it waits for no round trip. + if (!tape.screenState() and tape.authorityOnly("resize a terminal")) return; const state = pane.terminal orelse return; if (cols != pane.cols) for (0..pane.sel.len) |button| { pane.clearPointerSelection(button); diff --git a/test/replicas.zig b/test/replicas.zig index bd759b03..48ffe5d4 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -413,6 +413,8 @@ const Client = struct { wake_at: u64 = 0, drew: bool = false, resize: ?pardes.Event = null, + /// gui.zig `Client.posted`: a size posted once while it waits. + posted: ?@FieldType(pardes.Event, "resize") = null, resizes: u32 = 0, fn present(ctx: ?*anyopaque, _: *const pardes.Surface) void { @@ -453,9 +455,12 @@ const Client = struct { if (cl.kind != .window) return; cl.r.?.within(cl, own); if (cl.resize) |ev| { - cl.link.input(ev); - cl.resizes += 1; - } + if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) { + cl.link.input(ev); + cl.resizes += 1; + } + cl.posted = ev.resize; + } else cl.posted = null; cl.resize = null; } }; @@ -1050,6 +1055,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { if (c == 1) cl.link.test_diverge = 40; } cl.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 } }); -- cgit v1.3