diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 02:21:52 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 04:00:32 -0300 |
| commit | 1967cf64dc6d7490d386db874cf1866b764f235c (patch) | |
| tree | fd11484ffcb69b6e70fe6ea9610e8fdfb8d682bf | |
| parent | 969369d4b84fa1847dc3dee0e737dcd58e56c5e7 (diff) | |
| download | pardes-1967cf64dc6d7490d386db874cf1866b764f235c.tar.gz pardes-1967cf64dc6d7490d386db874cf1866b764f235c.zip | |
daemon: a session registers again with a daemon that was restarted: its link's reader, woken by the link's end alone (no timer, no poll: an idle session stays at 0 wakeups), dials the next daemon, starting one if none answers, and says its hello again on the link's own fd (dup3, so the session's own sends never race a new fd); the session loop, woken once by the note, tells it its shells' masters (`Ptys.tellDaemon`) and its clients again (`relinked`); a link the daemon never took (another build's) or the session's own end (`quit`) is not dialled again; test/daemon.py's `relink` (in plain, and alone as `--relink`), first failing on the base ("a daemon again" timed out: nothing dialled), now: the daemon killed, its two sessions (one detached, one with its terminal) start the next and are listed again with their shells, a client attaches, the detached one killed outright leaves its shell to another's Adopt, 0 and 0 wakeups in 2 s before and after; and the killed-session words in daemon.py read once the test's terminal has them (a race of the test's own); gated with the previous change, Debug: tui core-test 855/1005, shell-test 1046/1049, term 17/17, pane 183/184, kitty 45/45, behaviour 275/275 and its replay, process-test 0 of 144 failed, both soaks diverged 0 unequal 0 at 30/80/207 ms (corpus 22 scenes the same), daemon.py plain (50 cycles), far, games, window-clients, gui, upgrade both ways with clients attached pass; gui unit-test 1643/1647 (BaselineHarnessMismatch only); macOS x86_64 and aarch64, FreeBSD cross-builds pass; the frame and perf gate against tree2 PASS: 77/77 frames, perfab-corpus2x -0.114% (threshold 0.4%), 121 per-operation counts within 0.1% (largest +0.014%)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | dev/Ptys.zig | 6 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 1 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 2 | ||||
| -rw-r--r-- | runtime/daemon.zig | 124 | ||||
| -rw-r--r-- | runtime/session.zig | 6 | ||||
| -rw-r--r-- | test/daemon.py | 138 |
6 files changed, 237 insertions, 40 deletions
diff --git a/dev/Ptys.zig b/dev/Ptys.zig index 97c5cfde..16a31939 100644 --- a/dev/Ptys.zig +++ b/dev/Ptys.zig @@ -156,6 +156,12 @@ pub fn signal(p: *Ptys, id: pardes.Pane.Id, sig: pardes.PtySignal) void { if (p.slots[id.index()]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); } +/// A daemon started since the last one died: every master told it again, +/// as `spawn` tells the first (host_io.forkShell). +pub fn tellDaemon(p: *const Ptys) void { + for (p.slots) |slot| if (slot) |pt| daemon.pty(pt.pid, pt.fd); +} + /// The pane is gone, or its shell is: its reader out of the queue first /// (which lets go one waiting for room there) and canceled; its pty hung /// up, which the kernel passes on to the shell as SIGHUP; the daemon's diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 81d58137..2aaa8bcc 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -3182,6 +3182,7 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const s: *Shell = @ptrCast(@alignCast(ctx)); const q = s.queue; switch (note) { + .relinked => q.wake(), .adopted => |a| { for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 42f73559..c54447c7 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1101,6 +1101,8 @@ fn clearNativeImages( fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const loop: *Loop = @ptrCast(@alignCast(ctx)); switch (note) { + // A full queue wakes it anyway. + .relinked => _ = loop.tryPostEvent(.nop) catch false, .adopted => |a| { for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { _ = libc.close(fd); diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 1b9149b6..80e1cc09 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -12,7 +12,8 @@ //! - whether a terminal or a window shows it (`state`). //! It lists the sessions (`pardes ps`), hands a crashed session's masters //! to the one that asks for them (Adopt), and a client's connection to the -//! session it names (below). +//! session it names (below). A session whose daemon died dials the next +//! one and registers again (`readNotes`). //! //! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it //! carries (SCM_RIGHTS). @@ -290,9 +291,17 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) /// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off). pub var link: c_int = -1; /// The daemon said `ok` to the hello, and the link has not ended since; -/// `gone` once it has ended. +/// `gone` once it has ended for good (`readNotes`). var up = std.atomic.Value(bool).init(false); var gone = std.atomic.Value(bool).init(false); +/// The session is ending (`quit`): its link's end is no daemon's death. +var quitting = std.atomic.Value(bool).init(false); +/// A new daemon took the hello since the last one died: the rest of what +/// the dead one was told is to be told again (`relinked`). +var retell = std.atomic.Value(bool).init(false); +/// What the hello says besides the name: the kind, and whether detached. +var kind: Kind = .tty; +var detached_now = std.atomic.Value(bool).init(false); /// What it is called (its 9P name). var name_buf: [128]u8 = undefined; var name_len: usize = 0; @@ -328,6 +337,8 @@ fn setName(named: []const u8) void { pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool { if (comptime !supported) return false; setName(named); + kind = k; + detached_now.store(detached, .release); const c = fd orelse connect(true) orelse return false; startPending(true); if (!hello(c, k, libc.getpid(), name(), detached)) { @@ -362,19 +373,33 @@ pub fn closed(pid: libc.pid_t) void { /// Its own frontend let go (Detach, its terminal's end): detached for /// good, an attach after it a client. pub fn setDetached() void { + detached_now.store(true, .release); tell("state detached", &.{}); } +/// The last `clients` line, kept to be told to a new daemon (`relinked`). +var clients_line: ["clients".len + max_clients * " -2147483648".len]u8 = undefined; +var clients_len: usize = 0; + /// This session's replica clients now, each its process's pid (0 when its /// socket's peer is not known), for `--ps`. pub fn clients(pids: []const libc.pid_t) void { - var buf: ["clients".len + max_clients * " -2147483648".len]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - w.writeAll("clients") catch unreachable; // a literal, its .len in buf's - for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in buf's type + var w: std.Io.Writer = .fixed(&clients_line); + w.writeAll("clients") catch unreachable; // a literal, its .len in clients_line's + for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in clients_line's type + clients_len = w.end; tell(w.buffered(), &.{}); } +/// Whether a new daemon took this session's hello since the last call +/// (the session loop's, each pass): its clients told it again here, its +/// ptys the caller's to tell (`pty`). +pub fn relinked() bool { + if (!retell.swap(false, .acq_rel)) return false; + if (clients_len > 0) tell(clients_line[0..clients_len], &.{}); + return true; +} + /// Asks for the masters of sessions that died holding them; they come back /// as an `adopted` note. pub fn adopt() void { @@ -396,10 +421,15 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache stub = stub_fd; if (stub >= 0) hupOnStubDeath(true); setName(named); + kind = k; + detached_now.store(detached, .release); if (fd >= 0 and hello(fd, k, libc.getpid(), name(), detached)) link = fd else if (fd >= 0) _ = libc.close(fd); } pub const Note = union(enum) { + /// A new daemon took the hello (`readNotes`): the session loop is woken + /// to tell it the rest (`relinked`). + relinked, adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, /// A replica's connection, its hello taken (core/replica.zig `Peers`), /// and the view it joins again for, if it does. @@ -417,39 +447,58 @@ pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) v fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { var buf: [msg_max]u8 = undefined; - // The end of the link (a daemon gone, a hello refused): not kept. - defer { - up.store(false, .release); - gone.store(true, .release); - } - while (recv(fd, &buf)) |got| { - var words = std.mem.tokenizeScalar(u8, got.words, ' '); - const verb = words.next() orelse ""; - if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) { - .ok => up.store(true, .release), - .replica => { - const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null; - if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } }); - for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); - }, - .adopted => { - var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; - const a = ¬e.adopted; - for (got.fds[0..got.nfds]) |f| { - const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch { - _ = libc.close(f); - continue; - }; - a.pids[a.n] = pid; - a.fds[a.n] = f; - a.n += 1; - } - deliver(ctx, note); - }, - } else for (got.fds[0..got.nfds]) |f| { - _ = libc.close(f); + while (true) { + while (recv(fd, &buf)) |got| { + var words = std.mem.tokenizeScalar(u8, got.words, ' '); + const verb = words.next() orelse ""; + if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) { + .ok => up.store(true, .release), + .replica => { + const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null; + if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } }); + for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); + }, + .adopted => { + var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; + const a = ¬e.adopted; + for (got.fds[0..got.nfds]) |f| { + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch { + _ = libc.close(f); + continue; + }; + a.pids[a.n] = pid; + a.fds[a.n] = f; + a.n += 1; + } + deliver(ctx, note); + }, + } else for (got.fds[0..got.nfds]) |f| { + _ = libc.close(f); + } } + // The end of the link. One whose daemon took the hello (it died, or + // let the session go) is dialled again, a daemon started if none + // answers, and the hello said, here, off the session's way: the + // link's end is what wakes this, never a timer. One that never took + // it (another build's daemon), or the session's own end, is not: + // an end begun while it dialled finds the new link (`quit`). + if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break; + retell.store(true, .release); + deliver(ctx, .relinked); } + // Not kept, until the session's end. + gone.store(true, .release); +} + +/// A new connection in the place of `fd`, the link (its number kept, so +/// the session's own sends never race a new fd), and the hello said on it. +fn redial(fd: c_int) bool { + if (comptime !supported) return false; + const c = connect(true) orelse return false; + startPending(true); + defer _ = libc.close(c); + return libc.dup3(c, fd, @bitCast(@as(u32, @bitCast(libc.O{ .CLOEXEC = true })))) >= 0 and + hello(fd, kind, libc.getpid(), name(), detached_now.load(.acquire)); } /// `bytes` sent whole on a socket, never raising SIGPIPE: false when the @@ -485,6 +534,7 @@ pub fn hangUp() void { /// link closed, the reader joined. pub fn quit() void { if (link < 0) return; + quitting.store(true, .release); tell("quit", &.{}); _ = libc.shutdown(link, 2); if (reader) |r| r.join(); diff --git a/runtime/session.zig b/runtime/session.zig index 55b42b60..4172ba8d 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -24,7 +24,7 @@ //! - `sent()`: after each step's unit went to the clients. //! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs). //! - `note(n)`: what the daemon says (an adopted shell, a client's -//! connection), onto its queue. +//! connection, a new daemon's hello taken), onto its queue. //! - `watched()`: the files it watches (a Restore stops watching them). //! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it //! replaces the old one (its devices let go, what it is told of the @@ -139,8 +139,10 @@ pub fn Loop(comptime Frontend: type) type { } /// What the daemon says, onto the frontend's queue (once: its - /// reader is started by the first call). + /// reader is started by the first call); and a daemon started + /// since the last one died told the shells' masters it held. pub fn watch(l: *L) void { + if (daemon.relinked()) l.ptys.tellDaemon(); daemon.watch(l.fe, note); } diff --git a/test/daemon.py b/test/daemon.py index 31806863..d9706f04 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -4,6 +4,8 @@ private HOME and runtime directory: - a terminal's session detached (the stub ends, exit 0), then attached from another terminal N times, each a client (an attach is always one); +- the daemon killed: its sessions start the next and register again with + it, their shells too, and a client attaches (`relink`); - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - a replica's hello on the daemon's stream socket (phase 5): one of this @@ -23,6 +25,8 @@ private HOME and runtime directory: `ssh -L` forwards, say), timed python3 -B test/daemon.py --clients <pardes> the replica clients alone + python3 -B test/daemon.py --relink <pardes> + the daemon killed: its sessions register again with the next python3 -B test/daemon.py --far <pardes> the far clients and their blob cache alone, and a file by its hash python3 -B test/daemon.py --games <pardes> <lib> [seconds] @@ -606,6 +610,132 @@ def manage(binary): shutil.rmtree(root, ignore_errors=True) +def wakeups(pid, secs): + """Its threads' context switches over `secs` (Linux's /proc): none for + a process nothing wakes.""" + def count(): + n = 0 + for task in os.listdir(f'/proc/{pid}/task'): + try: + for line in open(f'/proc/{pid}/task/{task}/status'): + if line.split(':')[0] in ('voluntary_ctxt_switches', 'nonvoluntary_ctxt_switches'): + n += int(line.split()[1]) + except OSError: + pass + return n + before = count() + time.sleep(secs) + return count() - before + + +def relink(binary): + """The daemon killed outright (docs/next-run.md, "A session registering + again"): a detached session and a terminal's, each with a shell, dial + the next daemon themselves (the first to find none starts it) and + register again with their shells' masters, so `--ps` lists both and + their shells, a client attaches, and the session then killed outright + leaves its shell to an Adopt. An idle session stays idle before and + after.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rr-', 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') + + def listed(): + out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30) + return out.stdout.decode() if out.returncode == 0 else '' + + def daemons(): + return [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon'] and alive(p)] + + started = [] + terms = [] + try: + (root / 'notes.txt').write_text('notes\n') + started.append(subprocess.Popen([binary, '--detach=work', str(root / 'notes.txt')], env=env, cwd=root, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True).pid) + wait_for('the detached session\'s 9P socket', (root / 'pardes-9p-work.sock').exists) + work = Client(root / 'pardes-9p-work.sock') + session = int(dict(line.split(maxsplit=1) for line in work.read('/status').decode().splitlines())['pid']) + started.append(session) + work.write('/pane/1/exec', b'Term\n') + wait_for('its shell', lambda: terminals(work)) + shell = terminals(work)[0] + wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n') + shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=own'], env) + started.append(stub.pid) + wait_for('the terminal\'s session', (root / 'pardes-9p-own.sock').exists) + own = Client(root / 'pardes-9p-own.sock') + own_pid = int(dict(line.split(maxsplit=1) for line in own.read('/status').decode().splitlines())['pid']) + started.append(own_pid) + wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text()) + own_shell = terminals(own)[0] + own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1]) + started.append(own_shell_pid) + expected = [f'session work {session} (tty, detached)', f'session own {own_pid} (tty, has a frontend)', + f'shell {shell_pid}', f'shell {own_shell_pid}'] + assert all(row in listed() for row in expected), listed() + daemon = daemons()[0] + idle = wakeups(session, 2) if procfs else 0 + os.kill(daemon, signal.SIGKILL) + wait_for('the daemon gone', lambda: not alive(daemon)) + # Nobody runs pardes again: the sessions start the next one. + again = wait_for('a daemon again', daemons)[0] + started.append(again) + wait_for('both sessions and their shells listed again', lambda: all(row in listed() for row in expected)) + idle_after = wakeups(session, 2) if procfs else 0 + assert idle <= 2 and idle_after <= 2, ('an idle session woke', idle, idle_after) + print(f'relink: daemon {daemon} killed, {again} started by its sessions, both listed again with their shells; ' + f'the detached one idle before and after ({idle} and {idle_after} wakeups in 2 s)') + tc = Term(30, 100) + terms.append(tc) + c = tc.spawn([binary, 'attach', 'work'], env) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30) + wait_for('the client in --ps', lambda: f'client {c.pid} ' in listed()) + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + os.kill(session, signal.SIGKILL) + wait_for('the killed session gone', lambda: not alive(session)) + wait_for('its shell no session\'s', lambda: 'no session holds' in listed()) + assert alive(shell_pid), 'the new daemon held its master' + before = set(terminals(own)) + own.write(f'/pane/{min(before)}/exec', b'Adopt\n') + pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() + assert run(own, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') + exit_session(own, pane) + stub.wait(timeout=10) + own.socket.close() + work.socket.close() + wait_for('the shells hung up', lambda: not alive(shell_pid) and not alive(own_shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(again), timeout=5) + left = [p for p in processes(root) if alive(p)] + assert not left, [cmdline(p) for p in left] + print('relink: nothing left behind') + finally: + for t in terms: + try: + t.close() + except OSError: + pass + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + shutil.rmtree(root, ignore_errors=True) + + class Window: """A pardes-gui in test mode, its window offscreen and hidden, its keys written to its stdin (the test feed: Escape as `CSI 27 u`, which a @@ -1392,6 +1522,7 @@ def main(binary, cycles): far(binary) by_hash(binary) manage(binary) + relink(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) @@ -1490,7 +1621,10 @@ def main(binary, cycles): os.kill(session, signal.SIGKILL) killed = time.monotonic() wait_for('the replica client ended with its session', lambda: rc.poll() is not None, timeout=10) - assert time.monotonic() - killed < 2 and b'let this client go' in tr.text(), (time.monotonic() - killed, tr.text()[-300:]) + assert time.monotonic() - killed < 2, time.monotonic() - killed + # Its words are in its terminal before it ends, but this side's + # reader may not have them yet. + wait_for('the replica client says it was let go', lambda: b'let this client go' in tr.text()) tr.close() stub.wait(timeout=10) client.socket.close() @@ -2097,6 +2231,8 @@ if __name__ == '__main__': clients(sys.argv[2]) elif sys.argv[1:2] == ['--manage']: manage(sys.argv[2]) + elif sys.argv[1:2] == ['--relink']: + relink(sys.argv[2]) elif sys.argv[1:2] == ['--games']: games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10) elif sys.argv[1:2] == ['--far']: |
