summaryrefslogtreecommitdiff
path: root/core/replica.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/replica.zig')
-rw-r--r--core/replica.zig570
1 files changed, 536 insertions, 34 deletions
diff --git a/core/replica.zig b/core/replica.zig
index e05cf79e..39ee53b2 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -157,7 +157,7 @@ pub const Authority = struct {
seq: u32 = 0,
/// Each client's view (core/views.zig): its own layout, focus and
/// cursors over the session's text. The first client has the session's.
- view_of: [64]u8 = @splat(0),
+ view_of: [64]Pardes.View.Id = @splat(.at(0)),
/// Steps of its own taken since the last unit (`output`): one unit,
/// `pending`, sent before the next input it steps and at a frame.
batched: u32 = 0,
@@ -182,6 +182,7 @@ pub const Authority = struct {
a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null;
// A digest at a unit's end, as the session's (Peers.unit).
a.t.no_digest = true;
+ opts.tape = &a.t;
const was = Stepping.begin(&a.t, null);
defer was.end();
a.core = try Pardes.init(gpa, opts);
@@ -278,7 +279,7 @@ pub const Authority = struct {
};
a.core.pump(a.host) catch {};
was.end();
- a.view_of[client] = k.index();
+ a.view_of[client] = k;
a.seq += 1;
return .{ .view = k.index(), .unit = try a.unit(0, a.seq) };
}
@@ -295,7 +296,7 @@ pub const Authority = struct {
const again = if (back) |v| a.core.rejoinView(.at(v)) else false;
const k = (if (again) back else if (a.core.openView()) |o| o.index() else null) orelse return null;
a.core.undrawn |= @as(u8, 1) << @intCast(k);
- a.view_of[client] = k;
+ a.view_of[client] = .at(k);
a.seq += 1;
const u = try a.unit(0, a.seq);
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
@@ -321,8 +322,8 @@ pub const Authority = struct {
std.debug.assert(a.batched == 0);
const was = Stepping.begin(&a.t, null);
const k = a.view_of[client];
- a.core.undrawn &= ~(@as(u8, 1) << @intCast(k));
- if (again) a.core.awayView(.at(k)) else a.core.closeView(.at(k));
+ a.core.undrawn &= ~(@as(u8, 1) << @intCast(k.index()));
+ if (again) a.core.awayView(k) else a.core.closeView(k);
was.end();
a.seq += 1;
return a.unit(0, a.seq);
@@ -332,7 +333,7 @@ pub const Authority = struct {
pub fn closeView(a: *Authority, client: u16) ![]const u8 {
std.debug.assert(a.batched == 0);
const was = Stepping.begin(&a.t, null);
- a.core.closeView(.at(a.view_of[client]));
+ a.core.closeView(a.view_of[client]);
was.end();
a.seq += 1;
return a.unit(0, a.seq);
@@ -344,7 +345,7 @@ pub const Authority = struct {
std.debug.assert(a.batched == 0);
const in = parseInput(msg) orelse return error.BadInput;
const was = Stepping.begin(&a.t, null);
- a.core.toView(.at(a.view_of[in.client]));
+ a.core.toView(a.view_of[in.client]);
a.t.stamp = stampOf(in);
a.core.update(in.event);
a.core.step();
@@ -449,7 +450,7 @@ pub const Screens = struct {
/// What `peer` is owed of every terminal, each a message onto `out`
/// (owned): nothing for one it has as it is, or with `bound` in flight.
- pub fn flush(s: *Screens, core: *Pardes, peer: u16, _: u8, out: *std.ArrayListUnmanaged([]u8)) !void {
+ pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void {
const t0 = nowNs();
defer s.encode_ns += nowNs() - t0;
for (core.panes, 0..) |slot, id| {
@@ -1667,12 +1668,14 @@ pub const Peer = struct {
peers: *Peers,
fd: c_int,
id: u16,
- view: u8,
+ view: Pardes.View.Id,
/// Its process (its socket's peer), for `--ps`; 0 not known.
pid: libc.pid_t = 0,
/// Its bye said it joins again for its view (a divergence's rejoin):
/// kept for it (views.away), not closed. Its reader's, read after its end.
again: bool = false,
+ /// ...or that its window was closed (Peers.closed).
+ close: bool = false,
/// Its number in the session's `Screens`.
sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
@@ -1943,7 +1946,9 @@ pub const Peer = struct {
switch (t) {
.hello => return false,
.bye => {
- peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again;
+ const b = (wire.decodeClient(tag, payload) catch return false).bye;
+ peer.again = b.again;
+ peer.close = b.close;
return false;
},
.ping => {
@@ -2066,6 +2071,10 @@ pub const Peers = struct {
/// No frontend of its own (the host says): with no client either, the
/// session is unattended.
detached: bool = false,
+ /// Its last client left with a close (its window closed, its terminal
+ /// hung up) and the session is a pair's not kept (daemon.sessionState): it
+ /// ends there (runtime/session.zig).
+ closed: bool = false,
/// The worst a join cost the session's step, and the last one's dump.
join_ns: u64 = 0,
each_join: std.ArrayListUnmanaged(u64) = .empty,
@@ -2204,7 +2213,7 @@ pub const Peers = struct {
// The terminals as this step reads them, then the step, the rows
// it read, its unit (part B terminal notes' order).
ps.screensOut(core, .flush);
- core.toView(.at(peer.view));
+ core.toView(peer.view);
ps.t.stamp = stampOf(in);
core.update(in.event);
core.step();
@@ -2242,7 +2251,7 @@ pub const Peers = struct {
ps.msgs.clearRetainingCapacity();
}
(switch (what) {
- .flush => ps.screens.flush(core, peer.sid, peer.view, &ps.msgs),
+ .flush => ps.screens.flush(core, peer.sid, &ps.msgs),
.fill => ps.screens.fill(core, peer.sid, &ps.msgs),
}) catch return;
if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens);
@@ -2328,12 +2337,12 @@ 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, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
ps.next_id +%= 1;
if (ps.next_id == 0) ps.next_id = 1;
// The session's digest as dumped, for the joiner to check its load by.
const digest = tape.digestOf(core);
- peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = .at(k), .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
+ peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null;
if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null;
if (ps.threads and (peer.writer == null or peer.reader == null)) {
@@ -2362,11 +2371,12 @@ pub const Peers = struct {
log.info("client {d} left '{s}'", .{ peer.id, ps.name });
ps.tellClients();
ps.screens.dropPeer(peer.sid);
- core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
+ core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
// Cut off, it joins again after the words why (`send`); its reader
// has ended and no other thread sets `cut` now.
ps.closeViewOf(core, peer, peer.again or peer.cut);
if (ps.count() == 0) core.unattended = ps.detached;
+ if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -2378,7 +2388,7 @@ pub const Peers = struct {
/// session no one else watches leaves the session its layout, for a
/// client that comes after to find.
fn closeViewOf(ps: *Peers, core: *Pardes, peer: *Peer, again: bool) void {
- if (again) core.awayView(.at(peer.view)) else if (ps.count() == 0 and ps.detached) core.leaveView(.at(peer.view)) else core.closeView(.at(peer.view));
+ if (again) core.awayView(peer.view) else if (ps.count() == 0 and ps.detached) core.leaveView(peer.view) else core.closeView(peer.view);
}
/// Its threads ended and joined, its link closed.
@@ -2470,7 +2480,8 @@ pub const Peers = struct {
/// Detach typed in client view `k`'s: told it left the session running
/// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
- for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
+ for (ps.list) |slot| if (slot) |peer| if (peer.view.index() == k) {
+ daemon.keepSession();
var out: [wire.max_name + 8]u8 = undefined;
peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
@@ -2507,7 +2518,7 @@ pub const Peers = struct {
fn drop(ps: *Peers, core: *Pardes, again: bool) void {
for (&ps.list) |*slot| if (slot.*) |peer| {
slot.* = null;
- core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
+ core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
ps.closeViewOf(core, peer, again);
ps.screens.dropPeer(peer.sid);
ps.letGo(peer);
@@ -2941,10 +2952,11 @@ pub fn askCheck(fd: c_int) bool {
return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable);
}
-/// The client's last word: `again`, it joins again for its view at once.
-pub fn bye(fd: c_int, again: bool) void {
+/// The client's last word: `again`, it joins again for its view at once;
+/// `close`, its window was closed.
+pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
var out: [16]u8 = undefined;
- if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {}
+ if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {}
}
/// What the session streams a client after its dump, as its frontend's loop
@@ -2998,6 +3010,13 @@ pub fn ended(why: []const u8) bool {
/// The words a client goes with when its session runs another build now.
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
+/// A join's failure that is its session's running another build now: a
+/// client whose own start path holds a newer one execs that instead
+/// (runtime/client.zig).
+pub fn otherBuild(why: []const u8) bool {
+ return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words);
+}
+
/// A replica client's join, the terminal's and the window's alike (their
/// `runClient`): the session at `path` dialled (or, first, the one on its
/// pair, `o.pair`), its build checked to be this
@@ -3022,7 +3041,10 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null;
+ } else j.* = (if (o.join_view) |v|
+ redial(gpa, path, session, why, have, true, v)
+ else
+ sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3057,7 +3079,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
/// an upgrade under way may not have said yet.
fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, false);
+ bye(j.fd, .{});
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -3078,7 +3100,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
while (true) : (tries += 1) {
why.* = @splat(0);
if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
- if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) {
+ // Another build, or another protocol (the daemon moved with its
+ // session): no dial again will do.
+ const words = std.mem.sliceTo(why, 0);
+ if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) {
_ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {};
return null;
}
@@ -3099,6 +3124,8 @@ pub const Link = struct {
r: *Replica,
fd: c_int,
quit: bool = false,
+ /// ...because its window was closed: said in its bye.
+ close: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
@@ -3501,7 +3528,7 @@ fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime wh
msgs.deinit(gpa);
}
switch (what) {
- .flush => try screens.flush(a.core, peer, r.view, &msgs),
+ .flush => try screens.flush(a.core, peer, &msgs),
.fill => {
try screens.fill(a.core, peer, &msgs);
screens.filled(a.core);
@@ -3534,7 +3561,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined {
var whole = state.len;
for (blobs.items) |b| whole += b.bytes.len;
const peer = try ps.gpa.create(Peer);
- peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = 0, .dump = state, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = .at(0), .dump = state, .blobs = blobs, .dump_gpa = core.gpa };
peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
const Serve = struct {
fn run(p: *Peer) void {
@@ -5289,7 +5316,7 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it
const back = try joinedNow(a, 3, opened.view);
defer back.deinit();
try std.testing.expectEqual(digestOf(a), back.digest());
- a.view_of[3] = opened.view;
+ a.view_of[3] = .at(opened.view);
const u = try gpa.dupe(u8, try a.take(try back.input(.{ .key = .{ .cp = 'l', .text = "l" } })));
defer gpa.free(u);
old.confirm(u);
@@ -5391,13 +5418,13 @@ test "a client cut off for what it left unread is told why and joins again for i
// ...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));
+ try std.testing.expect(pardes.views.isAway(core, view.index()));
first.r.deinit();
_ = libc.close(fd);
- const back = try MemoryLinks.join(&ps, core, view, &fd);
+ const back = try MemoryLinks.join(&ps, core, view.index(), &fd);
defer back.r.deinit();
try std.testing.expectEqual(view, back.peer.view);
- link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view, .gmtoff = 0, .dump = &.{} });
+ link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} });
core.update(.{ .paste = "back" });
try core.pump(core.host);
ps.boundary(core);
@@ -5462,7 +5489,7 @@ test "a client's writer, the client cut off while it waits on the socket, writes
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.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = .at(0), .dump_gpa = gpa, .far = false, .limit = 256 << 10 };
peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len;
peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer});
defer ps.letGo(peer);
@@ -7222,9 +7249,6 @@ test "a client joined from a dump lands a click on a rail's tick as the session
r.confirm(try a.take(m));
r.settle();
}
- // (The key may be mispredicted: a step's places are a frame's time's
- // worth, `tape.over`, the session's verdict, and its drawn caches let
- // it find more in that time than the client's speculation did.)
try agrees(a, r);
try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current);
}
@@ -7476,6 +7500,111 @@ test "a client of screen-state terminals takes a 9P pty/run in a shell as the se
try agrees(a, late);
}
+// daemon.py --clients' client C (2026-11-20): idle, a copy taken ahead; the
+// session's script opens pty/run and its command prints, replayed over the
+// copy and kept; the client types into the shell, its speculation stops at
+// the pty write, and the rollback replays the open again over a record the
+// copy never held (it holds the opens as far as `opens_len`), whose line
+// and output the epoch had freed: freed again there, the client's C heap
+// was corrupt.
+test "a 9P open the session made over a copy taken ahead, replayed after a rollback: the record past the opens the copy holds is written over, never freed again" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
+ defer a.deinit();
+ var screens: Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt } });
+ r.confirm((try a.pending()).?);
+ try deliver(a, &screens, peer, r, .flush);
+ r.ready();
+ try std.testing.expect(r.copy.held and r.core().fs.opens_len == 0);
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ const Serve = struct {
+ fn serve(s: *Authority, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ const u = try std.testing.allocator.dupe(u8, try s.unit(0, s.seq));
+ defer std.testing.allocator.free(u);
+ x.confirm(u);
+ x.settle();
+ return reply;
+ }
+ };
+ const h = (try Serve.serve(a, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Serve.serve(a, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo x\n" });
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = "echo x\r\n\x1b]133;C;aid=pardes\x07x\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
+ r.confirm((try a.pending()).?);
+ r.settle();
+ // Kept over the copy: the record past its opens holds the run's output.
+ try std.testing.expect(r.copy.held and r.since.items.len > 0);
+ try std.testing.expectEqualStrings("x\n", r.core().fs.opens[h - 1].what.run.output);
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ // A key into the shell: its speculation stops at the pty write, and
+ // the copy is put back, the units since replayed (the open again).
+ try key(r, 'e', &sent);
+ try std.testing.expect(r.applied == 0 and r.stats.stopped > 0);
+ r.confirm(try a.take(sent.items[0]));
+ r.settle();
+ try deliver(a, &screens, peer, r, .flush);
+ _ = try Serve.serve(a, r, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true });
+ if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
+ try std.testing.expect(r.diverged == null and r.quiet());
+ try agrees(a, r);
+}
+
+test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ try n.join();
+ const r = n.late.?;
+ const exec = n.node(.exec);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ta" }, true);
+ r.ready();
+ // Replayed over the copy and kept: `Tab 8` runs, `Un` is held where
+ // `Ta` was, in the buffer the copy holds.
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "b 8\nUn" }, true);
+ try std.testing.expect(r.copy.held and r.since.items.len > 0);
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| std.testing.allocator.free(m);
+ sent.deinit(std.testing.allocator);
+ }
+ try key(r, 'l', &sent);
+ try std.testing.expectEqual(@as(usize, 1), r.applied);
+ // The session's key first: a rollback, the write replayed again.
+ try n.send(try n.a.local(.{ .key = .{ .cp = 'j', .text = "j" } }));
+ try std.testing.expect(r.stats.foreign > 0);
+ try n.send(try n.a.take(sent.items[0]));
+ _ = try n.serve(.{ .tag = 4, .op = .write, .node = exec, .handle = h, .data = "do\n" }, true);
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = exec, .handle = h, .opened = true }, true);
+ if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
+ try std.testing.expect(r.diverged == null and r.quiet());
+ try n.agree();
+}
+
// Del with a pane above and below asks which way the space goes, its
// question shown once a delay is up (builtins.zig): its time was the
// host's clock read in the step, an answering entry a speculation stops at.
@@ -7523,3 +7652,376 @@ test "a far client's Del with panes above and below is applied at once, and its
try agrees(a, r);
try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns);
}
+
+// ---- a client that joins a session with 9P work under way ----
+//
+// A 9P request is an input every replica replays, so the state the 9P
+// tree builds from the requests (the open records, each pane's `fs`) is
+// a client's for everything after its join: what was made before it
+// comes in the join's dump, or the client steps the next request
+// otherwise than its session.
+
+/// A session with a file pane and its 9P server, and a client joined
+/// from its dump (`join`) that takes every unit after.
+const NinepJoin = struct {
+ a: *Authority,
+ late: ?*Replica = null,
+ serial: u32,
+
+ fn init(text: []const u8, host: pardes.Host) !NinepJoin {
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host, false);
+ errdefer a.deinit();
+ const was = Stepping.begin(&a.t, null);
+ const pane = try a.core.setTestFile(text);
+ was.end();
+ _ = try a.unit(0, 0);
+ return .{ .a = a, .serial = pane.serial };
+ }
+
+ fn deinit(n: *NinepJoin) void {
+ if (n.late) |r| r.deinit();
+ n.a.deinit();
+ }
+
+ fn node(n: *const NinepJoin, file: pardes.ctlfs.PaneFile) u64 {
+ return pardes.ctlfs.Node.of(n.serial, file);
+ }
+
+ /// One request as the session's 9P server serves it, a step of its
+ /// own, then (`pumped`) its loop's pass: a join can come between the
+ /// two, the session's loop being elsewhere. Its unit to the client.
+ fn serve(n: *NinepJoin, req: pardes.ctlfs.Req, pumped: bool) !pardes.ctlfs.Reply {
+ const a = n.a;
+ const was = Stepping.begin(&a.t, null);
+ const reply = a.core.serveFs(req);
+ if (pumped) a.core.pump(a.host) catch {};
+ was.end();
+ a.seq += 1;
+ try n.send(try a.unit(0, a.seq));
+ return reply;
+ }
+
+ /// A pass of the session's loop with no request: its unit.
+ fn pump(n: *NinepJoin) !void {
+ n.a.pump();
+ try n.send((try n.a.pending()).?);
+ }
+
+ fn send(n: *NinepJoin, u: []const u8) !void {
+ const r = n.late orelse return;
+ const kept = try std.testing.allocator.dupe(u8, u);
+ defer std.testing.allocator.free(kept);
+ r.confirm(kept);
+ r.settle();
+ }
+
+ /// A client joins now, from the session's dump, at the digest the
+ /// session had.
+ fn join(n: *NinepJoin) !void {
+ const joined = (try n.a.join(1, null)).?;
+ defer std.testing.allocator.free(joined.dump);
+ const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ r.t.screen_state = false;
+ r.core().echo = null;
+ n.late = r;
+ try std.testing.expectEqual(joined.digest, r.digest());
+ }
+
+ fn agree(n: *NinepJoin) !void {
+ try agrees(n.a, n.late.?);
+ }
+};
+
+test "a client joined while a script's open of a pane's exec holds half a line runs the line its session runs" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const exec = n.node(.exec);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ne" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "w\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined between two writes of one open to a body makes them one undo step, as its session does" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const body = n.node(.body);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "a\n" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = "b\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true);
+ try n.agree();
+}
+
+test "a client joined while a script's ctl open holds a pane's lock refuses another open's lock, as its session does" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const ctl = n.node(.ctl);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = ctl, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = ctl, .handle = h, .data = "lock\n" }, true);
+ try n.join();
+ const g = (try n.serve(.{ .tag = 3, .op = .open, .node = ctl, .omode = 1 }, true)).handle;
+ try std.testing.expectEqual(pardes.ctlfs.Status.err, (try n.serve(.{ .tag = 4, .op = .write, .node = ctl, .handle = g, .data = "lock\n" }, true)).status);
+ // Who holds it, by name: on the base no digest covered it.
+ const id = n.a.core.paneBySerial(n.serial).?;
+ try std.testing.expectEqual(n.a.core.panes[id].?.fs.lock, n.late.?.core().panes[id].?.fs.lock);
+ try n.agree();
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = ctl, .handle = g, .opened = true }, true);
+ _ = try n.serve(.{ .tag = 6, .op = .release, .node = ctl, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script set a pane's addr, its limit, or truncated its dot writes where its session writes" {
+ // addr: the next data write replaces what it says.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.addr), .data = "/two/" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.data), .data = "2" }, true);
+ try n.agree();
+ }
+ // limit: an address is looked for inside it.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.limit), .data = "#0,#3" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.addr), .data = "/two/" }, true);
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = n.node(.data), .data = "2" }, true);
+ try n.agree();
+ }
+ // dot truncated: its open's release with no write empties it.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ const dot = n.node(.dot);
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = dot, .data = "#0,#3" }, true);
+ const h = (try n.serve(.{ .tag = 2, .op = .open, .node = dot, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = dot, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = dot, .handle = h, .opened = true }, true);
+ try n.agree();
+ }
+}
+
+test "a client joined between two writes of one open to a pane's sel runs the second on from the first, as its session does" {
+ var n = try NinepJoin.init("one two\n", TestHost.host());
+ defer n.deinit();
+ const sel = n.node(.sel);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = sel, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = sel, .handle = h, .data = "a" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = sel, .handle = h, .data = "b" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = sel, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script's nomark or noscroll writes as its session does" {
+ // nomark: writes under it are one undo step.
+ {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "nomark" }, true);
+ try n.join();
+ // Two opens' writes, each its own undo step but for nomark.
+ const body = n.node(.body);
+ for ([_][]const u8{ "two\n", "three\n" }) |text| {
+ const h = (try n.serve(.{ .tag = 2, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = text }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ }
+ _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "mark" }, true);
+ _ = try n.serve(.{ .tag = 6, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true);
+ try n.agree();
+ }
+ // noscroll: a write past the screen leaves the view where it was.
+ {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.scroll), .data = "0" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.body), .data = &@as([100]u8, @splat('\n')) }, true);
+ try n.agree();
+ }
+}
+
+test "a client joined after a script truncated a pane's tag writes the tag its session writes" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const tag = n.node(.tag);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Get Put\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script truncated the workspace's tag writes the tag its session writes" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const tag: u64 = @backingInt(pardes.ctlfs.TopFile.tag);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Exit\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined while a chorded exec waits for its event reader's write-back runs it with its argument, as its session does" {
+ var n = try NinepJoin.init("Msg said\narg-text\n", TestHost.host());
+ defer n.deinit();
+ const event = n.node(.event);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = event, .omode = 2 }, true)).handle;
+ // The session's chorded click, told to the reader, its argument kept.
+ {
+ const was = Stepping.begin(&n.a.t, null);
+ const id = n.a.core.paneBySerial(n.serial).?;
+ try std.testing.expect(pardes.mouse.reportRange(n.a.core, id, pardes.config.exec_cmd, "Msg", false, .{ .q0 = 0, .q1 = 3 }, "arg-text"));
+ was.end();
+ n.a.seq += 1;
+ _ = try n.a.unit(0, n.a.seq);
+ }
+ try n.join();
+ // The command's record written back alone: its argument is the one kept.
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = event, .handle = h, .data = "MX0 3 9 3 Msg\n" }, true);
+ _ = try n.serve(.{ .tag = 3, .op = .release, .node = event, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined while a script's writes to a body are held to go in as one edit puts them in as its session does" {
+ // A host with a clock: held writes go in once they have paused
+ // (pane.batch_pause_ns), and the join came before that.
+ const Clock = struct {
+ var now_ns: u64 = 5 * std.time.ns_per_s;
+ fn now(_: ?*anyopaque) u64 {
+ return now_ns;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now };
+ };
+ var n = try NinepJoin.init("one\n", .{ .vtable = &Clock.vtable });
+ defer n.deinit();
+ const body = n.node(.body);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "two\n" }, true);
+ try std.testing.expect(n.a.core.fs.batch.bytes.items.len > 0);
+ try n.join();
+ Clock.now_ns += std.time.ns_per_s;
+ try n.pump();
+ try n.agree();
+ _ = try n.serve(.{ .tag = 3, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client runs an Edit a script's write started once, as its session does, when the held write is asked again" {
+ var n = try NinepJoin.init("b\na\n", TestHost.host());
+ defer n.deinit();
+ try n.join();
+ const ctl = n.node(.ctl);
+ const req: pardes.ctlfs.Req = .{ .tag = 7, .op = .write, .node = ctl, .data = "Edit , | sort\n" };
+ // The step alone: its loop's pass would run the command (here, with no
+ // host to run it, fail it).
+ const first = try n.serve(req, false);
+ try std.testing.expectEqual(pardes.ctlfs.Status.ok, first.status);
+ // The write held as the session's listener holds it (runtime/9p_io.zig).
+ n.a.core.fs.edit_hold = .{ .asker = @ptrCast(n.a.core), .slot = 0, .seq = 1, .tag = req.tag, .node = ctl, .handle = 0, .written = first.written };
+ // Its command answers: the Edit is done.
+ n.a.apply(.{ .pipe_resp = .{ .id = n.a.core.pipe.edit_run.?.id, .success = true, .outputs = &.{"a\nb\n"} } });
+ n.a.seq += 1;
+ try n.send(try n.a.unit(0, n.a.seq));
+ try n.agree();
+ // A retry of the held write's park, as the listener serves it: its
+ // answer from the hold, no step, the Edit not run again by anyone.
+ const again = pardes.filesystem.EditHold.retried(&n.a.core.fs, req) orelse try n.serve(req, true);
+ try std.testing.expectEqual(pardes.ctlfs.Status.ok, again.status);
+ try std.testing.expect(n.a.core.pipe.edit_run == null);
+ try n.agree();
+}
+
+test "an Edit's stop token is each process's own (selection_pipe.next_token): a client's differs from its session's, and they agree" {
+ var n = try NinepJoin.init("b\na\n", TestHost.host());
+ defer n.deinit();
+ try n.join();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "Edit , | sort\n" }, false);
+ const session = n.a.core.pipe.edit_run.?.request.token;
+ const client = n.late.?.core().pipe.edit_run.?.request.token;
+ try std.testing.expect(session != client);
+ try n.agree();
+}
+
+/// A session with a shell, for a run's 9P state across a join: a host
+/// whose pty takes the line and whose tty nobody else holds.
+const RunJoin = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+
+ /// The session at its shell's first prompt, and the shell's slot.
+ fn init(n: *NinepJoin) !u8 {
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }, false);
+ n.* = .{ .a = a, .serial = 0 };
+ _ = try a.unit(0, 0);
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ n.serial = a.core.panes[shell].?.serial;
+ return shell;
+ }
+
+ fn output(n: *NinepJoin, shell: u8, bytes: []const u8) !void {
+ n.a.output(.{ .output = .{ .pane = .at(shell), .bytes = bytes } });
+ try n.send((try n.a.pending()).?);
+ }
+};
+
+test "a client joined while a script's pty/run waits on the command it sent ends the run as its session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ var n: NinepJoin = undefined;
+ const shell = try RunJoin.init(&n);
+ defer n.deinit();
+ // The shell's greeting (`ls`) run at its first prompt, done.
+ try RunJoin.output(&n, shell, RunJoin.prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt);
+ const run = n.node(.pty_run);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true);
+ try n.join();
+ try RunJoin.output(&n, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt);
+ const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true);
+ try std.testing.expectEqualStrings("exit 0\n", n.a.core.fsPayload(answer));
+ // The open's next line, sent at the prompt the first left.
+ _ = try n.serve(.{ .tag = 4, .op = .write, .node = run, .handle = h, .data = "false\n" }, true);
+ try RunJoin.output(&n, shell, "false\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;1;aid=pardes\x07" ++ RunJoin.prompt);
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = run, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after its session's shell was found to have no prompt marks answers a pty/run as its session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ var n: NinepJoin = undefined;
+ const shell = try RunJoin.init(&n);
+ defer n.deinit();
+ {
+ const was = Stepping.begin(&n.a.t, null);
+ n.a.core.acknowledgeShell(.at(shell), "/bin/sh", false);
+ was.end();
+ n.a.seq += 1;
+ _ = try n.a.unit(0, n.a.seq);
+ }
+ try n.join();
+ const run = n.node(.pty_run);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true);
+ const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true);
+ try std.testing.expectEqualStrings("error no prompt marks\n", n.a.core.fsPayload(answer));
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = run, .handle = h, .opened = true }, true);
+ try n.agree();
+}