summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-20 09:32:39 -0300
committerGabriel Schneider <[email protected]>2026-11-20 11:35:27 -0300
commit6ba1f5be0a838d1fda81425300ed5aca90b1f1ab (patch)
treecd923f1b5394fcfb96b5f3e9a4fe37628b944dc8
parent35b2c0efc6c43ba44640f4432d98734000f8887a (diff)
downloadpardes-6ba1f5be0a838d1fda81425300ed5aca90b1f1ab.tar.gz
pardes-6ba1f5be0a838d1fda81425300ed5aca90b1f1ab.zip
kept: a session's daemon is asked whether it keeps it by the hello's answer, however late it comes, not by a 2 s clock: kept() (runtime/daemon.zig) waited at most 2000 one-millisecond sleeps for the reader thread to take the daemon's ok, and the reader starts only after the session loop's first pass, so an Adopt (dev/host_io.zig Adoptions.ask) or a Detach asked before it, or while a busy daemon had not answered, was refused 'no pardes daemon is keeping shells for this session' with the daemon up and listing the session (14 of 40 rounds at a load of 16-37, an Adopt right after the first frame); now kept() starts the reader itself if the first frame has not (daemon.notesTo, before the session's first step, says where its notes go; watch() takes no arguments) and waits on a futex for the reader's word (up, or gone at the link's end): 0 of 40 at the same load; test/daemon.py answer_late (plain mode and --relink): an Adopt asked while the daemon is stopped 3 s, refused after 2.1 s before (3 of 3), adopted after 3 s now; the upgrade case keeps its waits for the first frame and the listing, for its new-to-old run against a build without this; tui.zig's quit path no longer starts the reader before kept; after, pinned to one CPU: 0 of 40; the five together: tui core-test 859/1014, shell-test 1055/1058, pane-test 183/184, term-test 17/17, kitty-test 45/45, behaviour-test 275/275 and --replay, process-test 0 of 144 (cmdexit once, again alone), daemon.py in every mode, both soaks diverged 0 unequal 0, gui unit-test 1651/1655 (BaselineHarnessMismatch), the frame and perf gate against tree2 PASS
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--dev/tui/tui.zig5
-rw-r--r--runtime/daemon.zig48
-rw-r--r--runtime/session.zig3
-rw-r--r--test/daemon.py87
4 files changed, 117 insertions, 26 deletions
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index bf051e9a..0157362a 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -1585,10 +1585,7 @@ const Shell = struct {
return true;
}
// The terminal went: a session the daemon keeps carries on
- // without it, to be attached again. Gone before the first
- // frame, the reader that takes the daemon's `ok` (kept
- // waits on it) is not started yet: started here.
- daemon.watch(s.loop, deliverNote);
+ // without it, to be attached again.
if (daemon.kept()) {
if (!s.detached()) s.leaveTerminal();
return true;
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index a2e890f9..9b566e60 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -290,10 +290,11 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// 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 for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// 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
@@ -306,6 +307,8 @@ var detached_now = std.atomic.Value(bool).init(false);
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
var reader: ?std.Thread = null;
+/// Where the reader hands each note (`notesTo`).
+var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null;
pub fn name() []const u8 {
return name_buf[0..name_len];
@@ -314,12 +317,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -438,11 +451,18 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// reader: the session's, before its first step.
+pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+ notes = .{ .ctx = ctx, .deliver = deliver };
+}
+
+/// Hands every note the daemon sends on (`notesTo`), on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
-pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+pub fn watch() void {
+ const n = notes orelse return;
if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+ reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null;
}
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
@@ -452,7 +472,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
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),
+ .ok => settle(.up),
.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 } });
@@ -482,12 +502,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// 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;
+ if (answer.swap(.asked, .acq_rel) != .up 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);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
diff --git a/runtime/session.zig b/runtime/session.zig
index 5d7eff78..93b72deb 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -100,6 +100,7 @@ pub fn Loop(comptime Frontend: type) type {
l.host = try fe.open(&l);
defer fe.close(&l);
+ daemon.notesTo(l.fe, note);
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
@@ -159,7 +160,7 @@ pub fn Loop(comptime Frontend: type) type {
/// 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);
+ daemon.watch();
}
fn note(ctx: *anyopaque, n: daemon.Note) void {
diff --git a/test/daemon.py b/test/daemon.py
index a8ae4331..2bc0cca6 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>
PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
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]
@@ -971,6 +972,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', 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')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ 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
@@ -1764,6 +1837,7 @@ def main(binary, cycles):
pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -2349,12 +2423,10 @@ def upgrades(old, new):
client = Client(sock)
again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
started.append(again)
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused. The
- # daemon lists it once it has taken its hello, which its `ok`
- # answers: an Adopt before that waits at most 2 s for the `ok`
- # (daemon.zig `kept`), which a loaded machine can take (3 in 40 at
- # a load of 35).
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
[str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
@@ -2486,6 +2558,7 @@ if __name__ == '__main__':
pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(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']: