summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-20 11:17:46 -0300
committerGabriel Schneider <[email protected]>2026-11-20 12:30:53 -0300
commit20f08450aee2487809feb6442ec44e21d2436e5d (patch)
treea6eda48cc7988b37019a98b914486cd04642e31a /core
parent35b2c0efc6c43ba44640f4432d98734000f8887a (diff)
parent23de206007ebae87007460afa993338781a03076 (diff)
downloadpardes-20f08450aee2487809feb6442ec44e21d2436e5d.tar.gz
pardes-20f08450aee2487809feb6442ec44e21d2436e5d.zip
integration (the terminals' line, NOT the main line yet): a client that falls behind lets go and joins again, a join's reloads never dropped and only of the terminals written, on the first client and the pair: pardes-term-join (with pardes-term-lag under it) and pardes-merge35; three conflicts, each two sides adding at one place: the tests at the end of core/replica.zig (both kept), the soak's fields and its end's checks in test/replicas.zig (the images' and the far client's both kept); one name follows: Peer.writeLoop's local for a cut link was named last, which the first client's Peer.last now is (cut_off); tui core-test 861/1018 (157 skipped), shell-test 1058/1061, term-test 18/18, the window builds; the soak, screen state: diverged 0, unequal 0, unlisted 0; BYTES: seed 0 at 30 ms two clients diverged (client 2 at digest 29, client 3 at digest 2): the divergence the join's report left open, here on the merged session: this line stays beside the main one until that soak is clean
Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core')
-rw-r--r--core/Term.zig13
-rw-r--r--core/panes.zig18
-rw-r--r--core/replica.zig418
-rw-r--r--core/tape.zig16
-rw-r--r--core/term/terminal.zig31
5 files changed, 459 insertions, 37 deletions
diff --git a/core/Term.zig b/core/Term.zig
index aa05a68f..6ef9b0a5 100644
--- a/core/Term.zig
+++ b/core/Term.zig
@@ -65,6 +65,12 @@ fn the() *const iface.Ops {
/// as it always has (`Parts` by name, then ghostty's snapshot).
pub const State = struct {
impl: *iface.State,
+ /// Written since its last reload (a feed, a reflow, a load: what cuts
+ /// its rows into pages), which a join reloads (panes.reloadTerminals,
+ /// the session's choice). One not holds the pages its last reload's
+ /// snapshot loads to, on every side, and so does a joiner loading the
+ /// same snapshot again from the dump.
+ written: bool = true,
/// The emulator as its program has made it, for the replay digest.
/// Under screen-state terminals the emulator is the authority's, and a
@@ -167,7 +173,9 @@ pub fn reload(s: *State) !u64 {
reloads.ns += dt;
reloads.worst_ns = @max(reloads.worst_ns, dt);
}
- return the().reload(s.impl);
+ const hash = try the().reload(s.impl);
+ s.written = false;
+ return hash;
}
/// When its next kitty animation frame is due (ms on the core's clock), as
@@ -180,6 +188,7 @@ pub fn due(s: *const State) ?u64 {
/// history marked off from what the next shell prints.
pub fn revive(s: *State) void {
writes +%= 1;
+ s.written = true;
the().revive(s.impl);
}
@@ -199,6 +208,7 @@ pub fn stop() void {
/// went).
pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told {
writes +%= 1;
+ s.written = true;
return the().feed(s.impl, bytes, tracked, rows, erased);
}
@@ -229,6 +239,7 @@ pub fn follow(s: *State) void {
/// Its grid reflowed, now or when `resizeDeferred` makes it.
pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void {
writes +%= 1;
+ s.written = true;
the().resize(s.impl, cols, rows, later);
}
diff --git a/core/panes.zig b/core/panes.zig
index 1c103bd1..89d9f309 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -1126,16 +1126,20 @@ pub const Term = @import("Term.zig");
pub const positions_lost = "terminal edit position reset: out of memory";
/// At a join (Core's openView, rejoinView): under bytes, every live
-/// terminal made again from its own snapshot, on every side alike, the
-/// session included (Term.reload): an emulator loaded from a snapshot holds
-/// its rows in other pages than one fed from its start, and ghostty prunes
-/// its history a page at a time, so the joiner, loaded from the session's
-/// dump made next, and the replicas there before it, would part. The
+/// terminal written since its last reload made again from its own snapshot,
+/// on every side alike, the session included (Term.reload): an emulator
+/// loaded from a snapshot holds its rows in other pages than one fed from
+/// its start, and ghostty prunes its history a page at a time, so the
+/// joiner, loaded from the session's dump made next, and the replicas there
+/// before it, would part. Which, the session says (`Term.State.written`,
+/// taped): one written by nothing since holds the pages its last reload
+/// made, on every side, and the joiner loads that snapshot again. The
/// session's snapshot's hash is taped, and each replica's own compared
/// with it: a check of the whole emulator at every join.
pub fn reloadTerminals(p: *Pardes) void {
if (tape.screenState()) return;
for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| {
+ if (!tape.value(.reload, written, .{state})) continue;
// Its cells' size in pixels as a feed sets it (`feedOutput`): a
// frontend's draw sets its own view's between steps (ansi.zig), a
// window's other than a terminal's, and the snapshot holds it.
@@ -1150,6 +1154,10 @@ fn sameHash(h: ?u64) ?u64 {
return h;
}
+fn written(s: *Term.State) bool {
+ return s.written;
+}
+
/// The sizes steps gave terminals (`Pane.resizeGrid`), made: between
/// units, on an authority with screen-state replicas (replica.Peers.unit).
pub fn resizeDeferred(p: *Pardes) void {
diff --git a/core/replica.zig b/core/replica.zig
index 781bd211..e1dc7dc1 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -963,9 +963,10 @@ pub const Replica = struct {
r.last_digest.clearRetainingCapacity();
if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {};
}
- // A terminal's output is never taken so (the one rule): what it
- // writes outside the copy is applied once, at its place, and much
- // of it no digest covers (a colour set, a mode).
+ // A terminal's output, or a join's reloads, never taken so (the one
+ // rule): what it writes outside the copy is applied once, at its
+ // place, and much of it no digest covers (a colour set, a mode, the
+ // pages a reload remakes).
if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and
(r.t.screen_state or !tape.feedsTerminal(u.tape)))
{
@@ -1686,8 +1687,11 @@ pub const Peer = struct {
/// What it is sent, not written yet, and what the writer writes now.
out: std.ArrayListUnmanaged(u8) = .empty,
sending: std.ArrayListUnmanaged(u8) = .empty,
- limit: usize = 64 << 20,
+ /// What may wait in `out` before it is cut off (a test's less).
+ limit: usize = lag_max,
closing: bool = false,
+ /// Cut off (`send`): the words why are the last it is sent, and its
+ /// view is kept for it (views.away), as for a bye's `again`.
cut: bool = false,
/// Its writer has ended (what it was sent, written).
done: std.atomic.Value(bool) = .init(false),
@@ -1714,7 +1718,7 @@ pub const Peer = struct {
if (!writeAll(peer.fd, peer.welcome[0..peer.welcome_len])) return false;
const io = peer.peers.io;
peer.lock.lockUncancelable(io);
- while (peer.far == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock);
+ while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock);
const far = peer.far;
peer.lock.unlock(io);
if (far orelse return false) return peer.farJoin();
@@ -1756,7 +1760,7 @@ pub const Peer = struct {
if (peer.blobs.items.len > 0) {
const io = peer.peers.io;
peer.lock.lockUncancelable(io);
- while (peer.want == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock);
+ while (peer.want == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock);
const want = peer.want;
peer.lock.unlock(io);
const bits = want orelse return false;
@@ -1771,12 +1775,13 @@ pub const Peer = struct {
return peer.z != null;
}
- /// Whether it is being let go (or was cut off).
+ /// Whether it is being let go. One cut off is still sent its join
+ /// whole, then the words why (`send`): it joins again after them.
fn letting(peer: *Peer) bool {
const io = peer.peers.io;
peer.lock.lockUncancelable(io);
defer peer.lock.unlock(io);
- return peer.closing or peer.cut;
+ return peer.closing;
}
/// One message into its stream's compressor.
@@ -1827,8 +1832,9 @@ pub const Peer = struct {
}
/// `parts` queued for it, in order; never waits. A client whose queue
- /// passes its limit is cut off: its link is shut down, and its reader
- /// says it is gone.
+ /// passes its limit is cut off: what waits for it is let go and the
+ /// words why queued in its place, after which its writer ends its link
+ /// (`writeLoop`); it joins again from a dump, for its view (`leave`).
fn send(peer: *Peer, parts: []const []const u8) void {
const io = peer.peers.io;
peer.lock.lockUncancelable(io);
@@ -1848,7 +1854,13 @@ pub const Peer = struct {
log.info("client {d} is {d} MB behind: cut off", .{ peer.id, n >> 20 });
peer.peers.cut += 1;
peer.cut = true;
- _ = libc.shutdown(peer.fd, 2);
+ peer.out.clearRetainingCapacity();
+ var words: [48]u8 = undefined;
+ var msg: [64]u8 = undefined;
+ const word = wire.encodeServer(&msg, .{ .refused = std.fmt.bufPrint(&words, "{d} MB behind the session", .{n >> 20}) catch unreachable }) catch unreachable;
+ peer.out.appendSlice(peer.peers.gpa, word) catch {
+ _ = libc.shutdown(peer.fd, 2);
+ };
peer.cond.signal(io);
return;
}
@@ -1909,17 +1921,17 @@ pub const Peer = struct {
while (true) {
peer.lock.lockUncancelable(io);
while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock);
- if (peer.out.items.len == 0 or peer.cut) {
+ if (peer.out.items.len == 0) {
peer.lock.unlock(io);
return;
}
std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending);
- // The limit was for the dump and what is queued behind it.
- peer.limit = lag_max;
+ // Cut off: the words why came last, and its link ends after them.
+ const cut_off = peer.cut;
peer.lock.unlock(io);
const ok = if (peer.z != null) peer.zWrite(peer.sending.items, .flush) else writeAll(peer.fd, peer.sending.items);
peer.sending.clearRetainingCapacity();
- if (!ok) {
+ if (!ok or cut_off) {
_ = libc.shutdown(peer.fd, 2);
return;
}
@@ -2316,7 +2328,7 @@ pub const Peers = struct {
core.gpa.free(bytes);
return daemon.refuseReplica(fd, "out of memory");
};
- peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .limit = lag_max, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
ps.next_id +%= 1;
if (ps.next_id == 0) ps.next_id = 1;
// The session's digest as dumped, for the joiner to check its load by.
@@ -2351,7 +2363,9 @@ pub const Peers = struct {
ps.tellClients();
ps.screens.dropPeer(peer.sid);
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
- ps.closeViewOf(core, peer, peer.again);
+ // Cut off, it joins again after the words why (`send`); its reader
+ // has ended and no other thread sets `cut` now.
+ ps.closeViewOf(core, peer, peer.again or peer.cut);
if (ps.count() == 0) core.unattended = ps.detached;
ps.seq += 1;
ps.unit(0, ps.seq);
@@ -3074,6 +3088,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
}
}
+/// How far behind its session a client may fall before it lets its link go
+/// and joins again from a dump (P32 (b)): near and far alike.
+pub const behind_max_ms = 2_000;
+
/// A replica client's link to its session, the terminal's (tui.zig
/// `runClient`) and the window's (gui.zig `runClient`): its replica, its socket,
/// what the session said, and what it checks. Drawing is the frontend's.
@@ -3137,6 +3155,17 @@ pub const Link = struct {
/// moved on (its own motion), for PARDES_REPLICA_STATS.
draws: u32 = 0,
again: u32 = 0,
+ /// How far behind the session it is, ns: each unit's head carries the
+ /// session's monotonic clock as it was made; against this client's own,
+ /// less the smallest difference seen (the clocks' offset and the link's
+ /// quickest crossing). This machine's clock, the link's alone: no step
+ /// reads it and no digest holds it (`lags`).
+ behind: u64 = 0,
+ least: ?i64 = null,
+ /// No unit taken since it joined (`lags`).
+ fresh: bool = true,
+ /// How far behind it was as it let its link go (`rejoins` says so).
+ lagged: u64 = 0,
fn time(c: *const Link) u64 {
return c.now orelse nowNs();
@@ -3168,6 +3197,8 @@ pub const Link = struct {
c.asked = false;
c.mispredicted = 0;
c.put_off = false;
+ c.behind = 0;
+ c.fresh = true;
if (r.core().views[r.view]) |v| {
c.yanks = v.yanks;
c.pastes = v.pastes;
@@ -3204,6 +3235,7 @@ pub const Link = struct {
switch (msg) {
.unit => |bytes| {
defer std.heap.c_allocator.free(bytes);
+ if (c.quit or c.lags(bytes)) return;
c.r.confirm(bytes);
if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) {
c.test_diverge = 0;
@@ -3263,6 +3295,25 @@ pub const Link = struct {
};
}
+ /// The session's unit `bytes`, taken now: how far behind it is. Past
+ /// `behind_max_ms` it lets its link go (true), to join again from a dump.
+ /// The first unit after a join past it is taken as the link now (a
+ /// session's clock stood still while its machine slept; a dump that took
+ /// longer than the bound to come), never a let-go again at once.
+ fn lags(c: *Link, bytes: []const u8) bool {
+ const u = parseUnit(bytes) orelse return false;
+ const d = @as(i64, @intCast(c.time())) - u.mono_ns;
+ const max = behind_max_ms * std.time.ns_per_ms;
+ if (c.fresh and d - (c.least orelse d) > max) c.least = d;
+ c.fresh = false;
+ c.least = @min(c.least orelse d, d);
+ c.behind = @intCast(d - c.least.?);
+ if (c.behind <= max) return false;
+ c.lagged = c.behind;
+ c.quit = true;
+ return true;
+ }
+
/// A write to the session failed: it hung up (it cut this client off,
/// lagging), as its reader will say.
fn cut(c: *Link) void {
@@ -3293,8 +3344,9 @@ pub const Link = struct {
fn checked(c: *Link, theirs: u64) void {
c.asked = false;
// Not quiet now, the answer is let go: it covers nothing, and the
- // next quiet asks again.
- if (!c.r.quiet() or c.r.diverged != null) {
+ // next quiet asks again. Nor once its link is let go: a lag's let-go
+ // drops the units after it (`lags`), and the core is behind them.
+ if (c.quit or !c.r.quiet() or c.r.diverged != null) {
c.changed = true;
return;
}
@@ -3336,12 +3388,18 @@ pub const Link = struct {
}
/// The link ended: whether the client joins again, and why in its
- /// notice (it diverged, or the session let it go to upgrade).
+ /// notice (it diverged, it fell too far behind, or the session let it
+ /// go: to upgrade, or cut off).
pub fn rejoins(c: *Link) bool {
if (c.r.diverged) |reason| {
c.notify("joined again: this client diverged from the session ({s})", .{reason});
return true;
}
+ if (c.lagged != 0) {
+ c.notify("joined again: {d}.{d} s behind", .{ c.lagged / std.time.ns_per_s, c.lagged / (std.time.ns_per_s / 10) % 10 });
+ c.lagged = 0;
+ return true;
+ }
if (c.refused) |words| {
c.notify("joined again: {s}", .{words});
std.heap.c_allocator.free(words);
@@ -4558,6 +4616,107 @@ fn firstOnPair(bytes: bool) !void {
try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n);
}
+test "bytes: a join refused for want of a view reloads every terminal and moves nothing a digest covers: a client with a key on top reloads too, at its place, never taking that unit as moving nothing" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ try b.output("a line of the program's\r\n");
+ // Every view taken: the session's, then three clients'.
+ for (2..pardes.views.max + 1) |client| b.r.confirm((try b.a.openView(@intCast(client))).unit);
+ try b.output("and one since the last join\r\n");
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ // A key of its own on top; a fifth client refused, its step reloading
+ // every terminal in the unit of the pump the others take next; the key
+ // confirmed; the program prints on.
+ try key(b.r, 'l', &sent);
+ try std.testing.expectEqual(@as(usize, 1), b.r.applied);
+ const before = pardes.Term.reloads.n;
+ try std.testing.expect(try b.a.join(pardes.views.max + 1, null) == null);
+ const session = pardes.Term.reloads.n - before;
+ try std.testing.expect(session > 0);
+ b.a.pump();
+ b.r.confirm((try b.a.pending()).?);
+ b.r.confirm(try b.a.take(sent.items[0]));
+ b.r.settle();
+ try b.output("and on\r\n");
+ try std.testing.expectEqual(2 * session, pardes.Term.reloads.n - before);
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+}
+
+test "bytes: a join reloads only the terminals written since their last reload: one idle since the last join is reloaded on no side, and through a prune of both every side holds the session's terminals, the joiner too" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ b.r.confirm(try b.a.local(.{ .command = "Term" }));
+ b.r.settle();
+ const second: pardes.Pane.Id = for (b.a.core.panes, 0..) |slot, id| {
+ if (id != b.shell.index() and (slot orelse continue).terminal != null) break .at(id);
+ } else return error.NoTerminal;
+ const both = [_]pardes.Pane.Id{ b.shell, second };
+ // Both written, and a join reloads both.
+ for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = "written\r\n" } });
+ b.r.confirm((try b.a.pending()).?);
+ const first = (try b.a.join(2, null)).?;
+ gpa.free(first.dump);
+ b.r.confirm(first.unit);
+ // The shell alone written since: the next join reloads it alone, on
+ // every side; the joiner loads the other's snapshot as it was.
+ try b.output("the shell's\r\n");
+ const before = pardes.Term.reloads.n;
+ const joined = (try b.a.join(3, null)).?;
+ defer gpa.free(joined.dump);
+ try std.testing.expectEqual(1, pardes.Term.reloads.n - before);
+ b.r.confirm(joined.unit);
+ try std.testing.expectEqual(2, pardes.Term.reloads.n - before);
+ const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ late.t.screen_state = false;
+ late.core().echo = null;
+ try std.testing.expectEqual(joined.digest, late.digest());
+ // Output into both until each has pruned its history (whole pages, by
+ // the history of its pages), a unit every few reads.
+ var read: std.ArrayListUnmanaged(u8) = .empty;
+ defer read.deinit(gpa);
+ const lines = 40_000;
+ var n: usize = 0;
+ while (n < lines) : (n += 100) {
+ read.clearRetainingCapacity();
+ for (n..n + 100) |i| try read.print(gpa, "\x1b[3{d}m{d}\x1b[0m line\r\n", .{ i % 8, i });
+ for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = read.items } });
+ if (n % 2000 == 1900) {
+ const u = (try b.a.pending()).?;
+ b.r.confirm(u);
+ late.confirm(u);
+ }
+ }
+ if (try b.a.pending()) |u| {
+ b.r.confirm(u);
+ late.confirm(u);
+ }
+ for (both) |id| try std.testing.expect(pardes.Term.grid(b.a.core.panes[id.index()].?.terminal).total < lines);
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+ try agrees(b.a, late);
+ try sameTerminals(b.a, late);
+ // And a join after: both written, both reloaded, every hash compared.
+ const left = try b.a.leave(2, false);
+ b.r.confirm(left);
+ late.confirm(left);
+ const third = (try b.a.join(4, null)).?;
+ gpa.free(third.dump);
+ b.r.confirm(third.unit);
+ late.confirm(third.unit);
+ try agrees(b.a, b.r);
+ try agrees(b.a, late);
+}
+
test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
@@ -5143,6 +5302,212 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it
try agrees(a, back);
}
+test "a client cut off for what it left unread is told why and joins again for its view, kept for it meanwhile: it loads the session's dump and agrees" {
+ // A session's side of its clients' links in memory (`Peers.threads`
+ // false, the soak's): a connection handed to it and joined at its next
+ // boundary, the replica loaded from what its writer would write (the
+ // welcome, the dump with its blobs in place); and what it queued for one,
+ // down its link in order, the link's end after it if it was cut off.
+ const MemoryLinks = struct {
+ fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int) !struct { r: *Replica, peer: *Peer } {
+ const gpa = std.testing.allocator;
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ fd.* = fds[1];
+ ps.handed(fds[0], view);
+ ps.boundary(core);
+ const peer = for (ps.list) |slot| {
+ if (slot) |p| if (p.fd == fds[0]) break p;
+ } else return error.Refused;
+ const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome;
+ const w = (try wire.decodeServer(f.tag, f.payload)).welcome;
+ var whole: std.ArrayListUnmanaged(u8) = .empty;
+ defer whole.deinit(gpa);
+ var pos: usize = 0;
+ for (peer.blobs.items) |b| {
+ try whole.appendSlice(gpa, peer.dump[pos..b.at]);
+ try whole.appendSlice(gpa, b.bytes);
+ pos = b.at;
+ }
+ try whole.appendSlice(gpa, peer.dump[pos..]);
+ var word: [16]u8 = undefined;
+ const far = try wire.encodeClient(&word, .{ .far = false });
+ _ = peer.take(far[0], far[wire.header_len..]);
+ ps.post(.{ .joined = peer });
+ const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 });
+ if (!r.loaded(w.digest)) return error.LoadedAnother;
+ return .{ .r = r, .peer = peer };
+ }
+
+ fn down(peer: *Peer, link: *Link) !void {
+ var at: usize = 0;
+ while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) {
+ link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) {
+ .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) },
+ .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) },
+ else => return error.UnexpectedFrame,
+ });
+ }
+ peer.out.clearRetainingCapacity();
+ if (!peer.cut) return;
+ link.quit = true;
+ link.gone = true;
+ }
+ };
+ const gpa = std.testing.allocator;
+ const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
+ defer core.deinit();
+ core.host = TestHost.host();
+ try core.pump(core.host);
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false };
+ defer ps.deinit();
+ defer ps.dropAll(core);
+ var fd: c_int = -1;
+ const first = try MemoryLinks.join(&ps, core, null, &fd);
+ defer _ = libc.close(fd);
+ var link: Link = .{ .r = first.r, .fd = fd };
+ defer link.deinit(gpa);
+ const view = first.peer.view;
+ // The session's own input, taken by the client.
+ core.update(.{ .key = .{ .cp = 'i', .text = "i" } });
+ try core.pump(core.host);
+ ps.boundary(core);
+ try MemoryLinks.down(first.peer, &link);
+ try std.testing.expect(!link.quit and first.r.diverged == null);
+ // Its link stalls; the session goes on, and what waits for it passes
+ // the bound: it is cut off.
+ first.peer.limit = 16 << 10;
+ const text: [6000]u8 = @splat('t');
+ for (0..3) |_| {
+ core.update(.{ .paste = &text });
+ try core.pump(core.host);
+ ps.boundary(core);
+ }
+ try std.testing.expect(first.peer.cut);
+ try std.testing.expectEqual(@as(u32, 1), ps.cut);
+ try MemoryLinks.down(first.peer, &link);
+ try std.testing.expect(link.quit);
+ // It was told why, and joins again (as a divergence's client does)...
+ try std.testing.expect(link.rejoins());
+ try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null);
+ // ...once its old link's end is heard: its view kept for it meanwhile.
+ ps.post(.{ .gone = first.peer });
+ ps.boundary(core);
+ try std.testing.expect(pardes.views.isAway(core, view));
+ first.r.deinit();
+ _ = libc.close(fd);
+ const back = try MemoryLinks.join(&ps, core, view, &fd);
+ defer back.r.deinit();
+ try std.testing.expectEqual(view, back.peer.view);
+ link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view, .gmtoff = 0, .dump = &.{} });
+ core.update(.{ .paste = "back" });
+ try core.pump(core.host);
+ ps.boundary(core);
+ try MemoryLinks.down(back.peer, &link);
+ try std.testing.expect(!link.quit and back.r.diverged == null and back.r.quiet());
+ try std.testing.expectEqual(tape.digestOf(core), back.r.digest());
+}
+
+test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" {
+ const gpa = std.testing.allocator;
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
+ defer a.deinit();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ defer for (fds) |fd| {
+ _ = libc.close(fd);
+ };
+ var link: Link = .{ .r = r, .fd = fds[1] };
+ defer link.deinit(gpa);
+ const Late = struct {
+ // A unit the session made at `made` ms on its clock, taken at `at`
+ // ms on the client's.
+ fn take(l: *Link, from: *Authority, made: i64, at: u64) !void {
+ const u = try std.heap.c_allocator.dupe(u8, try from.local(.tick));
+ std.mem.writeInt(i64, u[14..22], made * std.time.ns_per_ms, .little);
+ l.now = at * std.time.ns_per_ms;
+ l.take(.{ .unit = u });
+ }
+ };
+ // The client's clock 5 s on from the session's, the link 100 ms: the
+ // second unit 1.9 s later than the first, the third 2.1 s.
+ try Late.take(&link, a, 0, 5_100);
+ try Late.take(&link, a, 1_000, 8_000);
+ try std.testing.expect(!link.quit);
+ try Late.take(&link, a, 1_100, 8_300);
+ try std.testing.expect(link.quit);
+ // A check answered after it let go, behind the unit it let go of: its
+ // core is behind on purpose, no divergence.
+ link.take(.{ .checked = digestOf(a) +% 1 });
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expect(link.rejoins());
+ try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice());
+ try std.testing.expect(!link.rejoins());
+ r.deinit();
+ // Joined again, its first unit 3 s later than any before (the session's
+ // clock stood still, its machine asleep; or the dump took that long):
+ // taken as the link now, not let go of again.
+ const back = try joinedNow(a, 1, 0);
+ defer back.deinit();
+ link.reset(back, &.{ .fd = fds[1], .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = &.{} });
+ try Late.take(&link, a, 2_000, 10_100);
+ try Late.take(&link, a, 2_100, 10_250);
+ try std.testing.expect(!link.quit and back.diverged == null);
+}
+
+test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and ends the link" {
+ const gpa = std.testing.allocator;
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io };
+ defer ps.deinit();
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ defer _ = libc.close(fds[1]);
+ const peer = try gpa.create(Peer);
+ peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = 0, .dump_gpa = gpa, .far = false, .limit = 256 << 10 };
+ peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len;
+ peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer});
+ defer ps.letGo(peer);
+ // Units its client does not read: the socket fills, the writer waits
+ // on it with a batch in hand, and the rest queues up to the bound.
+ const unit: [16 << 10]u8 = @splat('u');
+ const head = wire.header(@backingInt(wire.ServerTag.unit), unit.len);
+ // The first taken in hand.
+ peer.send(&.{ &head, &unit });
+ while (true) {
+ peer.lock.lockUncancelable(std.testing.io);
+ const taken = peer.out.items.len == 0;
+ peer.lock.unlock(std.testing.io);
+ if (taken) break;
+ std.Thread.yield() catch {};
+ }
+ var sent: u32 = 1;
+ while (!peer.cut) : (sent += 1) peer.send(&.{ &head, &unit });
+ const Heard = struct {
+ units: u32 = 0,
+ last: ?[]u8 = null,
+ fn post(h: *@This(), msg: Said) bool {
+ switch (msg) {
+ .unit => |b| {
+ std.heap.c_allocator.free(b);
+ h.units += 1;
+ },
+ .refused => |words| h.last = words,
+ else => return false,
+ }
+ return true;
+ }
+ };
+ var heard: Heard = .{};
+ var rest: Framer = .{};
+ defer rest.deinit(gpa);
+ readLink(gpa, fds[1], &rest, &heard, Heard.post);
+ const words = heard.last orelse return error.NotTold;
+ defer std.heap.c_allocator.free(words);
+ try std.testing.expectEqualStrings("0 MB behind the session", words);
+ try std.testing.expect(heard.units > 0 and heard.units < sent);
+}
+
test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" {
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
@@ -6357,25 +6722,28 @@ test "an idle client's check answered covers the units that came while it was as
_ = libc.close(fd);
};
var c: Link = .{ .r = r, .fd = fds[0], .now = std.time.ns_per_s };
+ // Each unit made as the client takes it, on its clock (Link.behind).
const unit = struct {
- fn of(au: *Authority) !Said {
- return .{ .unit = try std.heap.c_allocator.dupe(u8, try au.local(.tick)) };
+ fn of(au: *Authority, l: *const Link) !Said {
+ const u = try std.heap.c_allocator.dupe(u8, try au.local(.tick));
+ std.mem.writeInt(i64, u[14..22], @intCast(l.now.?), .little);
+ return .{ .unit = u };
}
}.of;
// Something changed, 300 ms quiet since its last input: asked.
- c.take(try unit(a));
+ c.take(try unit(a, &c));
try std.testing.expectEqual(@as(?u32, null), c.quietCheck());
try std.testing.expect(c.asked);
// The session's pump for it (a unit), then the answer: agreed, and
// nothing to ask after it however long it stays quiet.
- c.take(try unit(a));
+ c.take(try unit(a, &c));
c.take(.{ .checked = digestOf(a) });
try std.testing.expect(!c.asked and c.r.diverged == null);
c.now.? += 10 * std.time.ns_per_s;
try std.testing.expectEqual(@as(?u32, null), c.quietCheck());
try std.testing.expect(!c.asked);
// A unit after it is a change again.
- c.take(try unit(a));
+ c.take(try unit(a, &c));
c.now.? += std.time.ns_per_s;
_ = c.quietCheck();
try std.testing.expect(c.asked);
diff --git a/core/tape.zig b/core/tape.zig
index 7f28621e..88a7047b 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -132,9 +132,9 @@ pub const Site = enum(u16) {
/// What a call into a kind did (Kind.Outcome), and a kind's pane's
/// tag prefix: the authority's, whose core alone runs the kind.
addon,
- /// The hash of a terminal's snapshot as the session reloaded it at a
- /// join (panes.reloadTerminals), which every replica's own reload
- /// compares.
+ /// Whether the session reloads a terminal at a join (written since its
+ /// last reload), then the hash of its snapshot as it did
+ /// (panes.reloadTerminals), which every replica's own reload compares.
reload,
/// A kitty image's medium as a terminal's emulator read it (a file, a
/// temporary file, shared memory: Term.media), its bytes or its failure.
@@ -1493,15 +1493,19 @@ pub fn endSpeculation(t: *Tape) bool {
/// a message may be (replica.zig `lag_max`'s neighbour, wire's bound).
pub const unit_max = 1 << 20;
-/// Whether a unit feeds a terminal its program's output (a pty's read; an
-/// input kept by hash is taken to): never taken as moving nothing (the
-/// replica engine's one rule, core/replica.zig `confirm`).
+/// Whether a unit writes a terminal's emulator: feeds one its program's
+/// output (a pty's read; an input kept by hash is taken to), or reloads
+/// every one at a join (`Site.reload`; a join refused too, which moves
+/// nothing a digest covers): never taken as moving nothing (the replica
+/// engine's one rule, core/replica.zig `confirm`).
pub fn feedsTerminal(bytes: []const u8) bool {
const Tag = std.meta.Tag(Input);
const EventTag = std.meta.Tag(pardes.Event);
+ const reload: u16 = @as(u16, host_fns.len) + @backingInt(Site.reload);
var r: walk.Reader = .{ .bytes = bytes };
while (nextRecord(&r)) |rec| switch (rec.kind) {
.blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true,
+ .host => if (rec.payload.len >= 2 and std.mem.bytesToValue(u16, rec.payload[0..2]) == reload) return true,
.input => {
if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue;
if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue;
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
index e57193a6..1673a3d8 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -1792,3 +1792,34 @@ test "a join at a cut: every side reloaded from its own snapshot holds the same
// another terminal once heavy colour has pruned pages cut otherwise.
try std.testing.expectEqual(2, heavy_apart);
}
+
+test "wide characters filling a scrollback past its limit, reflowed: its snapshot loads to the same snapshot and hash, and goes on as the same terminal through more bytes and reflows" {
+ // The soak's `cat` (test/replicas.zig): source lines, one in a few
+ // hundred with wide characters (CJK, box drawing, ambiguous symbols),
+ // a full scrollback pruned a page at a time, reflowed at odd widths
+ // where a wide character meets the right edge.
+ const gpa = std.testing.allocator;
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ defer out.deinit();
+ const wide = " try writeText(notes, \"# Fallback faces and rules\\n\\n| name | glyphs |\\n|------|--------|\\n| cjk | \u{754C}\u{9762}\u{5B57} |\\n| sym | \u{222E} \u{2260} \u{2605} |\\n\\n\u{250C}\u{2500}\u{2500}\u{252C}\u{2500}\u{2500}\u{2510}\\n\u{2502} a\u{2502} b\u{2502}\\n\u{2514}\u{2500}\u{2500}\u{2534}\u{2500}\u{2500}\u{2518}\\n\");";
+ for (0..30000) |i| {
+ if (i % 7 == 3) try out.writer.print("{s}\r\n", .{wide}) else try out.writer.print("{s} {d}\r\n", .{ " const line = std.fmt.bufPrint(&buf, \"{d}\", .{i}) catch continue;"[0 .. 8 + i % 60], i });
+ }
+ const bytes = out.written();
+ const stops: [2]usize = .{ bytes.len / 3, 2 * bytes.len / 3 };
+ const first = try openKeeping(gpa, 121, 40, 1 << 20);
+ defer close(first);
+ feedReflowing(first, bytes, 0, bytes.len / 2, stops);
+ const snap = try snapshotOf(gpa, first);
+ defer gpa.free(snap);
+ const loaded = try load(gpa, snap, &parts(first));
+ defer close(loaded);
+ const again = try snapshotOf(gpa, loaded);
+ defer gpa.free(again);
+ try std.testing.expectEqualSlices(u8, snap, again);
+ try std.testing.expectEqual(joinHash(snap), try reload(first));
+ try expectSame(gpa, first, loaded);
+ feedReflowing(first, bytes, bytes.len / 2, bytes.len, stops);
+ feedReflowing(loaded, bytes, bytes.len / 2, bytes.len, stops);
+ try expectSame(gpa, first, loaded);
+}