diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-21 01:00:47 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-21 01:08:24 -0300 |
| commit | 76565c605defb03ab6aa8300b93f306054a67efd (patch) | |
| tree | 706cc64e23ae33ec6be1d6b9164750ba42da712b /core/replica.zig | |
| parent | 6d937cd125ca04a2edb92b2d014014ee6c2eb45d (diff) | |
| parent | dac87eaa1d57acfc5b2dd8427e7fbacfe065e613 (diff) | |
| download | pardes-76565c605defb03ab6aa8300b93f306054a67efd.tar.gz pardes-76565c605defb03ab6aa8300b93f306054a67efd.zip | |
integration: the terminals' side line on the landed main: pardes-term-join-4 (terminals by the pty's bytes: a client's emulator fed the session's bytes, reload at a join, the lag bound; the query rows' paint decided on replicated state; views.park's leak; a view kept for its client's rejoin; C and Alt-C on a long text walking on from the row last tried: 306 G instructions to 194 M; the soak's witness and watchdog) and main (pardes-new-upgrade); seven conflicts: the wire's version (the side line's 24 is 26 here: 24 is the bye's close byte, 25 the 9P state), Peers' join (the view typed, the lag limit a field's default), a peer's end (the view's index; cut joins again), the client's and the soak's bye (the struct, again or lagged), daemon.py's WIRE; three more the compiler found (a test's view typed: its index where a u8 is asked)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/replica.zig')
| -rw-r--r-- | core/replica.zig | 530 |
1 files changed, 490 insertions, 40 deletions
diff --git a/core/replica.zig b/core/replica.zig index e2ecc796..39ee53b2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -964,9 +964,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))) { @@ -1689,8 +1690,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), @@ -1717,7 +1721,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(); @@ -1759,7 +1763,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; @@ -1774,12 +1778,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. @@ -1830,8 +1835,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); @@ -1851,7 +1857,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; } @@ -1912,17 +1924,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; } @@ -2325,7 +2337,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 = .at(k), .limit = lag_max, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; + peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(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. @@ -2360,7 +2372,9 @@ pub const Peers = struct { ps.tellClients(); ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); - 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; if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true; ps.seq += 1; @@ -3099,6 +3113,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. @@ -3164,6 +3182,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(); @@ -3195,6 +3224,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; @@ -3231,6 +3262,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; @@ -3290,6 +3322,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 { @@ -3320,8 +3371,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; } @@ -3363,12 +3415,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); @@ -4585,6 +4643,105 @@ 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 nothing on any side: a client with a key on top stays the session's" { + 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, 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); + try std.testing.expectEqual(before, pardes.Term.reloads.n); + 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(before, pardes.Term.reloads.n); + 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; @@ -5170,6 +5327,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.index())); + first.r.deinit(); + _ = libc.close(fd); + const back = try MemoryLinks.join(&ps, core, view.index(), &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.index(), .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 = .at(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); @@ -5224,6 +5587,70 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } } +// A query row's colours come from what this process has (its frames' +// paint of the owner, File.highlights; a worker's paint kept in the +// locations cache): out of the rows' digest. Whether a step asks a +// worker to paint the rows' file (Stream.paintRows, an effect on the +// tape) must not come from them: a session whose host paints on workers +// (search), that has drawn its owner, and a client that has not. +test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has drawn its owner" { + const Paints = struct { + fn search(_: ?*anyopaque, _: u32) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + }; + const gpa = std.testing.allocator; + // A view as tall as the text: the frame paints every line of it. + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + defer a.deinit(); + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try a.core.render(arena.allocator()); + } + _ = try a.openView(2); + const joiner = try joinedNow(a, 3, 1); + defer joiner.deinit(); + var buf: [256]u8 = undefined; + for ("/co", 1..) |c, seq| { + const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); + defer gpa.free(u); + joiner.confirm(u); + try agrees(a, joiner); + } +} + +// The same for the colours a worker painted earlier, kept in the session's +// locations cache (a Grep since has asked again of every file): a dump +// carries no cache, so a client joined since has none. +test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has them from an earlier paint" { + const Paints = struct { + fn search(_: ?*anyopaque, _: u32) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + }; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + defer a.deinit(); + { + const p = a.core; + const f = &p.panes[0].?.file.?; + const colors = try pardes.syntax.highlightFileRange(gpa, f.path, f.content, 0, f.content.len); + defer gpa.free(colors); + try p.locations_cache.put(p.tree_sitter_gpa, f.path, f.content, colors); + } + _ = try a.openView(2); + const joiner = try joinedNow(a, 3, 1); + defer joiner.deinit(); + var buf: [256]u8 = undefined; + for ("/co", 1..) |c, seq| { + const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); + defer gpa.free(u); + joiner.confirm(u); + try agrees(a, joiner); + } +} + test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -5893,9 +6320,12 @@ const may_wait = [_]Wait{ .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" }, .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" }, -} ++ (if (pardes.platform == .gui) [_]Wait{ +} ++ (if (pardes.font_picker) [_]Wait{ // A window's view (the font words are a window's). .{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, +} else [_]Wait{}) ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{ + // ...and Fonts a terminal's build has too, which a window client of its + // session runs (exec.zig's Font, a window build's alone, does not). .{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, } else [_]Wait{}); @@ -6049,6 +6479,23 @@ const Walk = struct { return what.len >= pattern.len - 1 and std.mem.startsWith(u8, what, pattern[0..star]) and std.mem.endsWith(u8, what, pattern[star + 1 ..]); } + /// Every word, with a sample argument where one is required. + fn words(w: *Walk) !void { + var line: [128]u8 = undefined; + for (std.enums.values(pardes.builtins.registry.Builtin())) |b| { + const name = @tagName(b); + const arg: ?[]const u8 = for (walk_samples) |s| { + if (std.mem.eql(u8, s[0], name)) break s[1]; + } else null; + if (pardes.builtins.registry.requiresArg(b) and arg == null) { + std.debug.print("may_wait: `{s}` requires an argument: give it one in walk_samples\n", .{name}); + return error.NoSample; + } + const cmd = if (arg) |x| try std.fmt.bufPrint(&line, "{s} {s}", .{ name, x }) else name; + try w.try_(cmd, &.{.{ .command = cmd }}); + } + } + /// The name of what stopped the inputs, "" when none did. fn try_(w: *Walk, what: []const u8, evs: []const pardes.Event) !void { const r = w.r; @@ -6115,7 +6562,6 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' var hit: [may_wait.len]bool = @splat(false); var unlisted: u32 = 0; var tried: u32 = 0; - const Builtin = pardes.builtins.registry.Builtin(); const stands = [_]struct { On, ?usize }{ .{ .file, file }, .{ .kind, kind }, .{ .shell, shell }, .{ .shell_normal, shell } }; for (stands) |stand| { const on, const at = stand; @@ -6137,19 +6583,7 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' try std.testing.expectEqual(id, r.core().view().active); if (on == .shell) try std.testing.expect(pardes.Term.modes(r.core().panes[id].?.terminal).focus); var w: Walk = .{ .r = r, .on = on, .seen = &seen, .hit = &hit }; - // Every word, with a sample argument where one is required. - for (std.enums.values(Builtin)) |b| { - const name = @tagName(b); - const arg: ?[]const u8 = for (walk_samples) |s| { - if (std.mem.eql(u8, s[0], name)) break s[1]; - } else null; - if (pardes.builtins.registry.requiresArg(b) and arg == null) { - std.debug.print("may_wait: `{s}` requires an argument: give it one in walk_samples\n", .{name}); - return error.NoSample; - } - const cmd = if (arg) |x| try std.fmt.bufPrint(&line, "{s} {s}", .{ name, x }) else name; - try w.try_(cmd, &.{.{ .command = cmd }}); - } + try w.words(); // Every key, plain, with Ctrl and with Alt, and after each prefix. var name_buf: [64]u8 = undefined; for (walk_keys) |k| try w.try_(keyName(&name_buf, k), &.{.{ .key = k }}); @@ -6188,6 +6622,19 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' unlisted += w.unlisted; tried += w.tried; } + // A terminal's build has the window's words too, which a window's view + // runs (a window client of its session; builtins.capabilities): its + // words walked again in one. + if (comptime pardes.builtins.desktop and pardes.platform != .gui) { + a.core.view().active = file; + _ = try a.local(.{ .frontend = .{ .windowed = true } }); + const r = try joinedFresh(a); + defer r.deinit(); + var w: Walk = .{ .r = r, .on = .file, .seen = &seen, .hit = &hit }; + try w.words(); + unlisted += w.unlisted; + tried += w.tried; + } // A row is stale where every kind of pane was walked: with no terminal // compiled in (core-test), a shell's rows stop nothing. var stale: u32 = 0; @@ -6384,25 +6831,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); |
