diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 11:17:46 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 12:30:53 -0300 |
| commit | 20f08450aee2487809feb6442ec44e21d2436e5d (patch) | |
| tree | a6eda48cc7988b37019a98b914486cd04642e31a | |
| parent | 35b2c0efc6c43ba44640f4432d98734000f8887a (diff) | |
| parent | 23de206007ebae87007460afa993338781a03076 (diff) | |
| download | pardes-20f08450aee2487809feb6442ec44e21d2436e5d.tar.gz pardes-20f08450aee2487809feb6442ec44e21d2436e5d.zip | |
integration (the terminals' line, NOT the main line yet): a client that falls behind lets go and joins again, a join's reloads never dropped and only of the terminals written, on the first client and the pair: pardes-term-join (with pardes-term-lag under it) and pardes-merge35; three conflicts, each two sides adding at one place: the tests at the end of core/replica.zig (both kept), the soak's fields and its end's checks in test/replicas.zig (the images' and the far client's both kept); one name follows: Peer.writeLoop's local for a cut link was named last, which the first client's Peer.last now is (cut_off); tui core-test 861/1018 (157 skipped), shell-test 1058/1061, term-test 18/18, the window builds; the soak, screen state: diverged 0, unequal 0, unlisted 0; BYTES: seed 0 at 30 ms two clients diverged (client 2 at digest 29, client 3 at digest 2): the divergence the join's report left open, here on the merged session: this line stays beside the main one until that soak is clean
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | core/Term.zig | 13 | ||||
| -rw-r--r-- | core/panes.zig | 18 | ||||
| -rw-r--r-- | core/replica.zig | 418 | ||||
| -rw-r--r-- | core/tape.zig | 16 | ||||
| -rw-r--r-- | core/term/terminal.zig | 31 | ||||
| -rw-r--r-- | runtime/client.zig | 7 | ||||
| -rw-r--r-- | test/replicas.zig | 369 |
7 files changed, 765 insertions, 107 deletions
diff --git a/core/Term.zig b/core/Term.zig index aa05a68f..6ef9b0a5 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -65,6 +65,12 @@ fn the() *const iface.Ops { /// as it always has (`Parts` by name, then ghostty's snapshot). pub const State = struct { impl: *iface.State, + /// Written since its last reload (a feed, a reflow, a load: what cuts + /// its rows into pages), which a join reloads (panes.reloadTerminals, + /// the session's choice). One not holds the pages its last reload's + /// snapshot loads to, on every side, and so does a joiner loading the + /// same snapshot again from the dump. + written: bool = true, /// The emulator as its program has made it, for the replay digest. /// Under screen-state terminals the emulator is the authority's, and a @@ -167,7 +173,9 @@ pub fn reload(s: *State) !u64 { reloads.ns += dt; reloads.worst_ns = @max(reloads.worst_ns, dt); } - return the().reload(s.impl); + const hash = try the().reload(s.impl); + s.written = false; + return hash; } /// When its next kitty animation frame is due (ms on the core's clock), as @@ -180,6 +188,7 @@ pub fn due(s: *const State) ?u64 { /// history marked off from what the next shell prints. pub fn revive(s: *State) void { writes +%= 1; + s.written = true; the().revive(s.impl); } @@ -199,6 +208,7 @@ pub fn stop() void { /// went). pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { writes +%= 1; + s.written = true; return the().feed(s.impl, bytes, tracked, rows, erased); } @@ -229,6 +239,7 @@ pub fn follow(s: *State) void { /// Its grid reflowed, now or when `resizeDeferred` makes it. pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { writes +%= 1; + s.written = true; the().resize(s.impl, cols, rows, later); } diff --git a/core/panes.zig b/core/panes.zig index 1c103bd1..89d9f309 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -1126,16 +1126,20 @@ pub const Term = @import("Term.zig"); pub const positions_lost = "terminal edit position reset: out of memory"; /// At a join (Core's openView, rejoinView): under bytes, every live -/// terminal made again from its own snapshot, on every side alike, the -/// session included (Term.reload): an emulator loaded from a snapshot holds -/// its rows in other pages than one fed from its start, and ghostty prunes -/// its history a page at a time, so the joiner, loaded from the session's -/// dump made next, and the replicas there before it, would part. The +/// terminal written since its last reload made again from its own snapshot, +/// on every side alike, the session included (Term.reload): an emulator +/// loaded from a snapshot holds its rows in other pages than one fed from +/// its start, and ghostty prunes its history a page at a time, so the +/// joiner, loaded from the session's dump made next, and the replicas there +/// before it, would part. Which, the session says (`Term.State.written`, +/// taped): one written by nothing since holds the pages its last reload +/// made, on every side, and the joiner loads that snapshot again. The /// session's snapshot's hash is taped, and each replica's own compared /// with it: a check of the whole emulator at every join. pub fn reloadTerminals(p: *Pardes) void { if (tape.screenState()) return; for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { + if (!tape.value(.reload, written, .{state})) continue; // Its cells' size in pixels as a feed sets it (`feedOutput`): a // frontend's draw sets its own view's between steps (ansi.zig), a // window's other than a terminal's, and the snapshot holds it. @@ -1150,6 +1154,10 @@ fn sameHash(h: ?u64) ?u64 { return h; } +fn written(s: *Term.State) bool { + return s.written; +} + /// The sizes steps gave terminals (`Pane.resizeGrid`), made: between /// units, on an authority with screen-state replicas (replica.Peers.unit). pub fn resizeDeferred(p: *Pardes) void { diff --git a/core/replica.zig b/core/replica.zig index 781bd211..e1dc7dc1 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -963,9 +963,10 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - // A terminal's output is never taken so (the one rule): what it - // writes outside the copy is applied once, at its place, and much - // of it no digest covers (a colour set, a mode). + // A terminal's output, or a join's reloads, never taken so (the one + // rule): what it writes outside the copy is applied once, at its + // place, and much of it no digest covers (a colour set, a mode, the + // pages a reload remakes). if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and (r.t.screen_state or !tape.feedsTerminal(u.tape))) { @@ -1686,8 +1687,11 @@ pub const Peer = struct { /// What it is sent, not written yet, and what the writer writes now. out: std.ArrayListUnmanaged(u8) = .empty, sending: std.ArrayListUnmanaged(u8) = .empty, - limit: usize = 64 << 20, + /// What may wait in `out` before it is cut off (a test's less). + limit: usize = lag_max, closing: bool = false, + /// Cut off (`send`): the words why are the last it is sent, and its + /// view is kept for it (views.away), as for a bye's `again`. cut: bool = false, /// Its writer has ended (what it was sent, written). done: std.atomic.Value(bool) = .init(false), @@ -1714,7 +1718,7 @@ pub const Peer = struct { if (!writeAll(peer.fd, peer.welcome[0..peer.welcome_len])) return false; const io = peer.peers.io; peer.lock.lockUncancelable(io); - while (peer.far == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); + while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const far = peer.far; peer.lock.unlock(io); if (far orelse return false) return peer.farJoin(); @@ -1756,7 +1760,7 @@ pub const Peer = struct { if (peer.blobs.items.len > 0) { const io = peer.peers.io; peer.lock.lockUncancelable(io); - while (peer.want == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); + while (peer.want == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const want = peer.want; peer.lock.unlock(io); const bits = want orelse return false; @@ -1771,12 +1775,13 @@ pub const Peer = struct { return peer.z != null; } - /// Whether it is being let go (or was cut off). + /// Whether it is being let go. One cut off is still sent its join + /// whole, then the words why (`send`): it joins again after them. fn letting(peer: *Peer) bool { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); - return peer.closing or peer.cut; + return peer.closing; } /// One message into its stream's compressor. @@ -1827,8 +1832,9 @@ pub const Peer = struct { } /// `parts` queued for it, in order; never waits. A client whose queue - /// passes its limit is cut off: its link is shut down, and its reader - /// says it is gone. + /// passes its limit is cut off: what waits for it is let go and the + /// words why queued in its place, after which its writer ends its link + /// (`writeLoop`); it joins again from a dump, for its view (`leave`). fn send(peer: *Peer, parts: []const []const u8) void { const io = peer.peers.io; peer.lock.lockUncancelable(io); @@ -1848,7 +1854,13 @@ pub const Peer = struct { log.info("client {d} is {d} MB behind: cut off", .{ peer.id, n >> 20 }); peer.peers.cut += 1; peer.cut = true; - _ = libc.shutdown(peer.fd, 2); + peer.out.clearRetainingCapacity(); + var words: [48]u8 = undefined; + var msg: [64]u8 = undefined; + const word = wire.encodeServer(&msg, .{ .refused = std.fmt.bufPrint(&words, "{d} MB behind the session", .{n >> 20}) catch unreachable }) catch unreachable; + peer.out.appendSlice(peer.peers.gpa, word) catch { + _ = libc.shutdown(peer.fd, 2); + }; peer.cond.signal(io); return; } @@ -1909,17 +1921,17 @@ pub const Peer = struct { while (true) { peer.lock.lockUncancelable(io); while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); - if (peer.out.items.len == 0 or peer.cut) { + if (peer.out.items.len == 0) { peer.lock.unlock(io); return; } std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); - // The limit was for the dump and what is queued behind it. - peer.limit = lag_max; + // Cut off: the words why came last, and its link ends after them. + const cut_off = peer.cut; peer.lock.unlock(io); const ok = if (peer.z != null) peer.zWrite(peer.sending.items, .flush) else writeAll(peer.fd, peer.sending.items); peer.sending.clearRetainingCapacity(); - if (!ok) { + if (!ok or cut_off) { _ = libc.shutdown(peer.fd, 2); return; } @@ -2316,7 +2328,7 @@ pub const Peers = struct { core.gpa.free(bytes); return daemon.refuseReplica(fd, "out of memory"); }; - peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .limit = lag_max, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; + peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; ps.next_id +%= 1; if (ps.next_id == 0) ps.next_id = 1; // The session's digest as dumped, for the joiner to check its load by. @@ -2351,7 +2363,9 @@ pub const Peers = struct { ps.tellClients(); ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); - ps.closeViewOf(core, peer, peer.again); + // Cut off, it joins again after the words why (`send`); its reader + // has ended and no other thread sets `cut` now. + ps.closeViewOf(core, peer, peer.again or peer.cut); if (ps.count() == 0) core.unattended = ps.detached; ps.seq += 1; ps.unit(0, ps.seq); @@ -3074,6 +3088,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, } } +/// How far behind its session a client may fall before it lets its link go +/// and joins again from a dump (P32 (b)): near and far alike. +pub const behind_max_ms = 2_000; + /// A replica client's link to its session, the terminal's (tui.zig /// `runClient`) and the window's (gui.zig `runClient`): its replica, its socket, /// what the session said, and what it checks. Drawing is the frontend's. @@ -3137,6 +3155,17 @@ pub const Link = struct { /// moved on (its own motion), for PARDES_REPLICA_STATS. draws: u32 = 0, again: u32 = 0, + /// How far behind the session it is, ns: each unit's head carries the + /// session's monotonic clock as it was made; against this client's own, + /// less the smallest difference seen (the clocks' offset and the link's + /// quickest crossing). This machine's clock, the link's alone: no step + /// reads it and no digest holds it (`lags`). + behind: u64 = 0, + least: ?i64 = null, + /// No unit taken since it joined (`lags`). + fresh: bool = true, + /// How far behind it was as it let its link go (`rejoins` says so). + lagged: u64 = 0, fn time(c: *const Link) u64 { return c.now orelse nowNs(); @@ -3168,6 +3197,8 @@ pub const Link = struct { c.asked = false; c.mispredicted = 0; c.put_off = false; + c.behind = 0; + c.fresh = true; if (r.core().views[r.view]) |v| { c.yanks = v.yanks; c.pastes = v.pastes; @@ -3204,6 +3235,7 @@ pub const Link = struct { switch (msg) { .unit => |bytes| { defer std.heap.c_allocator.free(bytes); + if (c.quit or c.lags(bytes)) return; c.r.confirm(bytes); if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { c.test_diverge = 0; @@ -3263,6 +3295,25 @@ pub const Link = struct { }; } + /// The session's unit `bytes`, taken now: how far behind it is. Past + /// `behind_max_ms` it lets its link go (true), to join again from a dump. + /// The first unit after a join past it is taken as the link now (a + /// session's clock stood still while its machine slept; a dump that took + /// longer than the bound to come), never a let-go again at once. + fn lags(c: *Link, bytes: []const u8) bool { + const u = parseUnit(bytes) orelse return false; + const d = @as(i64, @intCast(c.time())) - u.mono_ns; + const max = behind_max_ms * std.time.ns_per_ms; + if (c.fresh and d - (c.least orelse d) > max) c.least = d; + c.fresh = false; + c.least = @min(c.least orelse d, d); + c.behind = @intCast(d - c.least.?); + if (c.behind <= max) return false; + c.lagged = c.behind; + c.quit = true; + return true; + } + /// A write to the session failed: it hung up (it cut this client off, /// lagging), as its reader will say. fn cut(c: *Link) void { @@ -3293,8 +3344,9 @@ pub const Link = struct { fn checked(c: *Link, theirs: u64) void { c.asked = false; // Not quiet now, the answer is let go: it covers nothing, and the - // next quiet asks again. - if (!c.r.quiet() or c.r.diverged != null) { + // next quiet asks again. Nor once its link is let go: a lag's let-go + // drops the units after it (`lags`), and the core is behind them. + if (c.quit or !c.r.quiet() or c.r.diverged != null) { c.changed = true; return; } @@ -3336,12 +3388,18 @@ pub const Link = struct { } /// The link ended: whether the client joins again, and why in its - /// notice (it diverged, or the session let it go to upgrade). + /// notice (it diverged, it fell too far behind, or the session let it + /// go: to upgrade, or cut off). pub fn rejoins(c: *Link) bool { if (c.r.diverged) |reason| { c.notify("joined again: this client diverged from the session ({s})", .{reason}); return true; } + if (c.lagged != 0) { + c.notify("joined again: {d}.{d} s behind", .{ c.lagged / std.time.ns_per_s, c.lagged / (std.time.ns_per_s / 10) % 10 }); + c.lagged = 0; + return true; + } if (c.refused) |words| { c.notify("joined again: {s}", .{words}); std.heap.c_allocator.free(words); @@ -4558,6 +4616,107 @@ fn firstOnPair(bytes: bool) !void { try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n); } +test "bytes: a join refused for want of a view reloads every terminal and moves nothing a digest covers: a client with a key on top reloads too, at its place, never taking that unit as moving nothing" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line of the program's\r\n"); + // Every view taken: the session's, then three clients'. + for (2..pardes.views.max + 1) |client| b.r.confirm((try b.a.openView(@intCast(client))).unit); + try b.output("and one since the last join\r\n"); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // A key of its own on top; a fifth client refused, its step reloading + // every terminal in the unit of the pump the others take next; the key + // confirmed; the program prints on. + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + const before = pardes.Term.reloads.n; + try std.testing.expect(try b.a.join(pardes.views.max + 1, null) == null); + const session = pardes.Term.reloads.n - before; + try std.testing.expect(session > 0); + b.a.pump(); + b.r.confirm((try b.a.pending()).?); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try b.output("and on\r\n"); + try std.testing.expectEqual(2 * session, pardes.Term.reloads.n - before); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a join reloads only the terminals written since their last reload: one idle since the last join is reloaded on no side, and through a prune of both every side holds the session's terminals, the joiner too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + b.r.confirm(try b.a.local(.{ .command = "Term" })); + b.r.settle(); + const second: pardes.Pane.Id = for (b.a.core.panes, 0..) |slot, id| { + if (id != b.shell.index() and (slot orelse continue).terminal != null) break .at(id); + } else return error.NoTerminal; + const both = [_]pardes.Pane.Id{ b.shell, second }; + // Both written, and a join reloads both. + for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = "written\r\n" } }); + b.r.confirm((try b.a.pending()).?); + const first = (try b.a.join(2, null)).?; + gpa.free(first.dump); + b.r.confirm(first.unit); + // The shell alone written since: the next join reloads it alone, on + // every side; the joiner loads the other's snapshot as it was. + try b.output("the shell's\r\n"); + const before = pardes.Term.reloads.n; + const joined = (try b.a.join(3, null)).?; + defer gpa.free(joined.dump); + try std.testing.expectEqual(1, pardes.Term.reloads.n - before); + b.r.confirm(joined.unit); + try std.testing.expectEqual(2, pardes.Term.reloads.n - before); + const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + // Output into both until each has pruned its history (whole pages, by + // the history of its pages), a unit every few reads. + var read: std.ArrayListUnmanaged(u8) = .empty; + defer read.deinit(gpa); + const lines = 40_000; + var n: usize = 0; + while (n < lines) : (n += 100) { + read.clearRetainingCapacity(); + for (n..n + 100) |i| try read.print(gpa, "\x1b[3{d}m{d}\x1b[0m line\r\n", .{ i % 8, i }); + for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = read.items } }); + if (n % 2000 == 1900) { + const u = (try b.a.pending()).?; + b.r.confirm(u); + late.confirm(u); + } + } + if (try b.a.pending()) |u| { + b.r.confirm(u); + late.confirm(u); + } + for (both) |id| try std.testing.expect(pardes.Term.grid(b.a.core.panes[id.index()].?.terminal).total < lines); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try agrees(b.a, late); + try sameTerminals(b.a, late); + // And a join after: both written, both reloaded, every hash compared. + const left = try b.a.leave(2, false); + b.r.confirm(left); + late.confirm(left); + const third = (try b.a.join(4, null)).?; + gpa.free(third.dump); + b.r.confirm(third.unit); + late.confirm(third.unit); + try agrees(b.a, b.r); + try agrees(b.a, late); +} + test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -5143,6 +5302,212 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it try agrees(a, back); } +test "a client cut off for what it left unread is told why and joins again for its view, kept for it meanwhile: it loads the session's dump and agrees" { + // A session's side of its clients' links in memory (`Peers.threads` + // false, the soak's): a connection handed to it and joined at its next + // boundary, the replica loaded from what its writer would write (the + // welcome, the dump with its blobs in place); and what it queued for one, + // down its link in order, the link's end after it if it was cut off. + const MemoryLinks = struct { + fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int) !struct { r: *Replica, peer: *Peer } { + const gpa = std.testing.allocator; + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + fd.* = fds[1]; + ps.handed(fds[0], view); + ps.boundary(core); + const peer = for (ps.list) |slot| { + if (slot) |p| if (p.fd == fds[0]) break p; + } else return error.Refused; + const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const w = (try wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (peer.blobs.items) |b| { + try whole.appendSlice(gpa, peer.dump[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, peer.dump[pos..]); + var word: [16]u8 = undefined; + const far = try wire.encodeClient(&word, .{ .far = false }); + _ = peer.take(far[0], far[wire.header_len..]); + ps.post(.{ .joined = peer }); + const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); + if (!r.loaded(w.digest)) return error.LoadedAnother; + return .{ .r = r, .peer = peer }; + } + + fn down(peer: *Peer, link: *Link) !void { + var at: usize = 0; + while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) { + link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) { + .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) }, + .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) }, + else => return error.UnexpectedFrame, + }); + } + peer.out.clearRetainingCapacity(); + if (!peer.cut) return; + link.quit = true; + link.gone = true; + } + }; + const gpa = std.testing.allocator; + const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer core.deinit(); + core.host = TestHost.host(); + try core.pump(core.host); + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; + defer ps.deinit(); + defer ps.dropAll(core); + var fd: c_int = -1; + const first = try MemoryLinks.join(&ps, core, null, &fd); + defer _ = libc.close(fd); + var link: Link = .{ .r = first.r, .fd = fd }; + defer link.deinit(gpa); + const view = first.peer.view; + // The session's own input, taken by the client. + core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + try core.pump(core.host); + ps.boundary(core); + try MemoryLinks.down(first.peer, &link); + try std.testing.expect(!link.quit and first.r.diverged == null); + // Its link stalls; the session goes on, and what waits for it passes + // the bound: it is cut off. + first.peer.limit = 16 << 10; + const text: [6000]u8 = @splat('t'); + for (0..3) |_| { + core.update(.{ .paste = &text }); + try core.pump(core.host); + ps.boundary(core); + } + try std.testing.expect(first.peer.cut); + try std.testing.expectEqual(@as(u32, 1), ps.cut); + try MemoryLinks.down(first.peer, &link); + try std.testing.expect(link.quit); + // It was told why, and joins again (as a divergence's client does)... + try std.testing.expect(link.rejoins()); + try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); + // ...once its old link's end is heard: its view kept for it meanwhile. + ps.post(.{ .gone = first.peer }); + ps.boundary(core); + try std.testing.expect(pardes.views.isAway(core, view)); + first.r.deinit(); + _ = libc.close(fd); + const back = try MemoryLinks.join(&ps, core, view, &fd); + defer back.r.deinit(); + try std.testing.expectEqual(view, back.peer.view); + link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view, .gmtoff = 0, .dump = &.{} }); + core.update(.{ .paste = "back" }); + try core.pump(core.host); + ps.boundary(core); + try MemoryLinks.down(back.peer, &link); + try std.testing.expect(!link.quit and back.r.diverged == null and back.r.quiet()); + try std.testing.expectEqual(tape.digestOf(core), back.r.digest()); +} + +test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + 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); + }; + var link: Link = .{ .r = r, .fd = fds[1] }; + defer link.deinit(gpa); + const Late = struct { + // A unit the session made at `made` ms on its clock, taken at `at` + // ms on the client's. + fn take(l: *Link, from: *Authority, made: i64, at: u64) !void { + const u = try std.heap.c_allocator.dupe(u8, try from.local(.tick)); + std.mem.writeInt(i64, u[14..22], made * std.time.ns_per_ms, .little); + l.now = at * std.time.ns_per_ms; + l.take(.{ .unit = u }); + } + }; + // The client's clock 5 s on from the session's, the link 100 ms: the + // second unit 1.9 s later than the first, the third 2.1 s. + try Late.take(&link, a, 0, 5_100); + try Late.take(&link, a, 1_000, 8_000); + try std.testing.expect(!link.quit); + try Late.take(&link, a, 1_100, 8_300); + try std.testing.expect(link.quit); + // A check answered after it let go, behind the unit it let go of: its + // core is behind on purpose, no divergence. + link.take(.{ .checked = digestOf(a) +% 1 }); + try std.testing.expect(r.diverged == null); + try std.testing.expect(link.rejoins()); + try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice()); + try std.testing.expect(!link.rejoins()); + r.deinit(); + // Joined again, its first unit 3 s later than any before (the session's + // clock stood still, its machine asleep; or the dump took that long): + // taken as the link now, not let go of again. + const back = try joinedNow(a, 1, 0); + defer back.deinit(); + link.reset(back, &.{ .fd = fds[1], .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = &.{} }); + try Late.take(&link, a, 2_000, 10_100); + try Late.take(&link, a, 2_100, 10_250); + try std.testing.expect(!link.quit and back.diverged == null); +} + +test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and ends the link" { + const gpa = std.testing.allocator; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io }; + defer ps.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 _ = libc.close(fds[1]); + const peer = try gpa.create(Peer); + peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = 0, .dump_gpa = gpa, .far = false, .limit = 256 << 10 }; + peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len; + peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); + defer ps.letGo(peer); + // Units its client does not read: the socket fills, the writer waits + // on it with a batch in hand, and the rest queues up to the bound. + const unit: [16 << 10]u8 = @splat('u'); + const head = wire.header(@backingInt(wire.ServerTag.unit), unit.len); + // The first taken in hand. + peer.send(&.{ &head, &unit }); + while (true) { + peer.lock.lockUncancelable(std.testing.io); + const taken = peer.out.items.len == 0; + peer.lock.unlock(std.testing.io); + if (taken) break; + std.Thread.yield() catch {}; + } + var sent: u32 = 1; + while (!peer.cut) : (sent += 1) peer.send(&.{ &head, &unit }); + const Heard = struct { + units: u32 = 0, + last: ?[]u8 = null, + fn post(h: *@This(), msg: Said) bool { + switch (msg) { + .unit => |b| { + std.heap.c_allocator.free(b); + h.units += 1; + }, + .refused => |words| h.last = words, + else => return false, + } + return true; + } + }; + var heard: Heard = .{}; + var rest: Framer = .{}; + defer rest.deinit(gpa); + readLink(gpa, fds[1], &rest, &heard, Heard.post); + const words = heard.last orelse return error.NotTold; + defer std.heap.c_allocator.free(words); + try std.testing.expectEqualStrings("0 MB behind the session", words); + try std.testing.expect(heard.units > 0 and heard.units < sent); +} + test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); @@ -6357,25 +6722,28 @@ test "an idle client's check answered covers the units that came while it was as _ = libc.close(fd); }; var c: Link = .{ .r = r, .fd = fds[0], .now = std.time.ns_per_s }; + // Each unit made as the client takes it, on its clock (Link.behind). const unit = struct { - fn of(au: *Authority) !Said { - return .{ .unit = try std.heap.c_allocator.dupe(u8, try au.local(.tick)) }; + fn of(au: *Authority, l: *const Link) !Said { + const u = try std.heap.c_allocator.dupe(u8, try au.local(.tick)); + std.mem.writeInt(i64, u[14..22], @intCast(l.now.?), .little); + return .{ .unit = u }; } }.of; // Something changed, 300 ms quiet since its last input: asked. - c.take(try unit(a)); + c.take(try unit(a, &c)); try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(c.asked); // The session's pump for it (a unit), then the answer: agreed, and // nothing to ask after it however long it stays quiet. - c.take(try unit(a)); + c.take(try unit(a, &c)); c.take(.{ .checked = digestOf(a) }); try std.testing.expect(!c.asked and c.r.diverged == null); c.now.? += 10 * std.time.ns_per_s; try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(!c.asked); // A unit after it is a change again. - c.take(try unit(a)); + c.take(try unit(a, &c)); c.now.? += std.time.ns_per_s; _ = c.quietCheck(); try std.testing.expect(c.asked); diff --git a/core/tape.zig b/core/tape.zig index 7f28621e..88a7047b 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -132,9 +132,9 @@ pub const Site = enum(u16) { /// What a call into a kind did (Kind.Outcome), and a kind's pane's /// tag prefix: the authority's, whose core alone runs the kind. addon, - /// The hash of a terminal's snapshot as the session reloaded it at a - /// join (panes.reloadTerminals), which every replica's own reload - /// compares. + /// Whether the session reloads a terminal at a join (written since its + /// last reload), then the hash of its snapshot as it did + /// (panes.reloadTerminals), which every replica's own reload compares. reload, /// A kitty image's medium as a terminal's emulator read it (a file, a /// temporary file, shared memory: Term.media), its bytes or its failure. @@ -1493,15 +1493,19 @@ pub fn endSpeculation(t: *Tape) bool { /// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). pub const unit_max = 1 << 20; -/// Whether a unit feeds a terminal its program's output (a pty's read; an -/// input kept by hash is taken to): never taken as moving nothing (the -/// replica engine's one rule, core/replica.zig `confirm`). +/// Whether a unit writes a terminal's emulator: feeds one its program's +/// output (a pty's read; an input kept by hash is taken to), or reloads +/// every one at a join (`Site.reload`; a join refused too, which moves +/// nothing a digest covers): never taken as moving nothing (the replica +/// engine's one rule, core/replica.zig `confirm`). pub fn feedsTerminal(bytes: []const u8) bool { const Tag = std.meta.Tag(Input); const EventTag = std.meta.Tag(pardes.Event); + const reload: u16 = @as(u16, host_fns.len) + @backingInt(Site.reload); var r: walk.Reader = .{ .bytes = bytes }; while (nextRecord(&r)) |rec| switch (rec.kind) { .blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true, + .host => if (rec.payload.len >= 2 and std.mem.bytesToValue(u16, rec.payload[0..2]) == reload) return true, .input => { if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue; if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue; diff --git a/core/term/terminal.zig b/core/term/terminal.zig index e57193a6..1673a3d8 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -1792,3 +1792,34 @@ test "a join at a cut: every side reloaded from its own snapshot holds the same // another terminal once heavy colour has pruned pages cut otherwise. try std.testing.expectEqual(2, heavy_apart); } + +test "wide characters filling a scrollback past its limit, reflowed: its snapshot loads to the same snapshot and hash, and goes on as the same terminal through more bytes and reflows" { + // The soak's `cat` (test/replicas.zig): source lines, one in a few + // hundred with wide characters (CJK, box drawing, ambiguous symbols), + // a full scrollback pruned a page at a time, reflowed at odd widths + // where a wide character meets the right edge. + const gpa = std.testing.allocator; + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + const wide = " try writeText(notes, \"# Fallback faces and rules\\n\\n| name | glyphs |\\n|------|--------|\\n| cjk | \u{754C}\u{9762}\u{5B57} |\\n| sym | \u{222E} \u{2260} \u{2605} |\\n\\n\u{250C}\u{2500}\u{2500}\u{252C}\u{2500}\u{2500}\u{2510}\\n\u{2502} a\u{2502} b\u{2502}\\n\u{2514}\u{2500}\u{2500}\u{2534}\u{2500}\u{2500}\u{2518}\\n\");"; + for (0..30000) |i| { + if (i % 7 == 3) try out.writer.print("{s}\r\n", .{wide}) else try out.writer.print("{s} {d}\r\n", .{ " const line = std.fmt.bufPrint(&buf, \"{d}\", .{i}) catch continue;"[0 .. 8 + i % 60], i }); + } + const bytes = out.written(); + const stops: [2]usize = .{ bytes.len / 3, 2 * bytes.len / 3 }; + const first = try openKeeping(gpa, 121, 40, 1 << 20); + defer close(first); + feedReflowing(first, bytes, 0, bytes.len / 2, stops); + const snap = try snapshotOf(gpa, first); + defer gpa.free(snap); + const loaded = try load(gpa, snap, &parts(first)); + defer close(loaded); + const again = try snapshotOf(gpa, loaded); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, snap, again); + try std.testing.expectEqual(joinHash(snap), try reload(first)); + try expectSame(gpa, first, loaded); + feedReflowing(first, bytes, bytes.len / 2, bytes.len, stops); + feedReflowing(loaded, bytes, bytes.len / 2, bytes.len, stops); + try expectSame(gpa, first, loaded); +} diff --git a/runtime/client.zig b/runtime/client.zig index 1314d3fb..7c0bcb7f 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -138,8 +138,9 @@ pub fn Loop(comptime Frontend: type) type { l.link.take(msg); } - /// A join a pass: the first, and one after the replica diverged or - /// the session let it go to upgrade; the frontend stays as it is. + /// A join a pass: the first, and one after the replica diverged, fell + /// too far behind (replica.behind_max_ms) or the session let it go + /// (to upgrade, or cut off); the frontend stays as it is. pub fn run(l: *L, s: *Start) !Ended { const link = &l.link; while (true) { @@ -152,7 +153,7 @@ pub fn Loop(comptime Frontend: type) type { l.after(); } if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null); + if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null or link.lagged != 0); // The link's reader ends with the link, posting as it goes: // what it posted is let go until it has (a terminal's queue // is bounded: a reader blocked on it would never end). diff --git a/test/replicas.zig b/test/replicas.zig index 7bf79055..126b0410 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -13,8 +13,8 @@ //! are refused until one is let go. //! //! Terminals cross as screen state (core/term/screen_state.zig): the session's -//! shell pane runs a full-screen program and then a `yes` flood (`--flood` -//! MB of it) while the clients type, its output stepped by the authority +//! shell pane runs a full-screen program and then a flood (`--flood` MB of +//! `yes`, then as much of a `cat` of source text) while the clients type, its output stepped by the authority //! and sent to each replica as deltas, once a frame and before any input //! the authority steps, each replica acknowledging them over its link and //! asking for the rows it scrolls back into and does not hold. @@ -178,6 +178,10 @@ const Kind = enum { /// session's down it. up, blob, + /// The session's words in a client's stream (a cut's: `Peer.send`). + word, + /// Room in the far link again: its Peer's writer goes on (`Soak.write`). + drain, }; const Msg = struct { @@ -201,6 +205,8 @@ const Msg = struct { const Link = struct { last: u64 = 0, + /// When what was sent down it before has crossed (`Net.cross`). + free: u64 = 0, /// When a message sent at `now` arrives: half the RTT, jitter on top, /// and never before the one sent ahead of it (a stream keeps order). fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 { @@ -272,6 +278,26 @@ const Totals = struct { detach_words: u64 = 0, /// Panes of each plain kind the session opened (image, life). kind_panes: [3]u64 = @splat(0), + /// The far client (`throttle_*`): its joins from a dump, the time between + /// two from the flood's start on, and from the flood's end to the first + /// frame of its final screen (us); the most the session's queue for it + /// held (bytes); the clients the session cut off. + far_joins: u64 = 0, + far_gaps: std.ArrayListUnmanaged(u64) = .empty, + far_final: std.ArrayListUnmanaged(u64) = .empty, + queue_max: u64 = 0, + cut: u64 = 0, + /// How far behind the session each fell at most (Link.behind, ns), and + /// how often it let its link go for it: the far client, and the others. + far_behind: u64 = 0, + far_lags: u64 = 0, + near_behind: u64 = 0, + near_lags: u64 = 0, + /// What a join costs the replicas already there, ns of this process's + /// clock: the session's join step (its reloads and its dump), and each + /// client's unit that reloaded its terminals. + join_session_ns: std.ArrayListUnmanaged(u64) = .empty, + join_client_ns: std.ArrayListUnmanaged(u64) = .empty, fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -307,7 +333,7 @@ const Totals = struct { /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its /// wheel; a yank to the system clipboard and a paste from it; now and /// then a client's Detach. -fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script) pardes.Event { +fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; if (script.at < script.n) { @@ -351,8 +377,9 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const 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", + // its terminal's: none here). Not the far client's: the scene + // waits for its screen after the flood. + 12 => if (random.uintLessThan(u8, 4) == 0 and !far) "Detach" else "Undo", // The system clipboard, the client's own frontend's (client.zig // `asks`): a yank of the selection to it, a paste from it. 13 => "ClipYank", @@ -509,6 +536,17 @@ const Client = struct { distrusted: pardes.Addon.Distrusted = .{}, /// What stopped its inputs as last judged (`judgeStops`). stops: @FieldType(replica.Stats, "stops") = @splat(.{}), + /// Its Peer's writer's (`Soak.write`): the batch swapped out of the + /// session's queue for it (the Peers' allocator's), how much of it went + /// down the link, whether a cut's words end it, a wake asked for room; + /// how much of the queue carries the soak's clock (`Soak.stamp`). + sending: std.ArrayListUnmanaged(u8) = .empty, + at: usize = 0, + last: bool = false, + draining: bool = false, + marked: usize = 0, + /// The session's unit its last join's dump came after. + join_seq: u32 = 0, /// Where it is (`clients[c]`), the net its wakes go through, and the /// soak's time now. c: usize = 0, @@ -614,6 +652,17 @@ const Net = struct { jitter: u64, up: [8]Link = @splat(.{}), down: [8]Link = @splat(.{}), + /// The far client, whose link is `throttle_*`'s. + throttled: ?usize = null, + + /// When `bytes` sent at `now` down or up client `c`'s link `l` arrive: + /// the far one's cross at its rate as the far stream's zstd at `level` + /// makes them, after what was sent before them, then its delay. + fn cross(net: *Net, l: *Link, c: usize, now: u64, bytes: []const u8, level: c_int) u64 { + if (net.throttled != @as(?usize, c)) return l.arrive(net.random, now, net.one_way, net.jitter); + l.free = @max(now, l.free) + zstdLen(bytes, level) * std.time.us_per_s / throttle_rate; + return l.arrive(net.random, l.free, throttle_one_way, throttle_one_way / 20); + } fn send(net: *Net, m: Msg) !void { var mm = m; @@ -624,10 +673,32 @@ const Net = struct { /// Down client `c`'s link (the session's stream to it), `bytes` its. fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void { - try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); + try net.send(.{ .at = net.cross(&net.down[c], c, now, bytes, if (kind == .dump) 6 else 3), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); } }; +/// P32's far case: a link of 1 Mbit/s and 200 ms each way, what it carries +/// counted as the far stream's zstd makes it (core/replica.zig `zstd`), the +/// third client's (it joins before the flood); at most `throttle_window` of it ahead of +/// what has crossed (its sockets' and the route's buffers), the rest in the +/// session's queue for it, as a writer blocked on its socket leaves it. +const throttle_rate: u64 = 125_000; +const throttle_one_way: u64 = 200_000; +const throttle_window: u64 = 64 << 10; + +extern fn ZSTD_compressBound(n: usize) usize; +extern fn ZSTD_compress(dst: [*]u8, cap: usize, src: [*]const u8, n: usize, level: c_int) usize; +extern fn ZSTD_isError(code: usize) c_uint; + +/// `bytes` through zstd at `level`, alone: the far stream's (3, and 6 for a +/// join's), which a message shares with those before it. +fn zstdLen(bytes: []const u8, level: c_int) u64 { + const room = gpa.alloc(u8, ZSTD_compressBound(bytes.len)) catch return bytes.len; + defer gpa.free(room); + const n = ZSTD_compress(room.ptr, room.len, bytes.ptr, bytes.len, level); + return if (ZSTD_isError(n) != 0) bytes.len else n; +} + /// What client `c` wrote to its socket since (its inputs and their stamps, /// its terminal messages, a check asked, its bye), read off the session's /// end, a frame a message up its link: the session's Peer takes each as it @@ -642,7 +713,7 @@ fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { } var at: usize = 0; while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { - try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); + try net.send(.{ .at = net.cross(&net.up[c], c, now, cl.got.items[at..][0..f.total], 3), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); } std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]); cl.got.shrinkRetainingCapacity(cl.got.items.len - at); @@ -699,9 +770,12 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, const r = cl.r.?; const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(link.fd, r.diverged != null); + if (!link.gone) replica.bye(link.fd, r.diverged != null or link.lagged != 0); try drain(cl, c, net, now); cl.live = 0; + if (link.lagged != 0) { + if (net.throttled == @as(?usize, c)) totals.far_lags += 1 else totals.near_lags += 1; + } if (r.diverged) |why| { if (link.put_off) totals.rejoined += 1 else { totals.divergences += 1; @@ -711,7 +785,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, if (link.rejoins()) { cl.back = r.view; cl.dialling = true; - return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); r.deinit(); @@ -756,7 +830,9 @@ const Soak = struct { /// What the shell's program prints (`.output`). tui: []const u8, shell_session: []const u8, - yes: []const u8, + /// The flood: `yes`, then a `cat` (its first `yes_len` bytes `yes`). + flood: []const u8, + yes_len: usize, l: *SessionLoop = undefined, /// What failed inside the loop (its wait returns nothing): the run's. err: ?anyerror = null, @@ -805,9 +881,13 @@ const Soak = struct { /// The temporary file and the shared memory object an image was shown /// by (`images`): gone once the session read them. media: *const Media = undefined, - /// A Peer's queue, swapped out as its writer swaps it (the Peers' - /// allocator's). - sending: std.ArrayListUnmanaged(u8) = .empty, + /// The session's unit with the flood's last bytes; the far client's + /// last join, and whether it has shown the final screen; a join's step + /// at worst. + flood_seq: u32 = 0, + far_joined: u64 = 0, + far_final: bool = false, + join_worst: u64 = 0, fn of(ctx: ?*anyopaque) *Soak { return @ptrCast(@alignCast(ctx.?)); @@ -914,13 +994,13 @@ const Soak = struct { cl.loop.link.check = null; cl.loop.link.deinit(gpa); } + cl.sending.deinit(s.l.peers.gpa); } while (s.net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); for (s.echo.items) |e| gpa.free(e.bytes); s.echo.deinit(gpa); s.versions.deinit(gpa); - s.sending.deinit(s.l.peers.gpa); } /// The tty's own boot (a raw shell, a text pane under it), then three @@ -1034,6 +1114,15 @@ const Soak = struct { cl.peer = peer; cl.shut = false; cl.read_done = false; + cl.join_seq = ps.seq; + cl.sending.clearRetainingCapacity(); + cl.at = 0; + cl.last = false; + cl.marked = 0; + // What the join cost the session's step (Peers.join's measure). + s.join_worst = @max(s.join_worst, ps.join_ns); + try s.totals.join_session_ns.append(gpa, ps.join_ns); + ps.join_ns = 0; cl.gen += 1; cl.id = welcome.client; cl.view = welcome.view.index(); @@ -1048,49 +1137,19 @@ const Soak = struct { cl.shut = true; }; s.detach_view = null; - const flooding = now >= flood_at and s.flood_end == 0; + // The unit with the flood's last bytes: what the far client's final + // screen shows. + if (s.flood_end != 0 and s.flood_seq == 0) s.flood_seq = ps.seq; for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { - if (peer.cut) cl.shut = true; - const io = ps.io; - peer.lock.lockUncancelable(io); - std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &s.sending); - peer.lock.unlock(io); - defer s.sending.clearRetainingCapacity(); if (cl.shut) { - if (!cl.read_done) { - cl.read_done = true; - ps.post(.{ .gone = peer }); - try net.toClient(c, now, .gone, cl.gen, &.{}); - } + // What was queued for it is let go with its link. + peer.out.clearRetainingCapacity(); + try s.shut(cl, c); continue; } - var at: usize = 0; - while (try pardes.wire.framed(s.sending.items[at..])) |f| : (at += f.total) { - const tag = std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame; - switch (tag) { - .unit => { - s.totals.unit_bytes += f.payload.len; - if (flooding) s.totals.flood_unit_bytes += f.payload.len; - try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); - }, - .screen => { - if (f.payload[5] == 1) { - s.totals.deltas += 1; - s.totals.delta_bytes += f.payload.len; - if (flooding) s.totals.flood_delta_bytes += f.payload.len; - } else s.totals.filled_bytes += f.payload.len; - try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); - }, - .check => { - const d = try gpa.alloc(u8, 8); - std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); - try net.toClient(c, now, .checked, cl.gen, d); - }, - .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), - else => return error.UnexpectedFrame, - } - } - if (at != s.sending.items.len) return error.TornFrame; + s.stamp(cl, peer); + if (net.throttled == @as(?usize, c)) s.totals.queue_max = @max(s.totals.queue_max, peer.out.items.len); + try s.write(cl, c); }; // The kinds' panes it has opened, each counted once. for (core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen) { @@ -1105,6 +1164,97 @@ const Soak = struct { } } + /// The units the session queued for client `cl` since, their heads + /// carrying the soak's clock, the session's here (its host's `now`): + /// what the client's lag is measured by. Its replica guesses no clock + /// from them (`joined`: in process, both read one). + fn stamp(s: *Soak, cl: *Client, peer: *replica.Peer) void { + const out = peer.out.items; + var at = cl.marked; + while (pardes.wire.framed(out[at..]) catch null) |f| : (at += f.total) { + if (f.tag != @backingInt(pardes.wire.ServerTag.unit)) continue; + const head = at + f.total - f.payload.len; + std.mem.writeInt(i64, out[head + 14 ..][0..8], @intCast(s.now * std.time.ns_per_us), .little); + } + cl.marked = at; + } + + /// Client `c`'s Peer's writer (Peer.writeLoop's): the session's queue + /// for it swapped out a batch at a time and handed down its link, a + /// frame a message. The far link takes no more than `throttle_window` + /// ahead of what has crossed: the rest waits in the queue, as it does + /// for a writer blocked on its socket, until room comes (`.drain`). A + /// cut's words end a batch, and its link after them. + fn write(s: *Soak, cl: *Client, c: usize) !void { + const peer = cl.peer orelse return; + const net = s.net; + const window_us = throttle_window * std.time.us_per_s / throttle_rate; + while (true) { + if (cl.at == cl.sending.items.len) { + cl.sending.clearRetainingCapacity(); + cl.at = 0; + if (cl.last) return s.shut(cl, c); + const io = s.l.peers.io; + peer.lock.lockUncancelable(io); + std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); + cl.last = peer.cut; + peer.lock.unlock(io); + cl.marked = 0; + if (cl.sending.items.len == 0) return; + } + if (net.throttled == @as(?usize, c) and net.down[c].free > s.now + window_us) { + if (!cl.draining) try net.send(.{ .at = net.down[c].free - window_us, .n = 0, .kind = .drain, .who = @intCast(c + 1), .bytes = &.{} }); + cl.draining = true; + return; + } + const f = (try pardes.wire.framed(cl.sending.items[cl.at..])) orelse return error.TornFrame; + cl.at += f.total; + try s.forward(cl, c, f); + } + } + + /// One frame of client `c`'s stream, down its link. + fn forward(s: *Soak, cl: *Client, c: usize, f: pardes.wire.Framed) !void { + const net = s.net; + const now = s.now; + const flooding = now >= flood_at and s.flood_end == 0; + switch (std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame) { + .unit => { + s.totals.unit_bytes += f.payload.len; + if (flooding) s.totals.flood_unit_bytes += f.payload.len; + try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .screen => { + if (f.payload[5] == 1) { + s.totals.deltas += 1; + s.totals.delta_bytes += f.payload.len; + if (flooding) s.totals.flood_delta_bytes += f.payload.len; + } else s.totals.filled_bytes += f.payload.len; + try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .check => { + const d = try gpa.alloc(u8, 8); + std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); + try net.toClient(c, now, .checked, cl.gen, d); + }, + .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), + .refused => try net.toClient(c, now, .word, cl.gen, try gpa.dupe(u8, (try pardes.wire.decodeServer(f.tag, f.payload)).refused)), + else => return error.UnexpectedFrame, + } + } + + /// Client `c`'s link ended at the session's side (a Detach typed in its + /// view, or the words of a cut sent): it hears its end and nothing after, + /// and its reader's end is said (the next boundary lets it go). + fn shut(s: *Soak, cl: *Client, c: usize) !void { + cl.shut = true; + cl.last = false; + if (cl.read_done) return; + cl.read_done = true; + s.l.peers.post(.{ .gone = cl.peer.? }); + try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); + } + /// Each terminal at its version as the session's screen shows it now /// (after a flush: `Peers.flushed`). fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { @@ -1173,7 +1323,7 @@ const Soak = struct { // tape is stepped in it between its steps (tape.enter's check), // and no rollback epoch's trees are held. const in_client = switch (m.kind) { - .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => true, + .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => true, .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), else => false, }; @@ -1212,15 +1362,17 @@ const Soak = struct { if (s.program.at == s.program.bytes.len) { s.program = .{ .bytes = switch (m.who) { 0 => s.tui, - 1 => s.yes, + 1 => s.flood, else => s.shell_session, } }; } const k = @min(s.program.bytes.len - s.program.at, if (m.who == 1) @as(usize, 4096) else 700); const chunk = s.program.bytes[s.program.at..][0..k]; s.program.at += k; + // `yes` a read every 450 us, the `cat` a read every 4 ms + // (1 MB/s: the far link falls behind, many seconds long). if (s.program.at < s.program.bytes.len) - try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) + try net.send(.{ .at = m.at + if (m.who != 1) @as(u64, 3_000) else if (s.program.at < s.yes_len) @as(u64, 450) else 4_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) else if (m.who == 1) s.flood_end = m.at; core.update(.{ .output = .{ .pane = .at(s.shell), .bytes = chunk } }); took_output = true; @@ -1241,6 +1393,12 @@ const Soak = struct { return false; } }, + // Room in the far link: its Peer's writer goes on. + .drain => { + cl.draining = false; + try s.write(cl, c); + if (s.l.peers.urgent.swap(false, .acq_rel)) return false; + }, // A client's connection, handed over by the daemon (tui.zig // `.replica`): joined at the session's next step boundary, // on a socket pair of its own. @@ -1323,7 +1481,7 @@ const Soak = struct { cl.r = null; } cl.tries += 1; - if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(s.random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { + if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.cross(&net.up[c], c, m.at + 500_000, &.{}, 3), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { // Given up on: its keys are never typed. cl.dialling = false; if (cl.left > 0) s.typing -= 1; @@ -1331,7 +1489,7 @@ const Soak = struct { } }, .dump => try s.joined(cl, c, m), - .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => { + .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => { if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1350,7 +1508,7 @@ const Soak = struct { switch (m.kind) { .input => { var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script, net.throttled == @as(?usize, c)); cl.loop.input(ev); cl.left -= 1; if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { @@ -1359,7 +1517,21 @@ const Soak = struct { if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); } }, - .to_replica => cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .to_replica => { + if (net.throttled == @as(?usize, c) and !s.far_final and s.flood_seq != 0) if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0 and u.seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + }; + // A join's reloads on a replica there before it: + // what its unit cost, on this process's clock. + const reloads = pardes.Term.reloads.n; + const t0 = monoNs(); + cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }); + if (pardes.Term.reloads.n != reloads) try s.totals.join_client_ns.append(gpa, monoNs() - t0); + const behind = if (net.throttled == @as(?usize, c)) &s.totals.far_behind else &s.totals.near_behind; + behind.* = @max(behind.*, cl.loop.link.behind); + }, + .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), .screen_down => { const pane = m.bytes[0]; @@ -1408,7 +1580,7 @@ const Soak = struct { const core = s.l.core; s.clock(); var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script, false); core.toView(.at(0)); core.update(ev); s.own_left -= 1; @@ -1429,6 +1601,18 @@ const Soak = struct { } 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; + // In process: its clock reads are the session's machine's, and the + // units' heads carry the soak's clock (`stamp`). + rp.guess = false; + if (s.net.throttled == @as(?usize, c)) { + s.totals.far_joins += 1; + if (m.at >= flood_at and s.far_joined != 0) try s.totals.far_gaps.append(gpa, m.at - s.far_joined); + s.far_joined = m.at; + if (!s.far_final and s.flood_seq != 0 and cl.join_seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + } + } // Its terminals its own emulators, fed what the units carry. if (bytes_kind) { rp.t.screen_state = false; @@ -1471,7 +1655,9 @@ const Soak = struct { totals.flood_us += s.flood_end -| flood_at; for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); - if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + totals.cut += s.l.peers.cut; + if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); @@ -1580,7 +1766,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { nlooks += 1; }; - var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 }; + var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20, .throttled = if (r.clients >= 3) 2 else null }; defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; @@ -1598,7 +1784,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a - // flood of `yes`, read 4 KB at a time as a pty gives it. + // flood of `yes` and of a `cat`, read 4 KB at a time as a pty gives it. const tui = try screen_state.tuiStream(gpa); defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); @@ -1618,6 +1804,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); + const flood = try catAfter(yes, yes.len); + defer gpa.free(flood); var soak: Soak = .{ .r = r, @@ -1629,7 +1817,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .with_pdf = with_pdf, .tui = tui, .shell_session = shell_session, - .yes = yes, + .flood = flood, + .yes_len = yes.len, .own_left = r.steps, .typing = r.clients + 1, .media = &media, @@ -1718,6 +1907,26 @@ fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { return out.toOwnedSlice(gpa); } +/// `before`, then `n` bytes of what a `cat` of source text prints through a +/// pty: this file's lines, CR LF after each, again and again. +fn catAfter(before: []const u8, n: usize) ![]u8 { + var out: std.ArrayListUnmanaged(u8) = .empty; + errdefer out.deinit(gpa); + try out.appendSlice(gpa, before); + while (out.items.len < before.len + n) { + var lines = std.mem.splitScalar(u8, @embedFile("replicas.zig"), '\n'); + while (lines.next()) |line| try out.print(gpa, "{s}\r\n", .{line}); + } + out.shrinkRetainingCapacity(before.len + n); + return out.toOwnedSlice(gpa); +} + +fn monoNs() u64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + /// A typist: keys 50-200 ms apart, a pause now and then. fn typistGap(random: std.Random) u64 { return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); @@ -2563,7 +2772,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, .gone, .draw, .up, .blob => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } } const s = rp.echo.stats; @@ -2662,6 +2871,14 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { } +fn secs(us: u64) f64 { + return @as(f64, @floatFromInt(us)) / std.time.us_per_s; +} + +fn msOf(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; +} + fn pct(samples: []u64, p: usize) u64 { if (samples.len == 0) return 0; std.mem.sort(u64, samples, {}, std.sort.asc(u64)); @@ -2915,7 +3132,7 @@ pub fn main(init: std.process.Init) !void { // files (runtime/session.zig opens them), never the user's. var runtime_buf: [300]u8 = undefined; if (setenv("XDG_RUNTIME_DIR", try std.fmt.bufPrintSentinel(&runtime_buf, "{s}", .{dir}, 0), 1) != 0) return error.NoRuntimeDir; - std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); + std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes and as much of a cat in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); var term_lines: std.ArrayList(u8) = .empty; defer term_lines.deinit(gpa); @@ -2923,6 +3140,8 @@ pub fn main(init: std.process.Init) !void { defer join_lines.deinit(gpa); var stop_lines: std.ArrayList(u8) = .empty; defer stop_lines.deinit(gpa); + var far_lines: std.ArrayList(u8) = .empty; + defer far_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; pardes.Term.reloads = .{}; @@ -2959,6 +3178,20 @@ pub fn main(init: std.process.Init) !void { for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ + rtt, t.far_joins, t.far_lags, + secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), + secs(pct(t.far_final.items, 50)), secs(pct(t.far_final.items, 100)), + t.queue_max >> 10, t.cut, + msOf(pct(t.join_session_ns.items, 50)), msOf(pct(t.join_session_ns.items, 100)), + msOf(pct(t.join_client_ns.items, 50)), msOf(pct(t.join_client_ns.items, 100)), + t.join_client_ns.items.len, + msOf(t.far_behind), msOf(t.near_behind), + t.near_lags, + }); + // The far client shows the final screen in every run, and the near + // ones never fall behind with it. + if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; if (t.divergences > 0 or t.unequal > 0 or t.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", .{}); @@ -2967,6 +3200,8 @@ pub fn main(init: std.process.Init) !void { std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); + std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); + std.debug.print(" rtt joins lags refresh s final s queue KB cut session ms client ms behind far/near ms\n{s}", .{far_lines.items}); if (failed) std.process.exit(1); } |
