summaryrefslogtreecommitdiff
path: root/test/daemon.py
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-20 02:21:52 -0300
committerGabriel Schneider <[email protected]>2026-11-20 04:00:32 -0300
commit1967cf64dc6d7490d386db874cf1866b764f235c (patch)
treefd11484ffcb69b6e70fe6ea9610e8fdfb8d682bf /test/daemon.py
parent969369d4b84fa1847dc3dee0e737dcd58e56c5e7 (diff)
downloadpardes-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
Diffstat (limited to 'test/daemon.py')
-rw-r--r--test/daemon.py138
1 files changed, 137 insertions, 1 deletions
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']: