From b55b92456883e3fda113651f53e5fa2bc4a37304 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 01:04:57 -0300 Subject: replica: a client the session cuts off for what it left unread is told why and joins again for its view instead of ending (P32 (b); step 3, item 1): the fault shown first through the replica's surface (a session's queue for a client past its bound: the client's link ended with nothing said, Link.rejoins false, the client ended), then at the bound (Peer.send) what waits for it is let go and the words why ("N MB behind the session", a refusal, which a client already joins again on) queued in its place, its writer writing the batch in hand, the words, then ending the link (Peer.writeLoop; the limit's reset at every batch, a no-op, gone), its view kept for it (Peers.leave: views.away, as a bye's `again`), and a far join under way finished rather than dropped at a cut (writeJoin, farJoin, `letting`); two tests: a client cut off joins again from a dump and agrees, its view kept; a writer cut off while blocked on its socket writes its batch and the words; tui core-test 858/1008 (150 skipped), shell-test 1044/1047, term-test 17/17 (load 12-16) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 199 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 185 insertions(+), 14 deletions(-) (limited to 'core/replica.zig') diff --git a/core/replica.zig b/core/replica.zig index a52061f4..b6ac6ef9 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1686,8 +1686,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 +1717,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 +1759,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 +1774,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 +1831,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 +1853,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; } @@ -1899,17 +1910,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 last = 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 last) { _ = libc.shutdown(peer.fd, 2); return; } @@ -2303,7 +2314,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. @@ -2338,7 +2349,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); @@ -4925,6 +4938,164 @@ 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'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); -- cgit v1.3 From c9ac46755632d5cd1bdc34fe211112d730ffc77f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 01:21:25 -0300 Subject: replica: a client measures how far behind its session it is and past two seconds lets its link go and joins again from a dump, saying so once (P32 (b); step 3, item 2): the fault shown first (a client whose units came 2.1 s later than its quickest took them on: Link.quit false) and in the soak (the far client never let go: one join, its final screen 17.7 s after the flood's end); Link.behind, each unit's head's session clock against the client's own (Link.time), less the smallest difference seen; one constant, behind_max_ms = 2,000, near and far; past it the link let go (the bye's `again`, its view kept), the notice "joined again: N.N s behind" (Link.rejoins), the first unit after a join past it taken as the link now (a session's clock stood still while its machine slept; a dump that took longer than the bound: never a let-go at once, never a loop); the clock is the client's machine's, read in Link alone (no new line on root.zig's machine_lines; Link is no part of Pardes, so no digest or dump reaches it); a test that fed a simulated client clock with units of the real clock made them on its own clock; the soak counts the let-gos and how far behind each client fell; tui core-test 859/1009 (150 skipped), shell-test 1045/1048, term-test 17/17; the soak, screen state (--clients 5, 4 seeds): diverged 0, unequal 0, deltas 7093/0 7518/0 7603/0, quiet 590/0 472/0 541/0, unlisted 0, corpus 22 of 22, the far client 9/9/7 let-gos, others 0; bytes (--seeds 8): the far client shows its final screen in every run, 6.5-7.9 s after the flood's end, refreshed every 7.0-7.3 s (p50), others 0 let-gos and 2-10 ms behind at most, quiet 1077/0 1083/0 1457/0, unequal 0, BUT 5/3/1 near clients diverged at joins (reports/pardes-term-lag.md: open); ReleaseFast (2 seeds, 80 ms): 0 diverged, a join's unit on a client already there 9.6 ms p50, 17.7 ms at worst, the session's join step 1.4/14.3 ms Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 102 +++++++++++++++++++++++++++++++++++++++++++++++++---- runtime/client.zig | 7 ++-- test/replicas.zig | 27 ++++++++++---- 3 files changed, 121 insertions(+), 15 deletions(-) (limited to 'core/replica.zig') diff --git a/core/replica.zig b/core/replica.zig index b6ac6ef9..8fd0a251 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3050,6 +3050,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. @@ -3110,6 +3114,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(); @@ -3141,6 +3156,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; @@ -3177,6 +3194,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; @@ -3228,6 +3246,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 { @@ -3301,12 +3338,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); @@ -5044,6 +5087,50 @@ test "a client cut off for what it left unread is told why and joins again for i 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); + 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 }; @@ -6311,25 +6398,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/runtime/client.zig b/runtime/client.zig index 544be588..a2d89ab9 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -137,8 +137,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) { @@ -151,7 +152,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 637af0b3..5cddf6c8 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -284,6 +284,12 @@ const Totals = struct { 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. @@ -760,9 +766,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; @@ -1515,6 +1524,8 @@ const Soak = struct { 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) }), @@ -3082,16 +3093,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:>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})\n", .{ - rtt, t.far_joins, + 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, }); - if (t.far_final.items.len < seeds and clients >= 5) failed = true; + // 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", .{}); @@ -3100,8 +3115,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, 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\n", .{}); - std.debug.print(" rtt joins refresh s final s queue KB cut session ms client ms\n{s}", .{far_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); } -- cgit v1.3 From 4c5edb516c6c866fe6039037636804f4e868f4bb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 02:43:34 -0300 Subject: replica: a join's reloads are never taken as moving nothing (the one rule, which `tape.feedsTerminal` kept for a pty's output alone): a join refused for want of a view still reloads every terminal on every side (Core.zig `openViewInner`: `reloadTerminals` before `Views.open` returns null) and moves nothing a digest covers, so a near client with a key of its own on top took that unit as neutral (`confirm`, the same digest and no pty output: kept in `since`, not replayed), its key's fast path then left nothing on top, and the next output unit let the copy go and dropped `since` (`ahead`): that client never made the reload, held other pages than every other side, and once the flood pruned its history a page at a time it diverged: "digest N differs in panes pane 0.terminal pane 1.cwd" (pane 1's cwd is `.inherited: *Pane`, walked into pane 0's terminal) or, at the next join, "a terminal reloaded at a join is not the session's"; found by a ring of each replica's units and paths printed at its failure (seed 0 at 30 ms: the refused join `0/442` taken neutral, then the client's mouse `2/30` fast-pathed, then `0/443` released the copy); FIRST the test (a fifth client refused while every view is taken and a key of the client's is on top: the replica made 0 reloads where the session made 1, `expected 2, found 1` on the base), THEN `feedsTerminal` also names a unit with a `Site.reload` record; a user could not hit it today (real clients are screen state, which never reloads), and after the switch would have, whenever a fifth client was refused while another typed; and a third, seen once (seed 6 at 30 ms, the far client: "its digest, quiet, is not the session's"): a client that let its link go for its lag drops the units after it (`Link.lags`), but a check answered after the let-go was still judged (`Link.checked`) against a core behind on purpose: FIRST the lag test takes a check after its let-go (diverged on the base), THEN `checked` judges nothing once the link is let go; the soak, bytes, `--clients 5 --bytes --seeds 8` at 30/80/207 ms with the `cat` whole (Debug, load 25-44): 2 of 4 whole runs clean (diverged 0, unequal 0, quiet checks agreed, unlisted 0, corpus 22 of 22, no leak); in the other two, seed 2 at 80 ms (two clients at one session unit) and seed 0 at 30 ms (one client): OPEN, not root-caused (reports/pardes-term-join.md), never under a probe; seed 0 at 30 ms, 19 of 20 clean, one run hung spinning (killed, no trace); on the base seed 0 at 30 ms diverged every time and 9 of 24 runs; tui core-test 859/1011 (152 skipped), shell-test 1047/1050 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 49 ++++++++++++++++++++++++++++++++++++++++++++----- core/tape.zig | 10 +++++++--- 2 files changed, 51 insertions(+), 8 deletions(-) (limited to 'core/replica.zig') diff --git a/core/replica.zig b/core/replica.zig index 8fd0a251..b4d8edfa 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))) { @@ -3295,8 +3296,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; } @@ -4445,6 +4447,39 @@ test "bytes: a client joins from a dump with its terminals whole, and every side try sameTerminals(b.a, late); } +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 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; @@ -5116,6 +5151,10 @@ test "a client whose session's units come more than two seconds later than its q 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()); diff --git a/core/tape.zig b/core/tape.zig index d977b53e..ea1a5691 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -1520,15 +1520,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; -- cgit v1.3 From 23de206007ebae87007460afa993338781a03076 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 03:43:49 -0300 Subject: term: a join reloads only the terminals written since their last reload (step 3's way 1): `Term.State.written` (a feed, a reflow, a load, a revive; cleared by a reload), the session's choice taped before each terminal's hash at the `reload` site (`tape.value`), each replica reloading exactly those and comparing each hash as before; exact: one written by nothing since holds the pages its last reload's snapshot loads to on every side, and the joiner loads that snapshot again; FIRST the test (two terminals, both reloaded at a join, the shell alone written since: the next join reloads it alone on the session (1, the base 2) and on the replica, then 40,000 lines into both until each prunes its history: the replica and the joiner hold the session's snapshot bytes and digest, and a join after agrees); ReleaseFast, bytes, 2 seeds at 80 ms (load 8-18): the flooding shell alone, a join's unit on a client already there 9.9 ms p50, 13.6 ms at worst, the session's join step 1.4/14.8 ms (step 3's report: 9.6/17.7 and 1.4/14.3); with four idle shells each a full scrollback beside it (the soak patched for the measure, not landed): reloads 2,910 -> 659, the client's join unit 58.7 -> 20.3 ms p50 and 219 -> 122 ms at worst, the session's step 86.0 -> 38.2 ms p50 and 211 -> 106 at worst (the first join still reloads all); the soak, bytes, `--clients 5 --bytes --seeds 8` at 30/80/207 ms with the `cat` whole (Debug, load 25-44): 2 of 4 whole runs clean (diverged 0, unequal 0, quiet checks agreed, unlisted 0, corpus 22 of 22, no leak); in the other two, seed 2 at 80 ms (two clients at one session unit) and seed 0 at 30 ms (one client): OPEN, not root-caused (reports/pardes-term-join.md), never under a probe; seed 0 at 30 ms, 19 of 20 clean, one run hung spinning (killed, no trace); on the base seed 0 at 30 ms diverged every time and 9 of 24 runs; tui core-test 859/1011 (152 skipped), shell-test 1047/1050 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Term.zig | 13 ++++++++++- core/panes.zig | 18 ++++++++++----- core/replica.zig | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/tape.zig | 6 ++--- 4 files changed, 96 insertions(+), 9 deletions(-) (limited to 'core/replica.zig') diff --git a/core/Term.zig b/core/Term.zig index 89773f77..eabf5b81 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 @@ -155,7 +161,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 @@ -168,6 +176,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); } @@ -187,6 +196,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); } @@ -217,6 +227,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 fd152e1e..7d604567 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -1120,16 +1120,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. @@ -1144,6 +1148,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 b4d8edfa..6dcc0281 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4480,6 +4480,74 @@ test "bytes: a join refused for want of a view reloads every terminal and moves 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; diff --git a/core/tape.zig b/core/tape.zig index ea1a5691..3d2b6f31 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -131,9 +131,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, }; -- cgit v1.3 From ce92a8c3da84c0bc4f5f2b56acf6e09fa42990f4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 13:19:36 -0300 Subject: join: a join refused for want of a view reloads nothing: openViewInner reloaded every written terminal on every side before Views.open said no (core/Core.zig), a step of a megabyte's snapshot a terminal for nothing a session refuses 550-630 times a soak run; the view now taken first, the reloads after; FIRST the test (core/replica.zig, the earlier one turned round: every view taken, a key of the client's on top, a fifth client refused, the pump's unit, the key confirmed, more output: no reload on any side, the client the session's): on the base expected 2, found 3 (the refused join reloaded); with the change shell-test -Dtest-filter='bytes: a join' 13/13 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 4 +++- core/replica.zig | 12 +++++------- 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'core/replica.zig') diff --git a/core/Core.zig b/core/Core.zig index 7ebcc020..6de4f21e 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1174,9 +1174,11 @@ fn openViewInner(p: *Pardes) ?View.Id { // tape does it here: a join dumps the session next, and a core // loaded from a dump has no queue (Replica.initDump). p.settle(); + // A join refused (every view taken) reloads nothing. + const k = Views.open(p) orelse return null; pardes.panes.reloadTerminals(p); p.needs_frame = true; - return .at(Views.open(p) orelse return null); + return .at(k); } /// The client of view `k` gone: its view goes, the others stay. The diff --git a/core/replica.zig b/core/replica.zig index e1dc7dc1..ff43203a 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4616,7 +4616,7 @@ 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" { +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(); @@ -4630,21 +4630,19 @@ test "bytes: a join refused for want of a view reloads every terminal and moves 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. + // 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); - const session = pardes.Term.reloads.n - before; - try std.testing.expect(session > 0); + 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(2 * session, pardes.Term.reloads.n - before); + try std.testing.expectEqual(before, pardes.Term.reloads.n); try agrees(b.a, b.r); try sameTerminals(b.a, b.r); } -- cgit v1.3 From d3f9f3775e2efbcb4d617afb4a18eaf5efa72e29 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 13:32:36 -0300 Subject: may_wait: Fonts in a window's view of a terminal's build: the soak's 'client 2's input key stopped at fonts' was a window client (the soak's even clients are windows) of the tui build's session whose key ran Fonts (the key logged is Enter, a word taken under the cursor; the leader's SPC t f runs it too, config.zig, set wherever builtins.capabilities.font_picker, true on every desktop build: a window's view of a terminal's session has the window's words), whose list is the session's machine's fonts (Output.openFonts, tape site fonts): a far client may wait for it, as the window's build already lists; may_wait listed it only where pardes.platform == .gui; now Fonts where the build has the word (capabilities.font_picker) and Font where its site is reachable (pardes.font_picker: exec.zig's Font is a window build's alone); FIRST the test: the walk of every word, on a terminal's build, walks the words again in a window's view (on the base: 'Fonts on file stopped at fonts', 1 unlisted); then the rows: shell-test's walk 12/12 (with Font gated as Fonts it said the row Font * stale: its gate is its site's) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 50 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 15 deletions(-) (limited to 'core/replica.zig') diff --git a/core/replica.zig b/core/replica.zig index ff43203a..24d1ad21 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6229,9 +6229,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{}); @@ -6385,6 +6388,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; @@ -6451,7 +6471,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; @@ -6473,19 +6492,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 }}); @@ -6524,6 +6531,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; -- cgit v1.3 From e4bda7e899089b0c8594ad1b03099402bddeeef1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 16:12:18 -0300 Subject: Query rows: what a step asks a worker to paint no longer hangs on the colours this process happens to have: the bytes soak's 'the core called search where the tape has a host' (g6, seed 5 at 80 ms, the witness parting at the session's own step) was a query row's colours read by the step that decides whether to ask a worker for its file's paint (Stream.paintRows, an effect on the tape): Query.writePlacesRows (Query.zig:1073) took a `/` row's colours from the owner's frame paint (File.highlights, painted by refreshHighlights, derived) and only a row left plain went to Shades.of, which asked; Shades.of asked only on a miss in the locations cache (derived: a dump carries none, so a client joined since has none); recolor asked only for rows whose colours were still zeros (derived); so a session that had drawn its owner, or had the file's colours from an earlier paint, asked nothing where a replica that never draws, or a client joined since, asked a worker (and its stream.rows_count, rows_paint, rows_asked, rows_asked_at moved on one side only: the four fields the witness named); FIRST the tests (core/replica.zig, a session whose host paints on workers): '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' and '... though only the session has them from an earlier paint', both on the base 'diverged: the core called search where the tape has a done (0)'; then the fix: Shades asks for every file its rows show (Shades.file at every row, whatever colours it has; Shades.done at the file's end and each walk's), paintRows decides on replicated state alone (the row ring, the pending paint, the pane's text), its key the path's hash (a file is painted once between two Greps, not again at each revision of an open text, which a frame paints where it is seen); a row's colours still come from the frame's paint and the cache, out of the rows' digest as before; root.zig's kept_out lines for highlights and locations_cache say so --- core/Query.zig | 67 ++++++++++++++++++++++++++++++++------------------------ core/Stream.zig | 29 +++++++++++++----------- core/replica.zig | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++ core/root.zig | 4 ++-- 4 files changed, 120 insertions(+), 44 deletions(-) (limited to 'core/replica.zig') diff --git a/core/Query.zig b/core/Query.zig index ebb44155..f0e9ee1a 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -888,6 +888,7 @@ fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locatio if (gutter + code.len > buf.len) return; @memset(buf[address.len..gutter], ' '); @memcpy(buf[gutter..][0..code.len], code); + sh.file(p, path); try writeRow(p, out, rows, buf[0 .. gutter + code.len], .{ .kind = .match, .source_column = lead, @@ -895,16 +896,16 @@ fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locatio .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, .location_end = address.len, .code_start = gutter, - .colors = @constCast(if (shade.len >= lead + code.len) shade[lead..][0..code.len] else sh.of(p, path, line_no, code, lead)), + .colors = @constCast(if (shade.len >= lead + code.len) shade[lead..][0..code.len] else sh.of(line_no, code, lead)), }); } /// Rows' syntax colours from their file's whole (as Callstack's rows are), /// kept in the locations cache once a worker has painted it /// (Stream.paintRows): the line found going down the file a row at a time, -/// so a refill walks each file once. A file not painted, or whose line no -/// longer reads as the row does, is asked for (once a refill) and its rows -/// are plain till it lands (`recolor`). +/// so a refill walks each file once. Every file is asked for once its rows +/// are made (`file`, `done`; Stream.paintRows asks each once a Grep), and +/// a row it does not colour is plain till it lands (`recolor`). const Shades = struct { path: []const u8 = "", source: []const u8 = "", @@ -912,50 +913,54 @@ const Shades = struct { /// The line (1-based) that starts at `at` in `source`. line: usize = 1, at: usize = 0, - asked: bool = false, - - /// The colours of `code`, which is line `line_no` of `path` from byte - /// `column` on, or none. - fn of(sh: *Shades, p: *Pardes, path: []const u8, line_no: usize, code: []const u8, column: usize) []const u8 { - if (path.len == 0 or line_no == 0 or code.len == 0) return &.{}; - if (!std.mem.eql(u8, path, sh.path)) { - // its own copy: a caller's path is often a buffer it reuses - sh.* = .{ .path = p.scratch.allocator().dupe(u8, path) catch return &.{} }; - if (p.locations_cache.peek(path)) |e| { - sh.source = e.source; - sh.colors = e.colors; - } + + /// The rows of `path` follow (a caller's buffer: copied): the file + /// before them done. Called for every row, whatever colours it has, so + /// that every process asks paintRows at the same rows. + fn file(sh: *Shades, p: *Pardes, path: []const u8) void { + if (std.mem.eql(u8, path, sh.path)) return; + sh.done(p); + sh.* = .{ .path = p.scratch.allocator().dupe(u8, path) catch "" }; + if (p.locations_cache.peek(path)) |e| { + sh.source = e.source; + sh.colors = e.colors; } - if (sh.colors.len == 0 or sh.colors.len != sh.source.len) return sh.ask(p); + } + + /// The file's rows are made: its colours asked of a worker. + fn done(sh: *Shades, p: *Pardes) void { + if (sh.path.len > 0) Stream.paintRows(p, sh.path); + } + + /// The colours of `code`, which is line `line_no` of the file `file` + /// named from byte `column` on, or none. + fn of(sh: *Shades, line_no: usize, code: []const u8, column: usize) []const u8 { + if (sh.path.len == 0 or line_no == 0 or code.len == 0) return &.{}; + if (sh.colors.len == 0 or sh.colors.len != sh.source.len) return &.{}; if (line_no < sh.line) { sh.line = 1; sh.at = 0; } while (sh.line < line_no) : (sh.line += 1) { - sh.at = (std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse return sh.ask(p)) + 1; + sh.at = (std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse return &.{}) + 1; } const line = sh.source[sh.at .. std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse sh.source.len]; - if (column + code.len > line.len or !std.mem.eql(u8, line[column..][0..code.len], code)) return sh.ask(p); + if (column + code.len > line.len or !std.mem.eql(u8, line[column..][0..code.len], code)) return &.{}; return sh.colors[sh.at + column ..][0..code.len]; } - - fn ask(sh: *Shades, p: *Pardes) []const u8 { - if (!sh.asked) Stream.paintRows(p, sh.path); - sh.asked = true; - return &.{}; - } }; /// A file's colours arrived (Stream.paintRows): every query pane's hit /// rows still plain, live or frozen, coloured from what is painted now, in -/// place; the first row of a file not painted yet asks for it, so they are -/// painted one after another. +/// place; the next file not asked yet is asked for, so they are painted +/// one after another. pub fn recolor(p: *Pardes) void { for (p.panes) |slot| { const rp = slot orelse continue; if (rp.query == null) continue; const f = &rp.file.?; var sh: Shades = .{}; + defer sh.done(p); var lines = std.mem.splitScalar(u8, f.content, '\n'); // The rows are a blob (File.State): a digest keeps its word for // them and a rollback copy pins them, so they are made again, never @@ -967,9 +972,10 @@ pub fn recolor(p: *Pardes) void { for (f.location_rows, 0..) |row, i| { const text = lines.next() orelse break; if (row.kind != .match or row.location_end == 0 or row.at.line == 0 or row.colors.len == 0) continue; + sh.file(p, row.path); if (std.mem.indexOfNone(u8, row.colors, &.{0}) != null) continue; const code = text[@min(row.code_start, text.len)..]; - const got = sh.of(p, row.path, row.at.line, code[0..@min(code.len, row.colors.len)], row.source_column); + const got = sh.of(row.at.line, code[0..@min(code.len, row.colors.len)], row.source_column); if (got.len == 0) continue; const rows = fresh orelse locations.cloneRows(p.gpa, f.location_rows) catch break; fresh = rows; @@ -1027,6 +1033,7 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const rel = lookPath(&relbuf, path, dir); const width = addressWidth(rel, index.len); var sh: Shades = .{}; + defer sh.done(p); const decls = ownerDecls(f) orelse &.{}; var decl_now: ?usize = null; var i: usize = @min(from, hits.len); @@ -1182,6 +1189,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { } var current: ?usize = null; var sh: Shades = .{}; + defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { @@ -1342,6 +1350,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var pathbuf: [4096 + 8]u8 = undefined; var n: usize = 0; var sh: Shades = .{}; + defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; for (sorted.items, 0..) |ln, li| { diff --git a/core/Stream.zig b/core/Stream.zig index 1f4a7405..78f6ef41 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -245,10 +245,10 @@ ahead_seen: struct { serial: u32 = 0, scroll: usize = 0, dir: i2 = 1 } = .{}, /// the next asked when it lands (Query.recolor); a worker per file if a /// Grep of hundreds of files colours too slowly. rows_paint: ?TextTask = null, -/// The files (a hash of path and revision) asked since the last Grep -/// began: each asked once, so a file whose colours never fit its rows -/// (changed on disk since) is not painted again and again. ponytail: a -/// ring of 256; the oldest forgotten. +/// The files (a hash of the path) asked since the last Grep began: each +/// asked once, so a file whose colours never fit its rows (changed on +/// disk since, an edit) is not painted again and again. ponytail: a ring +/// of 256; the oldest forgotten. rows_asked: [256]u64 = @splat(0), rows_asked_at: u8 = 0, /// Rows asked for their colours while a 9P write was served: asked again @@ -352,17 +352,13 @@ pub fn askAhead(p: *Pardes) void { /// from disk there. Kept in the locations cache when it lands, where the /// rows find them (Query.Shades). Not without workers (the rows stay /// plain), nor for a file bigger than `max_rows_paint_bytes`, nor twice for -/// one revision of a file. +/// a file between two Greps. Asked after every file's rows, whatever +/// colours they have here: those are this process's own (what its frames +/// painted of the text, what its locations cache kept: in no digest), and +/// what a step asks of a worker must not hang on them. pub fn paintRows(p: *Pardes, path: []const u8) void { const s = &p.stream; if (s.rows_paint != null or !p.tape.has(p, .search)) return; - // Asked while a 9P write is served (a script's Grep): not now, as no - // paint is (the write would wait for it to settle); the next step asks. - if (p.fs.serving) { - s.rows_later = true; - return; - } - if (!syntax.readyApart(path)) return; var content: ?[]const u8 = null; var revision: u32 = 0; for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output == null and std.mem.eql(u8, f.path, path)) { @@ -371,8 +367,15 @@ pub fn paintRows(p: *Pardes, path: []const u8) void { break; }; if (content) |c| if (c.len > max_rows_paint_bytes) return; - const key = std.hash.Wyhash.hash(revision, path) | 1; + const key = std.hash.Wyhash.hash(0, path) | 1; if (std.mem.indexOfScalar(u64, &s.rows_asked, key) != null) return; + if (!syntax.readyApart(path)) return; + // Asked while a 9P write is served (a script's Grep): not now, as no + // paint is (the write would wait for it to settle); the next step asks. + if (p.fs.serving) { + s.rows_later = true; + return; + } const job = TextJob.make(p.gpa, 0, revision, 0, path, content orelse "") orelse return; s.rows_asked[s.rows_asked_at] = key; s.rows_asked_at +%= 1; diff --git a/core/replica.zig b/core/replica.zig index 24d1ad21..e05cf79e 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -5560,6 +5560,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; diff --git a/core/root.zig b/core/root.zig index 5300ce93..b5109b0e 100644 --- a/core/root.zig +++ b/core/root.zig @@ -737,7 +737,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "needs_frame", "whether to draw: steps set it, the loop reads it; no step's outcome reads it" }, .{ "Core.zig", "effects effects_head effects_len in_q in_head in_len opts dump_out dump_export tape", "this process's queues, options and tape, drained or set by its host" }, .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; a terminal is in no digest (Term.zig)" }, - .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest)" }, + .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, @@ -746,7 +746,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, - .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest)" }, + .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, .{ "File.zig", "node_tree node_tree_revision node_tree_edits node_history", "the parse of the text at its revision, made by the first key that walks it" }, -- cgit v1.3