summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-21 05:26:38 -0300
committerGabriel Schneider <[email protected]>2026-11-21 05:30:39 -0300
commite29ff73bbb2c198afbb894ee98854da2d9a7be7d (patch)
tree17cf56b16272f43fdb789174350681641876e170
parent63538d28cee238ff53c731f965c22e615d43bec1 (diff)
parentfe0aa07c18a9fd5ca6bdcb78e9354a2745e32298 (diff)
downloadpardes-e29ff73bbb2c198afbb894ee98854da2d9a7be7d.tar.gz
pardes-e29ff73bbb2c198afbb894ee98854da2d9a7be7d.zip
integration: the pair's finished steps on the gathered line: pardes-pair-4 (`rustnvoo`: an attach handed to a session as it upgrades is told so and joins the new process; the fast start, the boot as input zero: the wire at 27; a window client exec'd at an Upgrade comes back the size it was) and pardes-merge47 (`rprvwpnv`: the terminals' line at 26 and the library for a browser reader); three textual conflicts: abi/wire.zig's history says 27 and 26 each in its own words and the version is 27, test/daemon.py's WIRE is 27, core/replica.zig's Link keeps both lines' fields (the lag bound's `behind`, `least`, `fresh`, `lagged`; the pair's `held`); core-test 885/1045 (160 skipped), shell-test 1087/1090; its gate: .scratch/sketch/reorg/merge48, the numbers in PARDES.md (2026-11-21)
Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--abi/wire.zig19
-rw-r--r--core/dump.zig3
-rw-r--r--core/panes.zig5
-rw-r--r--core/replica.zig354
-rw-r--r--core/root.zig2
-rw-r--r--dev/gui/gui.zig16
-rw-r--r--dev/tui/tui.zig12
-rw-r--r--runtime/client.zig33
-rw-r--r--runtime/main.zig4
-rw-r--r--test/daemon.py394
10 files changed, 777 insertions, 65 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index 5f8e1f97..88a82e52 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -10,6 +10,9 @@ const pardes = @import("core");
const config = @import("pardes_options");
const build_info = @import("build_info");
+/// 27: a pair's first client makes its own core from the session's
+/// options and says its digest (`boot`) before its `far`: the session sends
+/// no dump when its own at the join has the same;
/// 26: a view kept for its client's rejoin says when it went away
/// (View.away_ns), and is that client's for Views.away_kept_ns;
/// 25: the 9P state a session's requests made (its open records, each
@@ -43,7 +46,7 @@ const build_info = @import("build_info");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 26;
+pub const version: u16 = 27;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -117,6 +120,12 @@ pub const ClientTag = enum(u8) {
/// guessed them for the input that follows: its time, which the step
/// reads (core/replica.zig).
stamp = 0x08,
+ /// A pair's first client's word before its `far`: the digest of the
+ /// core it made itself, from the session's options (Options.pair):
+ /// the session's at the join the same, no dump is sent. Not 0x09: a
+ /// stream's reader (replica.zig `Framer`) unpacks that tag as zstd
+ /// whichever way the stream runs.
+ boot = 0x0a,
key = 0x10,
mouse = 0x11,
@@ -313,6 +322,7 @@ pub const ClientMsg = union(enum) {
far: bool,
want: []const u8,
stamp: [2]i64,
+ boot: u64,
event: pardes.Event,
};
@@ -524,7 +534,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
},
// 0 it leaves, 1 it joins again, 2 its window was closed.
.bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)),
- .ping => |v| try w.writeInt(u64, v, .little),
+ .ping, .boot => |v| try w.writeInt(u64, v, .little),
.screen_ack, .want => |bytes| try w.writeAll(bytes),
.check => {},
.far => |far| try w.writeByte(@intFromBool(far)),
@@ -605,6 +615,7 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
.far => .{ .far = try getBool(&r) },
.want => return .{ .want = payload },
.stamp => .{ .stamp = .{ try r.takeInt(i64, .little), try r.takeInt(i64, .little) } },
+ .boot => .{ .boot = try r.takeInt(u64, .little) },
.key => blk: {
const cp = try r.takeInt(u32, .little);
// `Key.cp` is a u21, and the specials live in the private-use
@@ -661,7 +672,7 @@ const msg_slack = header_len + 64;
pub fn clientBound(msg: ClientMsg) usize {
return msg_slack + switch (msg) {
.hello => |h| h.session.len,
- .bye, .ping, .check, .far, .stamp => 0,
+ .bye, .ping, .check, .far, .stamp, .boot => 0,
.screen_ack, .want => |bytes| bytes.len,
.event => |ev| switch (ev) {
// Its hits' places (14 bytes each) past the slack.
@@ -788,6 +799,8 @@ test "detached wire: a session is never told to do a frontend's remembering" {
"hello", "bye", "ping", "screen_ack", "check",
// ...and how far it is, and which of the join's blobs it lacks.
"far", "want",
+ // ...and the digest of the core it made itself (a pair's).
+ "boot",
// ...and when its next input was, by the session's clocks.
"stamp",
// ...and everything a person can do to a window.
diff --git a/core/dump.zig b/core/dump.zig
index 4fc7fc4d..18ac28f7 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -66,7 +66,8 @@ pub fn defaultDirectory(buf: []u8) ?[]const u8 {
}
/// What a load makes a terminal's emulator with, when not the loader's
-/// own: a screen-state replica's are the C heap's (core/replica.zig).
+/// own: a screen-state replica's are the C heap's (core/replica.zig), and
+/// so are those a pair's client's own boot makes (panes.emulatorGpa).
pub var terminal_gpa: ?std.mem.Allocator = null;
// ---- a whole session to and from a dump (acme keeps this in rows.c) ----
diff --git a/core/panes.zig b/core/panes.zig
index 15e1db50..658de219 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -1194,9 +1194,10 @@ 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
-/// replica `emulator_gpa`.
+/// replica `emulator_gpa`, and in a replica's core being made (its dump's
+/// load, a pair's client's own boot) `dump.terminal_gpa`.
pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator {
- return if (tape.replaying()) emulator_gpa else gpa;
+ return if (tape.replaying()) emulator_gpa else pardes.dump.terminal_gpa orelse 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 39ee53b2..56fc4a59 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -750,8 +750,23 @@ pub const Replica = struct {
/// an image a frame late at worst... or reads freed pixels, which no test
/// session has.
pub fn initDump(gpa: Allocator, id: u16, view: u8, bytes: []const u8, opts: pardes.Options) !*Replica {
+ return made(gpa, id, view, opts, bytes);
+ }
+
+ /// A pair's first client's replica (Options.pair): its core made here
+ /// from the options the session is made from, its file read here (a
+ /// near client's read of its own machine), the view the session's join
+ /// opens for it opened (`Peers.viewFor`): the session's core at its
+ /// join, which the welcome confirms by its digest (`confirmBoot`). Its
+ /// id the session's first client's.
+ pub fn initBoot(gpa: Allocator, opts: pardes.Options) !*Replica {
+ return made(gpa, 1, null, opts, null);
+ }
+
+ /// `initDump`'s, or with no dump `initBoot`'s.
+ fn made(gpa: Allocator, id: u16, view: ?u8, opts: pardes.Options, dump: ?[]const u8) !*Replica {
const r = try gpa.create(Replica);
- r.* = .{ .gpa = gpa, .id = id, .view = view, .t = tape.memory(gpa), .guess = true };
+ r.* = .{ .gpa = gpa, .id = id, .view = view orelse 0, .t = tape.memory(gpa), .guess = true };
r.t.skips_render = true;
r.t.checks = false;
// Its terminals are the session's deltas (Peers sends them).
@@ -773,9 +788,29 @@ pub const Replica = struct {
// replica's: deltas write them while a copy is held.
pardes.dump.terminal_gpa = pardes.panes.emulator_gpa;
defer pardes.dump.terminal_gpa = null;
- const c = try pardes.dump.load(epoch, o, bytes, null);
+ const c = if (dump) |bytes| try pardes.dump.load(epoch, o, bytes, null) else boot: {
+ // The addons the session's start finds (runtime/session.zig).
+ o.addons = pardes.Addon.scan();
+ // On no tape, as the session's start is (one recording to a
+ // file aside): what it reads of the machine (the directory, the
+ // shell, the file) it reads as the session does, not as a
+ // replica's step would.
+ const c = init: {
+ const was = Stepping.begin(&tape.none, &r.epoch);
+ defer was.end();
+ break :init try pardes.Pardes.init(epoch, o);
+ };
+ // Its view opened on its own tape, as the session's join opens
+ // it on the one its clients are sent: its terminals, screen
+ // state, not reloaded there either.
+ tape.adoptCore(&r.t, c);
+ const was = Stepping.begin(&r.t, &r.epoch);
+ defer was.end();
+ r.view = Peers.viewFor(c, null) orelse return error.NoView;
+ break :boot c;
+ };
// The chrome's colours are local, never dumped: the restored theme's.
- pardes.colors.finishThemeInitialization(c);
+ if (dump != null) pardes.colors.finishThemeInitialization(c);
// It runs a plain kind's code of its own (Addon.plainOps), loaded
// at its first pane, each opened here from its record; another's
// panes show a line.
@@ -1709,6 +1744,11 @@ pub const Peer = struct {
/// Its first word after its hello: whether it is far (through ssh), its
/// blobs asked for by hash and its stream in zstd (`farJoin`).
far: ?bool = null,
+ /// A pair's client's word before that: the digest of the core it made
+ /// itself (`boot`); the session's at the join (`digest`) the same, its
+ /// dump is not sent.
+ boot: ?u64 = null,
+ digest: u64 = 0,
/// A far client's answer to its join's list: the blobs it lacks.
want: ?[]u8 = null,
/// A far client's stream's compressor, and an envelope's worth of its
@@ -1723,8 +1763,11 @@ pub const Peer = struct {
peer.lock.lockUncancelable(io);
while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock);
const far = peer.far;
+ const boot = peer.boot;
peer.lock.unlock(io);
if (far orelse return false) return peer.farJoin();
+ // Its client made this core itself (a pair's): nothing to send.
+ if (boot == peer.digest) return true;
var pos: usize = 0;
for (peer.blobs.items) |b| {
if (!writePieces(peer.fd, peer.dump[pos..b.at]) or !writePieces(peer.fd, b.bytes)) return false;
@@ -1969,8 +2012,9 @@ pub const Peer = struct {
peer.peers.post(.{ .check = peer });
return true;
},
- // What its join's writer waits for (`writeJoin`, `farJoin`).
- .far, .want => {
+ // What its join's writer waits for (`writeJoin`, `farJoin`); a
+ // pair's boot comes before its far.
+ .far, .want, .boot => {
const io = peer.peers.io;
const msg = wire.decodeClient(tag, payload) catch return false;
const bits = if (msg == .want) peer.peers.gpa.dupe(u8, msg.want) catch return false else null;
@@ -1982,6 +2026,8 @@ pub const Peer = struct {
return false;
}
peer.want = b;
+ } else if (msg == .boot) {
+ peer.boot = msg.boot;
} else peer.far = msg.far;
peer.cond.signal(io);
return true;
@@ -2075,6 +2121,10 @@ pub const Peers = struct {
/// hung up) and the session is a pair's not kept (daemon.sessionState): it
/// ends there (runtime/session.zig).
closed: bool = false,
+ /// An Upgrade told its clients so (`refuseAll`): a connection handed
+ /// over before its exec is told the same, never closed by the exec
+ /// unanswered. Its exec failed: the next boundary takes joins again.
+ upgrading: std.atomic.Value(bool) = .init(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,
@@ -2120,6 +2170,10 @@ pub const Peers = struct {
pub fn post(ps: *Peers, note: Note) void {
ps.lock.lockUncancelable(ps.io);
+ if (note == .join and ps.upgrading.load(.monotonic)) {
+ ps.lock.unlock(ps.io);
+ return daemon.refuseReplica(note.join.fd, upgrading);
+ }
ps.inbox.append(ps.gpa, note) catch {
ps.lock.unlock(ps.io);
switch (note) {
@@ -2167,6 +2221,7 @@ pub const Peers = struct {
/// After each of the session's pumps: its unit sent, the clients that
/// came joined, their inputs taken in, the ones gone let go.
pub fn boundary(ps: *Peers, core: *Pardes) void {
+ if (ps.upgrading.load(.monotonic)) ps.upgrading.store(false, .monotonic);
if (!ps.recording and !ps.mail.load(.acquire)) return;
const t0 = nowNs();
defer if (ps.recording and ps.samples) ps.boundary_ns.append(ps.gpa, nowNs() - t0) catch {};
@@ -2291,21 +2346,11 @@ pub const Peers = struct {
ps.recording = true;
ps.samples = std.c.getenv("PARDES_REPLICA_STATS") != null;
}
- // Someone looks at it now: its messages go by keys, not the clock.
- core.unattended = false;
- // Its own view again, kept for it since it left (views.away), or one
- // new. ponytail: a divergence's redial that came before its old
- // link's end (posted by that link's reader, microseconds after the
- // bye; the redial is a dial and the daemon's hand-over later) finds
- // its view not kept yet, and takes a new one.
- const back = if (joining.view) |v| core.rejoinView(.at(v)) else false;
- const k = (if (back) joining.view else if (core.openView()) |o| o.index() else null) orelse {
+ const k = viewFor(core, joining.view) orelse {
core.unattended = ps.count() == 0 and ps.detached;
if (ps.count() == 0) ps.stop(core);
return daemon.refuseReplica(fd, "that session has as many views as it takes");
};
- // Its own process draws it.
- core.undrawn |= @as(u8, 1) << @intCast(k);
ps.seq += 1;
ps.unit(0, ps.seq);
// The session's mutable state, dumped now; its blobs (file texts,
@@ -2340,8 +2385,10 @@ pub const Peers = struct {
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.
+ // The session's digest as dumped, for the joiner to check its load by
+ // (a pair's client, its own boot: `writeJoin`).
const digest = tape.digestOf(core);
+ peer.digest = digest;
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;
@@ -2364,6 +2411,41 @@ pub const Peers = struct {
if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("session: client {d} joined after unit {d}\n", .{ peer.id, ps.seq });
}
+ /// A joiner's view in `core`: the one kept for it since it left
+ /// (views.away), or one new; someone looks at the session now (its
+ /// messages go by keys, not the clock), and that view is its own
+ /// process's to draw. The session's join and a pair's client's own boot
+ /// (`Replica.initBoot`) alike, so that the two cores are the same: what
+ /// was queued before the join (a pair's session's first effects, its
+ /// boot shell's spawn among them) is performed after it, on the tape
+ /// its client is sent, not by the view's settle, as a client that made
+ /// its core itself performs none of them.
+ /// ponytail: a divergence's redial that came before its old link's end
+ /// (posted by that link's reader, microseconds after the bye; the
+ /// redial is a dial and the daemon's hand-over later) finds its view
+ /// not kept yet, and takes a new one.
+ fn viewFor(core: *Pardes, back: ?u8) ?u8 {
+ const held = core.gpa.alloc(pardes.Effect, core.effects_len) catch return null;
+ defer core.gpa.free(held);
+ for (held, 0..) |*e, i| e.* = core.effects[(core.effects_head + i) % core.effects.len];
+ core.effects_len = 0;
+ defer queueFirst(core, held);
+ core.unattended = false;
+ const k = (if (back) |v| (if (core.rejoinView(.at(v))) v else null) else null) orelse (core.openView() orelse return null).index();
+ core.undrawn |= @as(u8, 1) << @intCast(k);
+ return k;
+ }
+
+ /// `held` queued again ahead of what is queued now, in its order.
+ fn queueFirst(core: *Pardes, held: []const pardes.Effect) void {
+ const cap = core.effects.len;
+ const n = @min(held.len, cap - core.effects_len);
+ const head = (core.effects_head + cap - n) % cap;
+ for (held[0..n], 0..) |e, i| core.effects[(head + i) % cap] = e;
+ core.effects_head = head;
+ core.effects_len += n;
+ }
+
fn leave(ps: *Peers, core: *Pardes, peer: *Peer) void {
for (&ps.list) |*slot| if (slot.* == peer) {
slot.* = null;
@@ -2431,13 +2513,23 @@ pub const Peers = struct {
ps.gpa.destroy(peer);
}
- /// Every client told `why` and let go, its view with it: an Upgrade's
- /// exec is next (tui.zig `upgradeNow`). What each was sent goes first,
- /// for up to 200 ms; a client then dials the session again.
- pub fn refuseAll(ps: *Peers, core: *Pardes, why: []const u8) void {
+ /// Every client told the session is upgrading and let go, its view with
+ /// it: an Upgrade's exec is next (tui.zig `upgradeNow`). What each was
+ /// sent goes first, for up to 200 ms; a client then dials the session
+ /// again. So is a connection handed over and not joined yet, or until
+ /// the exec (`upgrading`): the exec would close it unanswered, and its
+ /// client would take that for the session's end.
+ pub fn refuseAll(ps: *Peers, core: *Pardes) void {
+ ps.lock.lockUncancelable(ps.io);
+ ps.upgrading.store(true, .monotonic);
+ var i: usize = 0;
+ while (i < ps.inbox.items.len) {
+ if (ps.inbox.items[i] == .join) daemon.refuseReplica(ps.inbox.orderedRemove(i).join.fd, upgrading) else i += 1;
+ }
+ ps.lock.unlock(ps.io);
if (ps.count() == 0) return;
var out: [600]u8 = undefined;
- const words = wire.encodeServer(&out, .{ .refused = why }) catch return;
+ const words = wire.encodeServer(&out, .{ .refused = upgrading }) catch unreachable; // the words fit
for (ps.list) |slot| if (slot) |peer| peer.last(words);
ps.flushed200();
// Each joins again for its view, kept in the dump (views.away).
@@ -2594,6 +2686,9 @@ pub const Joined = struct {
sent_bytes: u64 = 0,
/// How long its dial and load took, ms (`join`).
ms: u64 = 0,
+ /// Its replica is its own boot, the welcome not read yet (`ownBoot`,
+ /// `confirmBoot`).
+ booted: bool = false,
};
/// A blob a far join was sent: where it is in the dump, and its hash.
@@ -2617,13 +2712,15 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha
_ = libc.close(fd);
return said(why, "nothing answers at {s}", .{path});
}
- return joinOn(gpa, fd, session, why, have, view);
+ return joinOn(gpa, fd, session, why, have, view, null);
}
/// `dial`'s, on a connection made: the hello, then the join. The
/// connection is closed if the join fails. No session named: no hello, a
-/// pair's (Options.pair), whose session took it as its first client.
-fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
+/// pair's (Options.pair), whose session took it as its first client. `boot`:
+/// a pair's client that made its core itself and said so (`boot`): nothing
+/// said here, and its welcome's digest the same, no dump comes.
+fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8, boot_digest: ?u64) ?Joined {
var out: [wire.hello_max + 16]u8 = undefined;
const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch {
_ = libc.close(fd);
@@ -2637,6 +2734,7 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha
gpa: Allocator,
why: []u8,
have: ?*Have,
+ boot: ?u64,
failed: ?[]const u8 = null,
welcomed: bool = false,
done: bool = false,
@@ -2671,6 +2769,10 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha
r.j.gmtoff = w.gmtoff;
r.j.digest = w.digest;
r.j.semantics = w.semantics;
+ if (r.boot == w.digest) {
+ r.done = true;
+ return false;
+ }
r.j.dump = r.gpa.alloc(u8, @intCast(w.dump_len)) catch return r.fail("out of memory for the session's dump");
r.welcomed = true;
r.j.blobs = if (r.have != null) w.blobs else 0;
@@ -2763,11 +2865,11 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha
}
const maxInt = std.math.maxInt(usize);
};
- if (!writeAll(fd, out[0 .. hello.len + far.len])) {
+ if (boot_digest == null and !writeAll(fd, out[0 .. hello.len + far.len])) {
_ = libc.close(fd);
return said(why, "the session hung up", .{});
}
- var r: Read = .{ .j = &j, .gpa = gpa, .why = why, .have = have };
+ var r: Read = .{ .j = &j, .gpa = gpa, .why = why, .have = have, .boot = boot_digest };
defer r.deinit();
j.rest.run(gpa, fd, &r, Read.take);
if (r.failed != null or !r.done) {
@@ -3007,6 +3109,9 @@ pub fn ended(why: []const u8) bool {
return false;
}
+/// What an Upgrade tells its clients (`Peers.refuseAll`): each dials again.
+pub const upgrading = "the session is upgrading to another build of pardes";
+
/// 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";
@@ -3028,6 +3133,7 @@ pub fn otherBuild(why: []const u8) bool {
/// keeps the blobs it was sent (`Have.store`), and how long it all took is
/// `j.ms`. Null, and why in `why`.
pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o: pardes.Options, have: ?*Have, why: *[600]u8, old: ?*Replica) ?*Replica {
+ if (old == null) if (o.pair) |fd| return ownBoot(gpa, j, fd, o, why);
if (old) |prev| if (have) |h| h.leaving(prev.core());
const t0 = nowNs();
if (old) |prev| {
@@ -3044,7 +3150,9 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
} 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;
+ sameBuild(gpa, (dial(gpa, path, session, why, have, null) orelse
+ // Handed to the session as it upgraded: it is there again soon.
+ if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3053,15 +3161,21 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
_ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {};
return null;
};
- // PARDES_NO_ECHO: no predicted echo (the gates' baseline).
- if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false;
- // PARDES_REPLICA_STATS: its timing samples kept, for its line.
- r.stats.samples = std.c.getenv("PARDES_REPLICA_STATS") != null;
if (!r.loaded(j.digest)) {
r.deinit();
_ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {};
return null;
}
+ takeJoined(r, j, have, t0);
+ return r;
+}
+
+/// What a replica joined by `j` takes of it, and of the environment.
+fn takeJoined(r: *Replica, j: *Joined, have: ?*Have, t0: u64) void {
+ // PARDES_NO_ECHO: no predicted echo (the gates' baseline).
+ if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false;
+ // PARDES_REPLICA_STATS: its timing samples kept, for its line.
+ r.stats.samples = std.c.getenv("PARDES_REPLICA_STATS") != null;
r.gmtoff = j.gmtoff;
// On the session's machine: a file read sent by hash is read here;
// far, it goes to the disk for the next join.
@@ -3071,9 +3185,67 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
r.io = h.io;
}
j.ms = (nowNs() - t0) / std.time.ns_per_ms;
+}
+
+/// A pair's first join (Options.pair): its own core made (`Replica.initBoot`)
+/// and its digest said before its `far`, nothing waited for: the welcome is
+/// read once its first frame is drawn (`confirmBoot`). Its welcome's words
+/// meanwhile are what the session's first join gives: its first client's
+/// id, this process's time zone (the same machine), this build.
+fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600]u8) ?*Replica {
+ const t0 = nowNs();
+ const r = Replica.initBoot(gpa, o) catch |err| {
+ _ = std.fmt.bufPrint(why, "this client could not start the session's file itself: {t}\x00", .{err}) catch {};
+ return null;
+ };
+ const digest = r.digest();
+ var out: [64]u8 = undefined;
+ const said_boot = wire.encodeClient(&out, .{ .boot = digest }) catch unreachable;
+ const said_far = wire.encodeClient(out[said_boot.len..], .{ .far = false }) catch unreachable;
+ if (!writeAll(fd, out[0 .. said_boot.len + said_far.len])) {
+ r.deinit();
+ _ = std.fmt.bufPrint(why, "the session hung up\x00", .{}) catch {};
+ return null;
+ }
+ j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true };
+ takeJoined(r, j, null, t0);
return r;
}
+/// A pair's first client's welcome (`ownBoot`), read once its first frame is
+/// drawn: the session's core at its join the one this client made itself
+/// (the same digest), `r` goes on and nothing more comes; or not (the file
+/// changed between the two reads, anything else a start reads otherwise):
+/// the dump the session sent instead, loaded, `r` let go, and the dump's
+/// replica returned in its place. Null, and why in `why`, when the session
+/// hung up or runs another build, or its dump would not load.
+pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, why: *[600]u8) ?*Replica {
+ const t0 = nowNs();
+ const digest = j.digest;
+ j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest) orelse return null, why) orelse return null;
+ if (j.dump.len == 0) {
+ r.id = j.client;
+ r.view = j.view;
+ return r;
+ }
+ defer {
+ gpa.free(j.dump);
+ j.dump = &.{};
+ }
+ const loaded = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| {
+ _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {};
+ return null;
+ };
+ if (!loaded.loaded(j.digest)) {
+ loaded.deinit();
+ _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {};
+ return null;
+ }
+ takeJoined(loaded, j, null, t0);
+ r.deinit();
+ return loaded;
+}
+
/// `j`, when its session runs this build; else its link let go, and why in
/// `why`: the daemon judged the hello by what the session last said, which
/// an upgrade under way may not have said yet.
@@ -3094,8 +3266,9 @@ fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
/// `patient`: after an Upgrade's `refused` alone, while the session is
/// away a moment; after a divergence a session that will not answer is
/// gone, and the client says so at once (it froze 20 s, 2026-10-30).
-/// `view`: the one it had, which the session kept for it (views.away).
-fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have, patient: bool, view: u8) ?Joined {
+/// `view`: the one it had, which the session kept for it (views.away);
+/// none for a first join that met an Upgrade.
+fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have, patient: bool, view: ?u8) ?Joined {
var tries: u32 = 0;
while (true) : (tries += 1) {
why.* = @splat(0);
@@ -3193,6 +3366,9 @@ pub const Link = struct {
fresh: bool = true,
/// How far behind it was as it let its link go (`rejoins` says so).
lagged: u64 = 0,
+ /// A pair's first join, its own boot not confirmed yet: its inputs
+ /// kept here, not sent (`release`; client.zig `confirm`).
+ held: ?std.ArrayListUnmanaged(u8) = null,
fn time(c: *const Link) u64 {
return c.now orelse nowNs();
@@ -3233,6 +3409,15 @@ pub const Link = struct {
}
}
+ /// What was held (`held`) sent, or, its replica not the one they were
+ /// pended on (`send` false), dropped.
+ pub fn release(c: *Link, gpa: Allocator, send: bool) void {
+ var h = c.held orelse return;
+ c.held = null;
+ defer h.deinit(gpa);
+ if (send and !writeAll(c.fd, h.items)) c.cut();
+ }
+
pub fn notify(c: *Link, comptime fmt: []const u8, args: anytype) void {
const text = std.fmt.bufPrint(&c.notice_buf, fmt, args) catch c.notice_buf[0..];
for (text) |*b| if (b.* < 0x20 or b.* > 0x7e) {
@@ -3252,7 +3437,9 @@ pub const Link = struct {
c.input_ns = c.time();
// Sent first: the session steps it while this replica speculates.
const msg = c.r.pend(ev) catch return;
- if (!sendInput(c.fd, msg)) c.cut();
+ if (c.held) |*h| {
+ h.appendSlice(c.r.gpa, msg[head_len..]) catch c.cut();
+ } else if (!sendInput(c.fd, msg)) c.cut();
c.r.applyPended(ev);
c.dirty = true;
}
@@ -3579,7 +3766,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined {
peer.reader = try std.Thread.spawn(.{}, Serve.run, .{peer});
defer ps.letGo(peer);
var why: [300]u8 = @splat(0);
- return joinOn(std.testing.allocator, fds[1], "t", &why, have, null) orelse {
+ return joinOn(std.testing.allocator, fds[1], "t", &why, have, null, null) orelse {
std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)});
return error.JoinFailed;
};
@@ -3710,10 +3897,37 @@ test "a client joining again after a divergence is told at once that its session
var fds: [2]c_int = undefined;
try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds));
_ = libc.close(fds[1]);
- try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1) == null);
+ try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1, null) == null);
try std.testing.expect(ended(&why));
}
+test "an Upgrade tells a client handed to the session and not joined yet that it is upgrading, as it tells its clients; one handed after it is told so at once: each dials again" {
+ var ps: Peers = .{ .gpa = std.testing.allocator, .io = std.testing.io };
+ defer ps.deinit();
+ var fds: [2][2]c_int = undefined;
+ for (&fds) |*f| try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, f));
+ // Handed by the daemon, waiting for the next step boundary; then the
+ // Upgrade's word to the clients (no client joined: count() is 0), and
+ // a hand-over after it, before the exec.
+ ps.handed(fds[0][0], null);
+ ps.refuseAll(undefined);
+ ps.handed(fds[1][0], null);
+ try std.testing.expectEqual(0, ps.inbox.items.len);
+ for (fds) |f| {
+ defer _ = libc.close(f[1]);
+ var buf: [600]u8 = undefined;
+ const n = libc.read(f[1], &buf, buf.len);
+ try std.testing.expect(n > wire.header_len);
+ const msg = try wire.decodeServer(buf[0], buf[wire.header_len..@intCast(n)]);
+ try std.testing.expectEqualStrings(upgrading, msg.refused);
+ try std.testing.expectEqual(0, libc.read(f[1], &buf, buf.len));
+ }
+ // Its exec failed: the session goes on, and takes joins again.
+ ps.boundary(undefined);
+ ps.handed(-1, null);
+ try std.testing.expectEqual(1, ps.inbox.items.len);
+}
+
test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" {
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
@@ -4538,6 +4752,58 @@ test "bytes: a session's first client on its pair, taken before its first effect
try firstOnPair(true);
}
+test "a pair's client makes its own core from the session's options, its file read itself: the welcome confirms it by the digest and no dump is sent" {
+ try ownBootAgainst(false);
+}
+
+test "a pair's client's own core, the file edited between the session's read and its own: the dump is sent, loaded in its place, and the client shows the session's file" {
+ try ownBootAgainst(true);
+}
+
+/// A session's first client on its pair making its core itself
+/// (`ownBoot`), the file it opens `edited` after the session read it.
+fn ownBootAgainst(edited: bool) !void {
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
+ var path_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;
+ const path = try std.fmt.bufPrint(&path_buf, "{s}/a.txt", .{dir});
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "the session's start\n" });
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ const opts: pardes.Options = .{ .cols = 80, .rows = 24, .file = path };
+ const core = try Pardes.init(gpa, opts);
+ defer core.deinit();
+ core.host = TestHost.host();
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .detached = true };
+ defer ps.deinit();
+ defer live_peers = null;
+ defer ps.dropAll(core);
+ ps.join(core, .{ .fd = fds[0] });
+ // Edited after the session read it, before its client does.
+ if (edited) try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "edited between\n" });
+ var o = opts;
+ o.pair = fds[1];
+ var j: Joined = undefined;
+ var why: [600]u8 = @splat(0);
+ const booted = join(gpa, &j, "", "", o, null, &why, null) orelse return error.JoinFailed;
+ const r = confirmBoot(gpa, &j, booted, o, &why) orelse {
+ std.debug.print("the welcome: {s}\n", .{std.mem.sliceTo(&why, 0)});
+ return error.JoinFailed;
+ };
+ defer r.deinit();
+ defer {
+ _ = libc.close(j.fd);
+ j.rest.deinit(gpa);
+ }
+ try std.testing.expectEqual(!edited, r == booted);
+ try std.testing.expectEqual(tape.digestOf(core), r.digest());
+ // What the client shows is the session's file as the session read it.
+ try std.testing.expectEqualStrings("the session's start\n", r.core().panes[0].?.file.?.content);
+}
+
/// A session's first client on a socket pair (runtime/session.zig's, then
/// the client's first join on its end), the session's first effects after:
/// its boot shell spawned, its first bytes output; the client quiet and
@@ -4569,7 +4835,7 @@ fn firstOnPair(bytes: bool) !void {
var j: Joined = undefined;
var why: [600]u8 = @splat(0);
const r = if (bytes) r: {
- j = joinOn(gpa, fds[1], null, &why, null, null) orelse return error.JoinFailed;
+ j = joinOn(gpa, fds[1], null, &why, null, null, null) orelse return error.JoinFailed;
defer gpa.free(j.dump);
const r = try Replica.initDump(gpa, j.client, j.view, j.dump, opts);
r.t.screen_state = false;
@@ -4578,10 +4844,20 @@ fn firstOnPair(bytes: bool) !void {
} else r: {
var o = opts;
o.pair = fds[1];
- break :r join(gpa, &j, "", "", o, null, &why, null) orelse {
+ // Its own core, from the same options, before any byte of the
+ // session's; the welcome then says it is the session's: no dump.
+ const booted = join(gpa, &j, "", "", o, null, &why, null) orelse {
std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)});
return error.JoinFailed;
};
+ try std.testing.expect(j.booted);
+ const r = confirmBoot(gpa, &j, booted, o, &why) orelse {
+ std.debug.print("the welcome: {s}\n", .{std.mem.sliceTo(&why, 0)});
+ return error.JoinFailed;
+ };
+ try std.testing.expect(r == booted);
+ try std.testing.expectEqual(@as(usize, 0), j.dump.len);
+ break :r r;
};
defer r.deinit();
defer {
diff --git a/core/root.zig b/core/root.zig
index b5109b0e..572204a1 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -630,7 +630,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "hunks.zig", 1, "a test helper's file read" },
.{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" },
.{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" },
- .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
+ .{ "replica.zig", 75, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
.{ "rollback.zig", 1, "a test helper's directory" },
.{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" },
.{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" },
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 521f685f..d779cf47 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1429,16 +1429,22 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
// A new process's window: the build at its start path, exec'd.
- .upgrade => |view| Said.no(io, "{s}", .{client_loop.execAgain(&start, view)}),
+ .upgrade => |view| {
+ // Its new window the size this one has now.
+ var size: [2]c_int = .{ 0, 0 };
+ _ = c.SDL_GetWindowSize(g.window, &size[0], &size[1]);
+ Said.no(io, "{s}", .{client_loop.execAgain(&start, view, size)});
+ },
.left => {
var said: [600]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
std.process.exit(0);
},
.ended => |code| {
- // A pair's window is its session's parent: its status once it
- // is gone, as the terminal's (tui.zig `runClient`).
- if (opts_in.pair != null) {
+ // A pair's window is its session's parent, an exec'd one too:
+ // its status once it is gone, as the terminal's (tui.zig
+ // `runClient`).
+ if (!to.far) {
var status: c_int = 0;
while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
}
@@ -2501,7 +2507,7 @@ const Shell = struct {
core.settle();
// Its replica clients told, their views gone before the dump: each
// dials the session again once it is back.
- s.peers.refuseAll(core, "the session is upgrading to another build of pardes");
+ s.peers.refuseAll(core);
var rec: upgrade.Record = .{ .link = daemon.link, .window = s.gui != null, .exe = path };
s.ptys.record(&rec);
var at_buf: [1024:0]u8 = undefined;
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index e441df92..09704424 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -800,9 +800,11 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
},
.ended => |code| {
screen.leave();
- // A pair's client is its session's parent: its status once it
- // is gone, as a terminal's job ends with its program.
- if (opts.pair != null) {
+ // A pair's client is its session's parent, an exec'd one too
+ // (an Upgrade's, which `opts.pair` no longer says): its status
+ // once it is gone, as a terminal's job ends with its program.
+ // Not its child: no wait (ECHILD at once).
+ if (!far_link) {
var status: c_int = 0;
while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
}
@@ -816,7 +818,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
// The blink: its screen left, the build at its start path
// exec'd, which enters it again.
screen.leave();
- Said.no(io, "{s}", .{client_loop.execAgain(&start, view)});
+ Said.no(io, "{s}", .{client_loop.execAgain(&start, view, null)});
},
}
}
@@ -1306,7 +1308,7 @@ const Shell = struct {
core.settle();
// Its replica clients told, their views gone before the dump: each
// dials the session again once it is back.
- s.peers.refuseAll(core, "the session is upgrading to another build of pardes");
+ s.peers.refuseAll(core);
var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path };
s.ptys.record(&rec);
if (s.screen) |sc| if (sc.on) rec.addTty(.{
diff --git a/runtime/client.zig b/runtime/client.zig
index 55171af2..d4b76a1b 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -125,11 +125,14 @@ pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8
/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
/// Returns only when the exec failed: why.
-pub fn execAgain(s: *Start, view: u8) []const u8 {
+pub fn execAgain(s: *Start, view: u8, size: ?[2]c_int) []const u8 {
const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from";
var at_buf: [4200]u8 = undefined;
const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by";
- const argv = [_:null]?[*:0]const u8{ path, at };
+ // A window's new window the size it had (`--geometry`), not the default.
+ var size_buf: [48]u8 = undefined;
+ const geometry: ?[*:0]const u8 = if (size) |wh| (std.fmt.bufPrintSentinel(&size_buf, "--geometry={d}x{d}", .{ wh[0], wh[1] }, 0) catch unreachable).ptr else null; // two c_ints fit 48
+ const argv = [_:null]?[*:0]const u8{ path, at, geometry };
var view_buf: [32]u8 = undefined;
const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32
var n: usize = 0;
@@ -191,7 +194,9 @@ pub fn Loop(comptime Frontend: type) type {
upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
- l.fe.start(l);
+ if (s.joined.booted) {
+ if (!l.confirm(s)) return .failed;
+ } else l.fe.start(l);
var done: std.atomic.Value(bool) = .init(false);
const reader = try std.Thread.spawn(.{}, read, .{ l, s, &done });
while (!link.quit) {
@@ -232,6 +237,28 @@ pub fn Loop(comptime Frontend: type) type {
}
}
+ /// A pair's first join, its replica its own boot (replica.ownBoot): its
+ /// start's inputs held and its first pass drawn, then the session's
+ /// welcome read: the same core, what was held is sent; another (the
+ /// dump came), the dump's replica in place of the boot's, started
+ /// again. False, and why in `s.why`: no session to go on with.
+ fn confirm(l: *L, s: *Start) bool {
+ const link = &l.link;
+ link.held = .empty;
+ l.fe.start(l);
+ _ = l.before();
+ const r = replica.confirmBoot(s.gpa, &s.joined, s.r, s.o, &s.why) orelse {
+ link.release(s.gpa, false);
+ return false;
+ };
+ link.release(s.gpa, r == s.r);
+ if (r == s.r) return true;
+ s.r = r;
+ link.reset(r, &s.joined);
+ l.fe.start(l);
+ return true;
+ }
+
/// The session's stream, onto the frontend's queue: its messages,
/// and its end.
fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void {
diff --git a/runtime/main.zig b/runtime/main.zig
index 0751f6b0..b0338831 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1812,6 +1812,10 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
+ // The client makes its core from its session's options (replica.ownBoot):
+ // a window's session is the terminal binary it execs, whose views are
+ // not windowed until a window says so (its first input).
+ o.windowed = false;
clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
diff --git a/test/daemon.py b/test/daemon.py
index acfa4896..2c86c04f 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -29,6 +29,9 @@ private HOME and runtime directory:
`pardes new --detach` returns once its session runs
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
+ python3 -B test/daemon.py --attach-upgrading <pardes>
+ an attach started as its session upgrades, and two clients' views
+ across an Upgrade (in plain and --pair too)
python3 -B test/daemon.py --relink <pardes>
the daemon killed: its sessions register again with the next; and
one stopped: an Adopt waits for its answer to the hello
@@ -43,6 +46,7 @@ private HOME and runtime directory:
at 0/30/80/207 ms, and a window's session serving replicas
"""
import fcntl
+import json
import os
import random
import re
@@ -242,7 +246,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 26
+ WIRE = 27
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -749,9 +753,12 @@ def pair_rows(binary):
def upgraded(name, nine, session):
"""An Upgrade to the same build: the session exec'd under its pid, its
- 9P again."""
+ 9P again: its socket made anew (a second Upgrade's command line says
+ `--upgraded=` before its exec too)."""
+ sock = root / f'pardes-9p-{name}.sock'
+ before = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
- wait_for('the session exec\'d', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(session)), timeout=60)
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60)
nine.socket.close()
again = reconnect(root / f'pardes-9p-{name}.sock')
assert alive(session)
@@ -864,6 +871,369 @@ def pair_rows(binary):
shutil.rmtree(root, ignore_errors=True)
+def attach_upgrading(binary, rounds=6):
+ """`pardes attach` as its session upgrades: started at once after the
+ Upgrade's word, it is handed to the session before the exec; told the
+ session is upgrading (never cut by the exec unanswered: "hung up before
+ the dump was whole", exit 1), it dials again and joins the new process.
+ A `new --detach` session, without the variable and with it."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+ try:
+ for e in (env, dict(env, PARDES_PAIR='1')):
+ name = 'up' + e.get('PARDES_PAIR', '')
+ out = subprocess.run([binary, 'new', f'--detach={name}', str(notes)], env=e, cwd=root, capture_output=True,
+ timeout=30, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out
+ sock = root / f'pardes-9p-{name}.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ for k in range(rounds):
+ before = sock.stat().st_ino
+ nine.write('/ctl', b'Upgrade\n')
+ time.sleep(k * .005)
+ t = Term(30, 100)
+ terms.append(t)
+ a = t.spawn([binary, 'attach', name], e)
+ wait_for('the client drawn, or gone', lambda: b'line 3 of the notes' in t.text() or a.poll() is not None, timeout=40)
+ assert a.poll() is None, (k, a.returncode, t.text()[-120:])
+ os.kill(a.pid, signal.SIGKILL)
+ a.wait(timeout=10)
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60)
+ nine.socket.close()
+ nine = reconnect(sock)
+ assert alive(session)
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', name], env=e, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ print(f'attach upgrading: an attach started as its session upgrades joins the new process ({rounds} of {rounds}, '
+ 'without the variable and with it)')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair_upgrade_views(binary):
+ """PARDES_PAIR, two clients each in its own view (the pair's own terminal
+ and an attach), each with its own scroll and focus: the pair's scrolled
+ down a long file a page at a time, the attach's focus on a pane of its
+ own (New); an Upgrade lets both go and each joins again for its view
+ (views.away): the same lines shown, the cursor where it was, in each."""
+ import pyte
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ terms = []
+
+ def screen(t):
+ s = pyte.Screen(100, 30)
+ # Its colours (SGR with colons, which pyte misreads) left out.
+ pyte.ByteStream(s).feed(re.sub(rb'\x1b\[[0-9:;]*m', b'', t.text()))
+ return s
+
+ def shown(t):
+ """The notes' lines it shows, and its cursor."""
+ s = screen(t)
+ return sorted(int(m.group(1)) for row in s.display for m in re.finditer(r'line (\d+) of the notes', row)), (s.cursor.x, s.cursor.y)
+
+ def settled(t):
+ last = [None, 0]
+
+ def same():
+ now = shown(t)
+ if now != last[0]:
+ last[0], last[1] = now, time.monotonic()
+ return time.monotonic() - last[1] > 1.5 and now
+ return wait_for('its screen settled', same, timeout=30)
+
+ try:
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, '--9p=pv', str(notes)], env)
+ sock = root / 'pardes-9p-pv.sock'
+ wait_for('the socket', sock.exists)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ for _ in range(3):
+ os.write(t.master, b'\x1b[6~')
+ time.sleep(.2)
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', 'pv'], env)
+ wait_for('the attach drawn', lambda: b'\x1b[?1049h' in tt.text(), timeout=30)
+ os.write(tt.master, b'j')
+ time.sleep(.3)
+ before_panes = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ wait_for('a pane in the attach\'s view', lambda: view_panes(nine) - before_panes)
+
+ def focus():
+ """Each client's focus: its view live (a key that moves nothing)."""
+ got = []
+ for term in (t, tt):
+ os.write(term.master, b'\x1b')
+ time.sleep(.6)
+ got.append(nine.read('/focus'))
+ return got
+ focused = focus()
+ before = settled(t), settled(tt)
+ assert before[0][0] and before[0][0][0] >= 40, ('the pair scrolled', before[0])
+ marks = len(t.text()), len(tt.text())
+ ino = sock.stat().st_ino
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
+ nine = reconnect(sock)
+ for term, mark in zip((t, tt), marks):
+ wait_for('joined again', lambda: b'joined again' in term.text()[mark:], timeout=30)
+ after = settled(t), settled(tt)
+ assert after == before, ('each client\'s lines and cursor as they were', before, after)
+ # Its focus: what it types lands in the pane it had the keyboard in
+ # (/focus, read after a key, is which view is live then: not a
+ # client's own).
+ for term, pane, word in zip((t, tt), focused, (b'PAIRTYPED', b'ATTACHTYPED')):
+ os.write(term.master, b'i' + word + b'\x1b')
+ wait_for('typed into its pane', lambda: word in nine.read(f'/pane/{int(pane)}/body'), timeout=10)
+ print('pair upgrade views: two clients, each its own view: the pair\'s scroll and the attach\'s focus as they were after an Upgrade')
+ nine.socket.close()
+ a.terminate()
+ a.wait(timeout=20)
+ os.kill(c.pid, signal.SIGTERM)
+ c.wait(timeout=20)
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair_exec_reaps(old, new):
+ """PARDES_PAIR across builds: a pair started from `root/bin` (old), its
+ session upgraded to the build installed there since (new): its client,
+ the session's parent, execs that build (the blink) and is still its
+ parent; Exit typed then: the client returns once the session is gone,
+ reaped, its status the session's (0), as before the exec."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary = root / 'bin' / 'pardes'
+ install(old, binary)
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+ try:
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([str(binary), '--9p=px', str(notes)], env)
+ sock = root / 'pardes-9p-px.sock'
+ wait_for('the socket', sock.exists)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert ppid(session) == c.pid
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ install(new, binary)
+ ino = sock.stat().st_ino
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
+ wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ assert ppid(session) == c.pid
+ mark = len(t.text())
+ wait_for('drawn again', lambda: b'line 3 of the notes' in t.text()[mark:], timeout=30)
+ nine.write('/ctl', b'Exit\n')
+ nine.socket.close()
+ assert c.wait(timeout=30) == 0, c.returncode
+ # Its parent's wait returned: the session reaped, not a zombie left
+ # to whoever takes it in.
+ assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read()
+ print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def far_exec(old, new):
+ """A far client (PARDES_REPLICA_FAR, as through ssh's forward) of a
+ session started from `root/bin` (old), the session upgraded to the build
+ installed there since (new): the far client execs the build at its own
+ start path (its install holds the session's build now), the same
+ process, far still, and is back in its view: its key steps the session
+ and its digest agrees. Not through ssh: its forward's own end is not
+ here (its socket file left behind at the exec, the far install holding
+ another build: not covered)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary = root / 'bin' / 'pardes'
+ install(old, binary)
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=fx', str(notes)], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-fx.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ t = Term(30, 100)
+ terms.append(t)
+ check = root / 'f.check'
+ c = t.spawn([str(binary), f'--attach={root / "pardes-replica.sock"}:fx'],
+ dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check)))
+ wait_for('the far client drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ key = lambda b: os.write(t.master, b) # noqa: E731
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('its key stepped', lambda: agreed(check, seen + 1), timeout=30)
+ install(new, binary)
+ mark = len(t.text())
+ ino = sock.stat().st_ino
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
+ nine = reconnect(sock)
+ wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
+ assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ seen = len(checks(check))
+ key(b'j')
+ wait_for('its key stepped after', lambda: agreed(check, seen + 1), timeout=30)
+ assert c.poll() is None
+ print('far exec: a far client exec\'d the build at its start path at its session\'s Upgrade, far still, and agrees')
+ c.terminate()
+ c.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'fx'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair_window_geometry(gui_binary, new_gui):
+ """PARDES_PAIR, a window with `--geometry=WxH` (offscreen, not test
+ mode: its grid is its window's): another build at its start path, its
+ session upgraded: the window client execs it, and its new window is the
+ size it had (the session's grid as before), not the default's."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1',
+ SDL_VIDEO_DRIVER='offscreen')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ (root / 'bin').mkdir()
+ gui = root / 'bin' / 'pardes-gui'
+ install(Path(gui_binary), gui)
+ install(Path(gui_binary).with_name('pardes'), gui.with_name('pardes'))
+ procs = []
+
+ def grid(nine):
+ s = json.loads(nine.read('/screen'))
+ return s['cols'], s['rows']
+
+ def started(name, *flags):
+ p = subprocess.Popen([str(gui), f'--9p={name}', *flags, str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=open(root / f'{name}.err', 'w'), start_new_session=True)
+ procs.append(p)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ wait_for('its window\'s grid', lambda: grid(nine) != (80, 24), timeout=30)
+ time.sleep(1)
+ return p, nine, grid(nine)
+
+ try:
+ p0, n0, plain = started('plain')
+ n0.write('/ctl', b'Exit\n')
+ n0.socket.close()
+ p0.wait(timeout=30)
+ p, nine, sized = started('sized', '--geometry=900x560')
+ assert sized != plain, ('--geometry makes its own grid', sized, plain)
+ install(Path(new_gui), gui)
+ install(Path(new_gui).with_name('pardes'), gui.with_name('pardes'))
+ sock = root / 'pardes-9p-sized.sock'
+ ino = sock.stat().st_ino
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
+ wait_for('the window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30)
+ nine = reconnect(sock)
+ time.sleep(3)
+ assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain)
+ print(f'pair window geometry: --geometry=900x560 ({sized[0]}x{sized[1]}, the default {plain[0]}x{plain[1]}): the window exec\'d at an Upgrade the size it had')
+ nine.write('/ctl', b'Exit\n')
+ nine.socket.close()
+ p.wait(timeout=30)
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ for q in processes(root):
+ try:
+ os.kill(q, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -2145,6 +2515,8 @@ def main(binary, cycles):
launch(binary)
pair(binary)
pair_rows(binary)
+ attach_upgrading(binary)
+ pair_upgrade_views(binary)
manage(binary)
relink(binary)
answer_late(binary)
@@ -3093,10 +3465,16 @@ if __name__ == '__main__':
if sys.argv[1:3] == ['--upgrade', '--gui']:
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
- upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ old, new = Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()
+ upgrades(old, new)
+ if knows_exec(old):
+ pair_exec_reaps(old, new)
+ far_exec(old, new)
# With a pardes-gui beside each: the clients carried too.
- if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
- upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ if all(a.with_name('pardes-gui').exists() for a in (old, new)):
+ upgrade_clients(old, new)
+ if knows_exec(old):
+ pair_window_geometry(old.with_name('pardes-gui'), new.with_name('pardes-gui'))
elif sys.argv[1:2] == ['--upgrade-clients']:
upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
@@ -3108,6 +3486,10 @@ if __name__ == '__main__':
elif sys.argv[1:2] == ['--pair']:
pair(sys.argv[2])
pair_rows(sys.argv[2])
+ attach_upgrading(sys.argv[2])
+ pair_upgrade_views(sys.argv[2])
+ elif sys.argv[1:2] == ['--attach-upgrading']:
+ attach_upgrading(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
answer_late(sys.argv[2])