From 774efcc950662cd20c1b4a41d002ce421067564f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:49:10 -0300 Subject: pair: the boot as input zero (the last step's design 3, way a2): under PARDES_PAIR the client no longer waits for its session's init, dump and socket before its first frame: it makes its own core from the same options and arguments (replica.ownBoot, Replica.initBoot: Pardes.init on no tape, as the session's start, its file read on its own machine, then the view the session's join opens for it, Peers.viewFor, shared by both), draws it, and says its digest before its `far` (a new client word, `boot`, 0x0a: 0x09 is the server's zstd envelope, which a stream's reader unpacks whichever way it runs; wire protocol 26, after the other line's 25); the session's writer sends no dump when the joiner's boot digest is its own at the join, and the client, reading the welcome once its first frame is drawn (replica.confirmBoot, client.zig `confirm`, the start's inputs held until then: Link.held, Link.release), goes on from its own core, or, unequal (the file edited between the two reads, anything else a start reads otherwise), loads the dump in its place and starts again; what made boots unequal by construction, found by the digest's parts compared in a scratch build: a join's view settled the session's first effects (Pardes.settle in openView: its boot shell spawned and acknowledged inside the join), which a client cannot perform; the effects queued before a join are now performed after it, on the tape the client is sent (viewFor, queueFirst), so the boot shell's spawn and first bytes reach the client as units, as P32 asked, and the dump path gets them so too; and a boot stepped on the replica's own tape read the machine as a replica's step would (the shell, the directory): Pardes.init runs on no tape, the view on the replica's tape (no terminal reloaded there, as on the session's screen-state tape); confirmed over 100 starts of a file and 100 of a shell (see the report); a boot's terminals are made on the C heap (panes.emulatorGpa reads dump.terminal_gpa); a window's pair's client boots unwindowed, as the terminal binary its session execs (main.zig `pair`, Options.windowed); tests: core/replica.zig "a pair's client makes its own core ...: no dump is sent" and "... the file edited between ...: the dump is sent, loaded in its place, and the client shows the session's file", and firstOnPair's screen-state client now its own boot, confirmed with no dump, the boot shell's spawn and first bytes after, digests equal, no reload; the start (ReleaseFast, medium.zig, one build alternated, NOT quiet: loads 8-16): the pair's first frame best 9.5 ms against the own path's 9.9 (median 10.2 against 11.4), the client 45.0-53.8M instructions:u (the bar 56.7M), its session 17.2-17.6M beside it, the own path 53.5M bit-equal to the base's; confirmed 100 of 100 starts of a file and 100 of 100 of a shell, a window pair 17 of 17; tui core-test 863/1018 (155 skipped), shell-test 1060/1063, term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed, as a pair (PARDES_PAIR=1) 16 of 144 failed (the base 17), both soaks diverged 0, unequal 0, checked/wrong 0, unlisted 0, corpus 22 of 22, no leak, daemon.py plain, --far, --pair, --relink, --launch, --games, --window-clients, --gui, --upgrade both ways (new->old failed once on a client's key under load, then passed twice) pass, an idle pair 0 and 0 wakeups in 2 s, gui unit-test 1656/1660 with only BaselineHarnessMismatch, the frame and perf gate against tree2 PASS (77/77 frames, corpus2x -0.008%, 121 per-operation counts within 0.1%), macOS lib (Linux host), aarch64-macos and FreeBSD build (loads 5-23) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'test/daemon.py') diff --git a/test/daemon.py b/test/daemon.py index b28d16ea..1107e502 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -241,7 +241,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 = 24 + WIRE = 26 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout -- cgit v1.3 From 63f59cbf3092c8bb7e3eae155969c0249fe2063d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 01:34:10 -0300 Subject: 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 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 68 +++++++++++++++++++++++++++++++++++++++++++++++------- dev/gui/gui.zig | 2 +- dev/tui/tui.zig | 2 +- test/daemon.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 130 insertions(+), 12 deletions(-) (limited to 'test/daemon.py') 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_PAIR: a terminal's session and its first client + python3 -B test/daemon.py --attach-upgrading + an attach started as its session upgrades (in plain and --pair too) python3 -B test/daemon.py --relink 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]) -- cgit v1.3 From fe0aa07c18a9fd5ca6bdcb78e9354a2745e32298 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 03:29:45 -0300 Subject: client: what the pair's last rounds left, each a test first: a window client exec'd at its session's Upgrade comes back the size it was, not the default (runtime/client.zig `execAgain` passed `--attach=` alone, so the new process made a 1120x720 window: a `--geometry=900x560` pair's session went from 56x16 to 70x20 after an Upgrade to another build, with the variable or without (any `pardes-gui attach`); now the window's size at the exec, SDL_GetWindowSize, as `--geometry=WxH`); a pair's client exec'd at an Upgrade waits for its session at `ended` as before the exec (tui.zig and gui.zig `runClient` asked `opts.pair`, which the exec'd `--attach=` client has not: now every near client waits, a non-child answers ECHILD at once; not seen to fail here: the subreaper took the session first); tests in test/daemon.py: `pair_upgrade_views` (plain, --pair: two clients' own views, the pair's scroll and the attach's focus, the same after a same-build Upgrade: the screens by pyte, the focus by where typing lands: passed before this change too), `pair_exec_reaps`, `far_exec` (a far client, PARDES_REPLICA_FAR by the socket's path, execs the build at its start path and agrees after: passed before too), `pair_window_geometry` (offscreen, not test mode: failed before), the last three in --upgrade OLD NEW Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/gui/gui.zig | 14 ++- dev/tui/tui.zig | 10 +- runtime/client.zig | 7 +- test/daemon.py | 324 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 341 insertions(+), 14 deletions(-) (limited to 'test/daemon.py') diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index d10173b4..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) {} } diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index a6d2216d..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)}); }, } } diff --git a/runtime/client.zig b/runtime/client.zig index c550b0fa..22e60fc1 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; diff --git a/test/daemon.py b/test/daemon.py index 5744b099..7a600048 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -30,7 +30,8 @@ private HOME and runtime directory: python3 -B test/daemon.py --pair PARDES_PAIR: a terminal's session and its first client python3 -B test/daemon.py --attach-upgrading - an attach started as its session upgrades (in plain and --pair too) + 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 the daemon killed: its sessions register again with the next; and one stopped: an Adopt waits for its answer to the hello @@ -44,6 +45,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 @@ -925,6 +927,312 @@ def attach_upgrading(binary, rounds=6): 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 @@ -2132,6 +2440,7 @@ def main(binary, cycles): pair(binary) pair_rows(binary) attach_upgrading(binary) + pair_upgrade_views(binary) manage(binary) relink(binary) answer_late(binary) @@ -3070,10 +3379,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']: @@ -3086,6 +3401,7 @@ if __name__ == '__main__': 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']: -- cgit v1.3