summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-19 22:06:32 -0300
committerGabriel Schneider <[email protected]>2026-11-20 00:38:51 -0300
commit2662a45ac245e574987bf6876f4470aed89da09c (patch)
treec582032cde0cb742a67e2dd548022f7b83f8d1fd /core
parentba10cc4ff30d08d27ad35576df04a03282b6521b (diff)
downloadpardes-2662a45ac245e574987bf6876f4470aed89da09c.tar.gz
pardes-2662a45ac245e574987bf6876f4470aed89da09c.zip
replica: the bytes kind of replica made right and joinable (P29, P32; the brief's step 2: 2a, 2b, 2c and 2d in one change): the one rule in place of two, the faults shown first (a session's output kept over a copy held ahead was fed again by a rollback: the digests apart; the pages an emulator gained while a copy was held were the epoch's and freed with it: a crash in PageList.increaseCapacity in the rollback's replay): every replica's emulators on the C heap (panes.emulatorGpa), Term.writes counting the writes into emulators, a unit whose replay wrote one never kept over a copy taken ahead, never taken as moving nothing (tape.feedsTerminal), a client's input that owed a reflow always replayed when confirmed; a speculation moves a terminal's view under bytes as under screen state; tape.unit_max (1 MiB) and Tape.cut, which the session's Peers sets, so a pump's reads are cut into units under it; the join: whole terminals in a joiner's dump, every replica the session included reloading each live terminal in the step that opens or reopens a view (panes.reloadTerminals), the session's hash taped (Site.reload) and compared, kitty records left out of it, the cell pixels set first as a feed does; .positions and .prompt compared with the replica's own emulator on replay; replicas load kitty images by direct data only (Term.direct); Peers.bytes for the soak; six tests (core/replica.zig, bytes:); tui core-test 848/997 (149 skipped), shell-test 1033/1036, pane-test 183/184, term-test 17/17, kitty-test 45/45, behaviour-test 275/275 and --replay 0, process-test 2 of 144 (the base's), image- and kitty-harness pass, unit-test bytes: 22/22; gui unit-test 1633/1637 (the perf check's BaselineHarnessMismatch); the soaks in klrvlrly's
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core')
-rw-r--r--core/Core.zig2
-rw-r--r--core/Term.zig32
-rw-r--r--core/dump.zig7
-rw-r--r--core/panes.zig44
-rw-r--r--core/replica.zig247
-rw-r--r--core/root.zig1
-rw-r--r--core/tape.zig60
-rw-r--r--core/term/term.zig1
-rw-r--r--core/term/terminal.zig45
9 files changed, 406 insertions, 33 deletions
diff --git a/core/Core.zig b/core/Core.zig
index d5a990e2..9bc40775 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -1175,6 +1175,7 @@ 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();
+ pardes.panes.reloadTerminals(p);
p.needs_frame = true;
return .at(Views.open(p) orelse return null);
}
@@ -1217,6 +1218,7 @@ fn rejoinViewInner(p: *Pardes, k: View.Id) bool {
if (!Views.isAway(p, k.index())) return false;
p.views_away &= ~(@as(u8, 1) << @intCast(k.index()));
p.settle();
+ pardes.panes.reloadTerminals(p);
p.needs_frame = true;
return true;
}
diff --git a/core/Term.zig b/core/Term.zig
index 82d5dad7..9f5d6362 100644
--- a/core/Term.zig
+++ b/core/Term.zig
@@ -14,6 +14,15 @@ const dump = @import("dump.zig");
const File = @import("File.zig");
const iface = plain.term;
+/// Writes into this process's emulators (a read fed, a grid reflowed, a
+/// view moved, one opened, closed, loaded or made again): whether a unit's
+/// replay made one, the replica engine's one rule (core/replica.zig
+/// `confirm`) reads across that replay, on its one thread.
+pub var writes: u32 = 0;
+/// The reloads this process made (a join's, on every side) and their time,
+/// for the soak's join line (test/replicas.zig `--bytes`).
+pub var reloads: struct { n: u32 = 0, ns: u64 = 0, worst_ns: u64 = 0 } = .{};
+
/// The terminal module's entries; null in a core built without it.
pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null;
@@ -94,6 +103,9 @@ pub const State = struct {
defer arena.deinit();
const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null);
out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) };
+ writes +%= 1;
+ // A replica's (a join's, a closed terminal brought back in a step).
+ if (tape.replaying() or dump.terminal_gpa != null) o.direct(out.impl);
}
};
@@ -114,6 +126,10 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
const s = try gpa.create(State);
errdefer gpa.destroy(s);
s.* = .{ .impl = try o.open(gpa, cols, rows) };
+ writes +%= 1;
+ // A replica's emulator loads its program's images by direct data alone
+ // (P32): what is read off the session's machine is the session's.
+ if (tape.replaying()) o.direct(s.impl);
return s;
}
@@ -121,6 +137,7 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
/// one it was opened with): the allocator a caller hands is not used.
pub fn close(s: *State, _: std.mem.Allocator) void {
const own = the().gpa(s.impl);
+ writes +%= 1;
the().close(s.impl);
own.destroy(s);
}
@@ -130,6 +147,14 @@ pub fn close(s: *State, _: std.mem.Allocator) void {
/// history a page at a time, and a snapshot does not say how its rows were
/// cut into pages). The snapshot's hash, which every side compares.
pub fn reload(s: *State) !u64 {
+ writes +%= 1;
+ const t0 = @import("FrameStats.zig").nowNs();
+ defer {
+ reloads.n += 1;
+ const dt = @import("FrameStats.zig").nowNs() -| t0;
+ reloads.ns += dt;
+ reloads.worst_ns = @max(reloads.worst_ns, dt);
+ }
return the().reload(s.impl);
}
@@ -142,6 +167,7 @@ pub fn due(s: *const State) ?u64 {
/// Loaded from a dump without its shell: its program's modes reset, its
/// history marked off from what the next shell prints.
pub fn revive(s: *State) void {
+ writes +%= 1;
the().revive(s.impl);
}
@@ -160,6 +186,7 @@ pub fn stop() void {
/// One read of its program's output (`Told` says where the tracked rows
/// went).
pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told {
+ writes +%= 1;
return the().feed(s.impl, bytes, tracked, rows, erased);
}
@@ -171,25 +198,30 @@ pub fn grid(s: ?*const State) Grid {
/// Its view to a row of its history, or onto its output (null).
pub fn viewTo(s: *State, at: ?usize) void {
+ writes +%= 1;
the().viewTo(s.impl, at);
}
/// Its view moved by a number of rows (negative scrolls back).
pub fn scroll(s: *State, delta: i32) void {
+ writes +%= 1;
the().scroll(s.impl, delta);
}
/// Its view back onto its output.
pub fn follow(s: *State) void {
+ writes +%= 1;
the().follow(s.impl);
}
/// Its grid reflowed, now or when `resizeDeferred` makes it.
pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void {
+ writes +%= 1;
the().resize(s.impl, cols, rows, later);
}
pub fn resizeDeferred(s: *State) bool {
+ writes +%= 1;
return the().resizeDeferred(s.impl);
}
diff --git a/core/dump.zig b/core/dump.zig
index 1616f557..f1d4ed26 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -261,7 +261,9 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 {
/// first delta brings each afresh). What is left is the session's mutable
/// state, made in its step.
pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 {
- slim_terminals = true;
+ // Under bytes, each terminal whole (as the join's step reloaded it on
+ // every side: panes.reloadTerminals), its sequence in flight with it.
+ slim_terminals = p.tape.screen_state;
defer slim_terminals = false;
// The join's file reads are the session's host's, between its steps:
// with its io, which the core's tape holds (a walk's hook takes no more).
@@ -270,7 +272,8 @@ pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![
return dumpWith(p, deferred);
}
-/// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator.
+/// `dumpJoin`'s under screen state and `dumpExit`'s: a terminal dumps its
+/// size, not its emulator.
pub var slim_terminals = false;
/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file),
/// read with this io.
diff --git a/core/panes.zig b/core/panes.zig
index 56a8e82a..61c57541 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -966,15 +966,17 @@ pub const Pane = struct {
/// replica by its authority (the next delta says), on such an authority
/// once the step's unit is out (`resizeDeferred`).
pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void {
- // A screen-state client's speculation does what its replay does
- // (its selections, never the grid): it waits for no round trip.
- if (!tape.screenState() and tape.authorityOnly("resize a terminal")) return;
+ // A client's speculation does what its replay does (its
+ // selections) but the grid: it waits for no round trip. Under bytes
+ // it owes the grid (`touchTerminal`): its input is replayed when
+ // confirmed, never taken as speculated (replica.zig `confirm`).
const state = pane.terminal orelse return;
if (cols != pane.cols) for (0..pane.sel.len) |button| {
pane.clearPointerSelection(button);
pane.sel[button].state = .none;
};
if (tape.screenReplica()) return;
+ if (tape.speculating()) return tape.touchTerminal();
// A client typing at another size than the last typist's read
// history rows its replay held as holes, and the rows came
// renumbered (2026-10-30): the authority's waits for the unit.
@@ -1117,6 +1119,31 @@ pub const Term = @import("Term.zig");
/// not follow the output (no memory for its pin), so it was reset.
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
+/// 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| {
+ // 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.
+ Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h);
+ const mine: ?u64 = Term.reload(state) catch null;
+ p.shell_rows.markStale(pane);
+ if (tape.value(.reload, sameHash, .{mine}) != mine) tape.diverged("a terminal reloaded at a join is not the session's");
+ };
+}
+
+fn sameHash(h: ?u64) ?u64 {
+ return h;
+}
+
/// 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 {
@@ -1147,16 +1174,17 @@ pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
return pane;
}
-/// A screen-state replica's emulators' allocator (`Term.State.gpa`): the C
-/// heap, outside its rollback epoch: written by deltas while a copy is
-/// held, no part of it is ever a copy's to save or put back.
+/// A replica's emulators' allocator (`Term.State.gpa`): the C heap,
+/// outside its rollback epoch: written (by the session's bytes or deltas)
+/// while a copy is held, no part of it is ever a copy's to save or put
+/// back, or the pages an emulator gains then are freed with the copy.
pub const emulator_gpa = std.heap.c_allocator;
/// What a terminal's emulator is made with, by `createTerminal` or a pane's
/// load (dump.loadPane, a closed terminal brought back): `gpa`, but on a
-/// screen-state replica `emulator_gpa`.
+/// replica `emulator_gpa`.
pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator {
- return if (tape.screenReplica()) emulator_gpa else gpa;
+ return if (tape.replaying()) emulator_gpa else gpa;
}
// ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ----
diff --git a/core/replica.zig b/core/replica.zig
index c68848f2..39af9404 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -905,7 +905,7 @@ pub const Replica = struct {
// nothing ends on again (`neutral`); none, not known.
r.last_digest.clearRetainingCapacity();
if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {};
- if (r.pending.items[0].terminal and r.applied > 1) {
+ if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) {
// Right, but what it did read a terminal: replayed later (a
// rollback's `since`) it would read the deltas that came
// after it. So it is taken now, over the emulator its step
@@ -959,7 +959,12 @@ pub const Replica = struct {
r.last_digest.clearRetainingCapacity();
if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {};
}
- if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) {
+ // 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).
+ 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)))
+ {
// Nothing a digest covers moved: what was applied on top is
// what the session will apply on top of it. Replayed when the
// copy is next put back.
@@ -992,6 +997,7 @@ pub const Replica = struct {
// replayed by a rollback were, if at all, as they came).
const check = ends != null and r.checkDue();
r.t.checks = check;
+ const writes = Term.writes;
const replayed = tape.replayUnit(&r.t, u.tape);
r.t.checks = false;
if (replayed) |why| {
@@ -1015,10 +1021,15 @@ pub const Replica = struct {
// or freed here, and is not put back with the copy: a rollback
// replaying the unit again would close a terminal freed already (the
// soak, a `Del` of the shell). Let go with the copy.
+ // The one rule: a unit that wrote an emulator (a terminal's output,
+ // a grid reflowed, a view moved, one reloaded at a join) wrote what
+ // no copy holds: kept, a rollback would replay it into what it
+ // wrote already (the bytes fed twice). It goes with the copy: the
+ // state is the confirmed one, nothing being on top.
const c = r.core();
for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null;
for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n;
- if (retiring) {
+ if (retiring or (!r.t.screen_state and Term.writes != writes)) {
r.copy.release();
rollback.Epoch.select(null);
return r.clearSince();
@@ -1139,7 +1150,9 @@ pub const Replica = struct {
const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false;
c.update(in.event);
c.step();
- p.terminal = r.t.screen_state and (keyboard or r.t.touched);
+ // Under bytes: it owes an emulator a write it skipped (a grid's
+ // size), replayed when confirmed.
+ p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched;
const clean = tape.endSpeculation(&r.t);
const dt = nowNs() - t0;
// Where a blob was written, should one be: the input that did.
@@ -1215,7 +1228,6 @@ pub const Replica = struct {
r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| {
if (x != null or y != null) break true;
} else false;
- if (!r.t.screen_state) return;
for (r.core().panes, &r.views) |slot, *v| v.* = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null;
}
@@ -1230,7 +1242,6 @@ pub const Replica = struct {
}
fn putViews(r: *Replica) void {
- if (!r.t.screen_state) return;
for (r.core().panes, r.views) |slot, at| if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, at);
}
@@ -2055,6 +2066,10 @@ pub const Peers = struct {
/// After each flush of a client's terminals, told: the soak's record
/// of each terminal as each version left it (test/replicas.zig).
flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null,
+ /// Its clients' terminals cross as the pty's bytes in its units, each
+ /// client's emulator its own (P29, P32), not as screen state: the
+ /// soak's (test/replicas.zig `--bytes`), until the switch.
+ bytes: bool = false,
pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer };
/// A connection to join, and the view it joins again for, if it does.
@@ -2175,6 +2190,14 @@ pub const Peers = struct {
ps.screensOut(core, .flush);
}
+ /// What its steps recorded passed a unit's bound (`tape.unit_max`): a
+ /// unit of its own now, between two inputs of the pump (Tape.cut).
+ fn cutUnit(ctx: *anyopaque) void {
+ const ps: *Peers = @ptrCast(@alignCast(ctx));
+ ps.seq += 1;
+ ps.unit(0, ps.seq);
+ }
+
const ScreensOut = enum { flush, fill };
/// What each client is owed of the terminals (`Screens.flush`), or the
@@ -2186,6 +2209,7 @@ pub const Peers = struct {
}
fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void {
+ if (ps.bytes) return;
defer {
for (ps.msgs.items) |m| ps.gpa.free(m);
ps.msgs.clearRetainingCapacity();
@@ -2219,8 +2243,9 @@ pub const Peers = struct {
ps.t.unit_digests = true;
// Terminals cross as screen state: a unit carries no pty bytes,
// and its digest is a word (PARDES_REPLICA_TRACE: one a field).
- ps.t.screen_state = true;
+ ps.t.screen_state = !ps.bytes;
ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null;
+ ps.t.cut = .{ .ctx = ps, .f = cutUnit };
ps.screens = .init(ps.gpa);
tape.on = &ps.t;
core.tape = &ps.t;
@@ -4139,6 +4164,214 @@ test "a unit that closes or tears down a terminal is never kept over a copy take
try std.testing.expectEqual(a.core.store.closed.items.len, r.core().store.closed.items.len);
}
+/// The emulators of a session's and a replica's terminals as a dump keeps
+/// them (what pardes keeps beside each, its whole snapshot): the same
+/// bytes, or a test fails.
+fn sameTerminals(a: *Authority, r: *Replica) !void {
+ const gpa = std.testing.allocator;
+ for (a.core.panes, r.core().panes) |x, y| {
+ const theirs = (x orelse continue).terminal orelse continue;
+ const mine = (y orelse return error.NoPane).terminal orelse return error.NoTerminal;
+ var w1: std.Io.Writer.Allocating = .init(gpa);
+ defer w1.deinit();
+ var w2: std.Io.Writer.Allocating = .init(gpa);
+ defer w2.deinit();
+ try theirs.dumpWrite(gpa, &w1.writer);
+ try mine.dumpWrite(gpa, &w2.writer);
+ try std.testing.expectEqualSlices(u8, w1.written(), w2.written());
+ }
+}
+
+/// A session and a replica of the bytes kind (its terminals fed the pty's
+/// bytes the session's units carry), the session's view on its text pane,
+/// and the shell's slot.
+const BytesPair = struct {
+ a: *Authority,
+ r: *Replica,
+ shell: pardes.Pane.Id,
+
+ fn init() !BytesPair {
+ const gpa = std.testing.allocator;
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false);
+ errdefer a.deinit();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ var shell: ?pardes.Pane.Id = null;
+ for (a.core.panes, 0..) |slot, id| if (slot) |pane| {
+ if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id);
+ };
+ const pair: BytesPair = .{ .a = a, .r = r, .shell = shell orelse return error.NoShell };
+ r.confirm(try a.local(.{ .focus = true }));
+ return pair;
+ }
+
+ fn deinit(b: BytesPair) void {
+ b.r.deinit();
+ b.a.deinit();
+ }
+
+ /// The session's program prints `bytes`, a unit of its own the replica takes.
+ fn output(b: BytesPair, bytes: []const u8) !void {
+ b.a.output(.{ .output = .{ .pane = b.shell, .bytes = bytes } });
+ b.r.confirm((try b.a.pending()).?);
+ b.r.settle();
+ }
+
+ /// The client types a key over the text, and the session's own key
+ /// comes first: a rollback, which replays what was kept since the copy.
+ fn rollback(b: BytesPair) !void {
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| std.testing.allocator.free(m);
+ sent.deinit(std.testing.allocator);
+ }
+ try key(b.r, 'l', &sent);
+ try std.testing.expectEqual(@as(usize, 1), b.r.applied);
+ b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } }));
+ b.r.settle();
+ b.r.confirm(try b.a.take(sent.items[0]));
+ b.r.settle();
+ }
+};
+
+test "bytes: a session's output taken over a copy held ahead is fed once: a rollback does not feed it again" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const b = try BytesPair.init();
+ defer b.deinit();
+ b.r.ready();
+ try std.testing.expect(b.r.copy.held);
+ try b.output("one line of the program's\r\n");
+ try b.rollback();
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+}
+
+test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const b = try BytesPair.init();
+ defer b.deinit();
+ b.r.ready();
+ // Pages and their side tables the emulator had not: thousands of rows,
+ // a colour and a link a word.
+ var line: [128]u8 = undefined;
+ for (0..3000) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i }) } });
+ b.r.confirm((try b.a.pending()).?);
+ try b.rollback();
+ try b.output("after\r\n");
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+}
+
+test "bytes: a session's output that moves nothing the digest covers (a colour set) is never taken as moving nothing: it is fed, at its place" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const b = try BytesPair.init();
+ defer b.deinit();
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| std.testing.allocator.free(m);
+ sent.deinit(std.testing.allocator);
+ }
+ // A key of its own applied on top, the session's colour comes, then the
+ // key is confirmed, and the session's next output is in that colour.
+ try key(b.r, 'l', &sent);
+ try std.testing.expectEqual(@as(usize, 1), b.r.applied);
+ try b.output("\x1b[31m");
+ b.r.confirm(try b.a.take(sent.items[0]));
+ b.r.settle();
+ try b.output("red\r\n");
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+}
+
+test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ // The program hears every motion, in SGR form.
+ try b.output("\x1b[?1003h\x1b[?1006h");
+ const at = b.a.core.view().rects[b.shell.index()];
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ // Its speculation encodes the motion (the cell noted) and stops at the
+ // pty's write; the session's unit for it is replayed.
+ try sent.append(gpa, try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .none, .kind = .motion, .col = at.x + 3, .row = at.y + at.h / 2 } })));
+ b.r.confirm(try b.a.take(sent.items[0]));
+ b.r.settle();
+ try agrees(b.a, b.r);
+}
+
+test "bytes: a client joins from a dump with its terminals whole, and every side, the session too, reloads each terminal in the step that opens its view: their hashes agree, and all go on as one" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ // History with colours and links, a sequence left open at the cut.
+ var line: [128]u8 = undefined;
+ for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i }));
+ try b.output("half a colour: \x1b[38;2;10;20");
+ const reloads = pardes.Term.writes;
+ const joined = (try b.a.join(2, null)).?;
+ defer gpa.free(joined.dump);
+ b.r.confirm(joined.unit);
+ try std.testing.expect(b.r.diverged == null);
+ try std.testing.expect(pardes.Term.writes != reloads);
+ const late = try Replica.initDump(gpa, 2, 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());
+ b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } });
+ const rest = (try b.a.pending()).?;
+ b.r.confirm(rest);
+ late.confirm(rest);
+ late.settle();
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+ try agrees(b.a, late);
+ try sameTerminals(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;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ const Cuts = struct {
+ a: *Authority,
+ units: std.ArrayListUnmanaged([]u8) = .empty,
+ fn cut(ctx: *anyopaque) void {
+ const c: *@This() = @ptrCast(@alignCast(ctx));
+ c.a.batched = 0;
+ c.a.seq += 1;
+ const u = c.a.unit(0, c.a.seq) catch unreachable;
+ c.units.append(std.testing.allocator, std.testing.allocator.dupe(u8, u) catch unreachable) catch unreachable;
+ }
+ };
+ var cuts: Cuts = .{ .a = b.a };
+ defer {
+ for (cuts.units.items) |u| gpa.free(u);
+ cuts.units.deinit(gpa);
+ }
+ b.a.t.cut = .{ .ctx = &cuts, .f = Cuts.cut };
+ defer b.a.t.cut = null;
+ // A pump's worth of reads, 64 KiB each, 3 MiB in all.
+ var read: [64 * 1024]u8 = undefined;
+ for (&read, 0..) |*c, i| c.* = if (i % 80 == 79) '\n' else @intCast('a' + i % 26);
+ for (0..48) |_| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = &read } });
+ try std.testing.expect(cuts.units.items.len >= 2);
+ for (cuts.units.items) |u| {
+ try std.testing.expect(u.len <= tape.unit_max + read.len + 4096);
+ b.r.confirm(u);
+ }
+ if (try b.a.pending()) |u| b.r.confirm(u);
+ b.r.settle();
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+}
+
test "a replica joined from the session's dump replays the units after it" {
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
diff --git a/core/root.zig b/core/root.zig
index 69ec3ded..423eed35 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -460,6 +460,7 @@ const allowed_vars = [_]struct { []const u8, []const u8, []const u8 }{
.{ "Kind.zig", "ready", "this process's draws done, each keyed by its core, pane and serial" },
.{ "Names.zig", "dp_rows dp_trace", "the scorer's scratch, written before it is read in one call" },
.{ "Turn.zig", "yield_depth", "this thread's nesting of yields (threadlocal)" },
+ .{ "Term.zig", "writes reloads", "this process's emulators' writes, read across one replay on its thread (the replica engine's one rule), and its reloads' count and time" },
.{ "c_heap.zig", "allocators allocators_len allocators_lock last", "the C heap's registry of allocators and its lookup's memo" },
.{ "c_heap.zig", "test_allocator stateless", "its tests'" },
.{ "config.zig", "other_build addon_sources", "the docs check's data, a test's" },
diff --git a/core/tape.zig b/core/tape.zig
index 00486666..69b74bc4 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -131,6 +131,10 @@ 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.
+ reload,
};
/// What the sites return. wire.semantics hashes their shape with the
@@ -297,6 +301,10 @@ pub const Tape = struct {
/// not recorded, and no digest covers it. A replica's core never writes
/// one but by `apply`.
screen_state: bool = false,
+ /// The session's (replica.Peers): called between two of its inputs once
+ /// what it recorded since its last unit passes `unit_max`, to send that
+ /// as a unit: a pump of a flood's reads is cut into units under it.
+ cut: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque) void } = null,
/// A digest as one word (screen-state replicas: every unit of a pty's
/// output carries one, at the pty's read rate), not one a field; what
/// differs is then not named.
@@ -440,6 +448,7 @@ pub const Tape = struct {
if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t);
if (t.depth == 0) t.flush();
t.seeFields();
+ if (t.depth == 0 and t.buf.items.len >= unit_max) if (t.cut) |c| c.f(c.ctx);
}
// ---- replaying ----
@@ -803,6 +812,16 @@ pub const Tape = struct {
// Diverged (said in `diverged`): what a speculation gets, harmless,
// for the rest of the input. A replica joins again; a replay says so.
if (!t.expectHost(id, @tagName(s))) return poisonOf(R);
+ // What a terminal told (its rows moved, its prompt, a command's
+ // output) is the session's answer, kept, and a replica whose
+ // emulators are fed the same bytes asks its own and compares: a
+ // check a unit, for nothing (P30: a digest, not state).
+ if (comptime s == .positions or s == .prompt) if (!t.screen_state) {
+ const mine = @call(.auto, f, full);
+ t.scratch.clearRetainingCapacity();
+ walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory");
+ if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s});
+ };
var ret = t.last_ret;
return walk.decode(R, &ret, a orelse t.arena.allocator()) catch {
t.diverge("the tape's answer to {t} is short", .{s});
@@ -882,17 +901,12 @@ pub const Tape = struct {
return true;
}
- /// A speculation that moves a terminal's view: a screen-state replica's
- /// may (its rollback puts the view back, replica.zig `views`, and a delta
- /// sets it), any other stops (`authorityOnly`).
- pub fn viewOnly(t: *Tape, comptime why: []const u8) bool {
- if (!t.speculating) return false;
- if (t.screen_state) {
- t.touched = true;
- return false;
- }
- t.poison(why);
- return true;
+ /// A speculation that moves a terminal's view: it may (its rollback
+ /// puts the view back, replica.zig `views`); a screen-state replica's
+ /// says it did (a delta sets the view again).
+ pub fn viewOnly(t: *Tape, comptime _: []const u8) bool {
+ if (t.speculating and t.screen_state) t.touched = true;
+ return false;
}
/// A speculation read a terminal's rows or moved its view (`Tape.touched`).
@@ -1505,6 +1519,30 @@ pub fn endSpeculation(t: *Tape) bool {
return !t.poisoned;
}
+/// About what a unit of the session's holds at most (`Tape.cut`): a pump
+/// takes up to 496 reads of 64 KiB, which as one unit could pass the 16 MiB
+/// 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`).
+pub fn feedsTerminal(bytes: []const u8) bool {
+ const Tag = std.meta.Tag(Input);
+ const EventTag = std.meta.Tag(pardes.Event);
+ 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,
+ .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;
+ if (std.mem.eql(u8, rec.payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)], std.mem.asBytes(&@as(EventTag, .output)))) return true;
+ },
+ else => {},
+ };
+ return false;
+}
+
/// Whether two tapes record the same inputs, host calls and answers,
/// their digests aside.
pub fn sameRecords(a: []const u8, b: []const u8) bool {
diff --git a/core/term/term.zig b/core/term/term.zig
index 4bb60079..b18f5875 100644
--- a/core/term/term.zig
+++ b/core/term/term.zig
@@ -32,6 +32,7 @@ pub const ops: iface.Ops = .{
.snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot),
.load = cast(iface.Ops, "load", terminal_.load),
.reload = cast(iface.Ops, "reload", terminal_.reload),
+ .direct = cast(iface.Ops, "direct", terminal_.direct),
.feed = cast(iface.Ops, "feed", terminal_.feed),
.grid = cast(iface.Ops, "grid", terminal_.grid),
.viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo),
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
index 4de389bd..055c8981 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -195,6 +195,11 @@ pub const State = struct {
/// the step reads the grid it had, as its replicas' replays do, and the
/// rows sent them for it (Screens.fill) are of that grid's numbering.
resize_to: ?struct { cols: u16, rows: u16 } = null,
+ /// Its program's kitty images by direct data alone (`direct`): a
+ /// replica's emulator, which is not the session's. A file, a temporary
+ /// file or shared memory is the session's machine's (and a temporary
+ /// one is deleted by its first reader): its image is absent here.
+ direct: bool = false,
/// The stream over the emulator, its answers to the program and its
/// size reports routed here, PNG decoded: what `create` and a dump's
@@ -338,15 +343,35 @@ pub fn reload(s: *State) !u64 {
var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined;
@memcpy(reply[0..saved.reply.len], saved.reply);
saved.reply = reply[0..saved.reply.len];
- const kept = .{ s.changes, s.read, s.resize_to };
+ const kept = .{ s.changes, s.read, s.resize_to, s.direct };
if (comptime images_enabled) s.images.deinit(gpa);
s.stream.deinit();
s.vt.deinit(gpa);
- s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] };
+ s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2], .direct = kept[3] };
// Short of room for its sequence in flight it goes on without it (lost
// at the next cut), as ghostty's stream does: not worth a terminal.
_ = install(s, decoded.continuation, &saved);
- return std.hash.Wyhash.hash(0, bytes.written());
+ return joinHash(bytes.written());
+}
+
+/// What a join compares of a snapshot (`reload`): every record of it but
+/// its kitty images' (tags 8 to 10, which ghostty's framing makes optional:
+/// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload,
+/// after a 10-byte envelope): an image by file or shared memory is the
+/// session's alone (P32, `direct`), and no digest reads an image.
+fn joinHash(bytes: []const u8) u64 {
+ const envelope = 10;
+ const head = 10;
+ var h: std.hash.Wyhash = .init(0);
+ h.update(bytes[0..@min(bytes.len, envelope)]);
+ var at: usize = envelope;
+ while (at + head <= bytes.len) {
+ const tag = std.mem.readInt(u16, bytes[at..][0..2], .little);
+ const end = @min(bytes.len, at + head + std.mem.readInt(u32, bytes[at + 2 ..][0..4], .little));
+ if (tag < 8 or tag > 10) h.update(bytes[at..end]);
+ at = end;
+ }
+ return h.final();
}
/// A decoded emulator at its address made a terminal: its stream wired,
@@ -354,7 +379,7 @@ pub fn reload(s: *State) !u64 {
/// whether its stream had all the room it wanted (`wire`).
fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool {
if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| {
- if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir());
+ if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = if (out.direct) .direct else .allWithTempDir(tempDir());
};
const whole = out.wire();
switch (continuation) {
@@ -384,6 +409,16 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *
return whole;
}
+/// Its program's kitty images by direct data alone from now on: the
+/// emulator of a replica that is not the session (P32).
+pub fn direct(s: *State) void {
+ if (comptime !images_enabled) return;
+ s.direct = true;
+ inline for (.{ .primary, .alternate }) |which| {
+ if (s.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .direct;
+ }
+}
+
/// The allocator it was opened with, its own from then on.
pub fn gpaOf(s: *const State) std.mem.Allocator {
return s.gpa;
@@ -1748,7 +1783,7 @@ test "a join at a cut: every side reloaded from its own snapshot holds the same
// the session's snapshot taken after (the join's dump).
const hash = try reload(session);
try std.testing.expectEqual(hash, try reload(there));
- try std.testing.expectEqual(hash, std.hash.Wyhash.hash(0, before));
+ try std.testing.expectEqual(hash, joinHash(before));
const after = try snapshotOf(gpa, session);
defer gpa.free(after);
const joiner = try load(gpa, after, &parts(session));