summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-21 01:34:10 -0300
committerGabriel Schneider <[email protected]>2026-11-21 01:51:21 -0300
commit63f59cbf3092c8bb7e3eae155969c0249fe2063d (patch)
tree09b8e3631b3e7797e597124dedb284f09f2d8cd7
parent6d937cd125ca04a2edb92b2d014014ee6c2eb45d (diff)
downloadpardes-63f59cbf3092c8bb7e3eae155969c0249fe2063d.tar.gz
pardes-63f59cbf3092c8bb7e3eae155969c0249fe2063d.zip
replica: an attach handed to a session as it upgrades is told so and joins the new process, never cut unanswered by the exec: `Peers.refuseAll` returned at once when no client was joined, and with clients its `drop` closed the connections queued in `Peers.inbox` without a word, and a hand-over posted after it was closed by the exec (MSG_CMSG_CLOEXEC), so `pardes attach NAME` started as NAME upgraded said "the session hung up before the dump was whole" and exited 1, with PARDES_PAIR or without (exp2: a `new --detach` session, no variable, ReleaseSafe main: 2 of 20 attaches at 0 ms); now refuseAll tells each queued connection what it tells its clients (`replica.upgrading`, "the session is upgrading to another build of pardes", the words tui and gui passed), `Peers.upgrading` makes `post` tell a later hand-over the same at once (reset at the next boundary: the exec failed), and a first join told so dials again patiently (`join` -> `redial`, its view optional); the pair row that failed on the release build only (daemon.py --pair, `ended_by(how, *attached('rows'))`, the coordinator's landing check) was this race, reached through the test: its `upgraded()` waited for `--upgraded=` in the session's command line, which a second Upgrade's old process already had, so it attached to the old process; found under strace (the daemon handed the attach, then took the session's `upgrade`, then exec'd); the release build and the test's long runtime path only moved the timing; `upgraded()` now waits for the session's 9P socket made anew; tests: core/replica.zig "an Upgrade tells a client handed to the session and not joined yet that it is upgrading ..." (main: both hand-overs still queued, never told), test/daemon.py `attach_upgrading` (plain, --pair, --attach-upgrading: an attach started 0-25 ms after the Upgrade's word, without the variable and with it: main's release build failed its first round)
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--core/replica.zig68
-rw-r--r--dev/gui/gui.zig2
-rw-r--r--dev/tui/tui.zig2
-rw-r--r--test/daemon.py70
4 files changed, 130 insertions, 12 deletions
diff --git a/core/replica.zig b/core/replica.zig
index e2ecc796..92d3ea90 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -2063,6 +2063,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,
@@ -2108,6 +2112,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) {
@@ -2155,6 +2163,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 {};
@@ -2417,13 +2426,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).
@@ -2993,6 +3012,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";
@@ -3030,7 +3052,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, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else 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 = &.{};
@@ -3080,8 +3104,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);
@@ -3656,6 +3681,33 @@ test "a client joining again after a divergence is told at once that its session
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);
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 521f685f..d10173b4 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -2501,7 +2501,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..a6d2216d 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -1306,7 +1306,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/test/daemon.py b/test/daemon.py
index 44221d17..d3ba6e3d 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -29,6 +29,8 @@ 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 (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
@@ -748,9 +750,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)
@@ -863,6 +868,63 @@ 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 manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -2069,6 +2131,7 @@ def main(binary, cycles):
launch(binary)
pair(binary)
pair_rows(binary)
+ attach_upgrading(binary)
manage(binary)
relink(binary)
answer_late(binary)
@@ -3022,6 +3085,9 @@ if __name__ == '__main__':
elif sys.argv[1:2] == ['--pair']:
pair(sys.argv[2])
pair_rows(sys.argv[2])
+ attach_upgrading(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])