#!/usr/bin/env python3 """The per-user daemon end to end (docs/next-daemon.md, phase 3), under a 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 build handed to its session, which welcomes it, sends its dump and answers its pings; another build's refused, and a session nobody has; - replica clients (`pardes --attach=:`, phase 5 part B) of a detached session, one through the delay relay: each one's keys in the session's text, every client's digest the session's once quiet, one killed outright while the other types on; - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py [cycles] python3 -B test/daemon.py --gui [cycles] (hidden windows, offscreen, and a pardes beside it for the terminal's client) python3 -B test/daemon.py --ping [n] a hello of 's build and n pings on a replica socket (one `ssh -L` forwards, say), timed python3 -B test/daemon.py --clients the replica clients alone python3 -B test/daemon.py --launch `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 --with-pair ... any mode with PARDES_PAIR set in every process it starts python3 -B test/daemon.py --attach-upgrading 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 python3 -B test/daemon.py --far the far clients and their blob cache alone, one under `yes` across a slow link, and a file by its hash python3 -B test/daemon.py --kitty-image a plain client watching a kitty image in its session's terminal python3 -B test/daemon.py --games [seconds] the games in the clients that show them, from zig build addon-test's /lib (libsnake, liblife, libliar) python3 -B test/daemon.py --window-clients window replica clients (hidden, offscreen) of a terminal's session, at 0/30/80/207 ms, and a window's session serving replicas """ import fcntl import json import os import random import re import select import shutil import signal import socket import statistics import struct import subprocess import sys import tempfile import termios import threading import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from ninep import Client # noqa: E402 # `--with-pair` before a mode: that mode as a user who exported PARDES_PAIR. WITH_PAIR = False def base_env(): """This process's environment without the caller's PARDES_* (a session of the user's) or a pager; under `--with-pair`, PARDES_PAIR set in it, as for a user who exported it: every mode run with the variable.""" env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} if WITH_PAIR: env['PARDES_PAIR'] = '1' return env def listed_as(word, kind='tty'): """How `--ps` lists a session `detached` (started so, or Detached in its own frontend) or that `has a frontend`: under the variable the first is kept (from birth, or at the Detach) and the second a pair (P36).""" if WITH_PAIR: return f'({kind}, kept)' if word == 'detached' else f'({kind})' return f'({kind}, {word})' def wait_for(what, check, timeout=10): deadline = time.monotonic() + timeout while True: got = check() if got: return got if time.monotonic() > deadline: raise TimeoutError(what) time.sleep(.01) class Term: """A terminal: a pty whose other end is read and kept, its frame requests answered (CSI 5 n), as a terminal emulator does.""" def __init__(self, rows=24, cols=80): self.master, self.slave = os.openpty() fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0)) self.out = bytearray() self.lock = threading.Lock() self.closing = False self.tail = b'' self.reader = threading.Thread(target=self.drain, daemon=True) self.reader.start() def drain(self): # Never blocked in a read when `close` comes: a master closed under a # read stays open until it returns, so the terminal would not hang # up, and its fd's number, taken again, would be read here. while not self.closing: try: if not select.select([self.master], [], [], 0.05)[0]: continue # Read and kept in one hold of the lock: `last` counts what # waits on the master under it. with self.lock: got = os.read(self.master, 65536) self.out += got except OSError: return if not got: return # A request split across two reads is answered too. seen, self.tail = self.tail + got, got[-3:] if b'\x1b[5n' in seen: try: os.write(self.master, b'\x1b[0n') except OSError: return def spawn(self, argv, env): slave = self.slave return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave, start_new_session=True, preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)) def text(self): with self.lock: return bytes(self.out) def last(self): """Its text once what was written to it is read, for a read after its writer ended (or wrote its last before an event seen elsewhere): the reader may not have the last bytes yet (it reads every 50 ms, later under load). Nothing waiting on the master and nothing more read for 0.1 s.""" quiet = None def done(): nonlocal quiet with self.lock: now = (struct.unpack('i', fcntl.ioctl(self.master, termios.FIONREAD, b'\0\0\0\0'))[0], len(self.out)) if now[0] or quiet is None or quiet[0] != now: quiet = (now, time.monotonic()) return time.monotonic() - quiet[1] >= .1 wait_for('the terminal\'s last bytes read', done) return self.text() def close(self): self.closing = True self.reader.join(timeout=2) os.close(self.slave) os.close(self.master) def run(client, serial, line): """pty/run: a line in, `exit N` and its output out.""" fid = client.open(f'/pane/{serial}/pty/run', 2) try: client.rpc(118, struct.pack(' t.rfind(b'\x1b[6 q') def agreed(path, after): """A check after the first `after` agreed; one that differed fails.""" lines = checks(path) bad = [line for line in lines if line.startswith('differ')] assert not bad, (path.name, bad) return len(lines) > after def made_live(term, check): """A key in a replica client's terminal (`gg`), stepped by its session (a check after it agreed): its view is the live one, the one /layout reads and /exec runs in, until the next input. A client asks one check at a time, and checks come on (each answer wakes its session): the first after the key may have been asked before it, the second was not.""" seen = len(checks(check)) os.write(term.master, b'gg') wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=20) def view_panes(client): """The panes the live view lays out (/layout's pane serials).""" return {int(x) for line in client.read('/layout').decode().splitlines() if line.split()[:1] != ['active'] for x in line.split()[6:]} def in_own_view(what, live, client, pane, theirs): """`live()` makes a client's view the live one (made_live, still), and /layout read after it lays out its pane and not the other client's: asked again until it does, for a view is the live one only until the next input (the session's own terminal answering a query late, the other client's rejoin sizing it). A view lost lays out neither pane, another's lays out theirs: neither ever passes.""" def own(): live() shown = view_panes(client) return pane in shown and theirs not in shown try: wait_for(what, own, timeout=30) except TimeoutError: raise AssertionError((what, pane, theirs, client.read('/layout'))) from None def clients(binary): """Replica clients of a detached session: one on the replica socket, one through the delay relay; each one's keys in the session's text and every client's digest the session's once quiet; one killed outright while the other types on; nothing left behind.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch)) env = base_env() 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(300))) started = [] terms = [] try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) nine = Client(root / 'pardes-9p-files.sock') pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') alone = fds(sess.pid) relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), str(root / 'relay.sock'), str(sock), '--delay', '40'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) started.append(relay.pid) wait_for('the relay', (root / 'relay.sock').exists) ta, tb = Term(30, 100), Term(24, 80) terms += [ta, tb] a = ta.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'a.check'))) b = tb.spawn([binary, f'--attach={root / "relay.sock"}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'b.check'))) started += [a.pid, b.pid] for t in (ta, tb): wait_for('a client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=20) os.write(ta.master, b'Ofrom-A\x1b') os.write(tb.master, b'jjofrom-B\x1b') wait_for('both clients\' keys in the session\'s text', lambda: b'from-A' in nine.read(f'/pane/{pane}/body') and b'from-B' in nine.read(f'/pane/{pane}/body')) wait_for('both clients out of insert mode', lambda: normal_again(ta) and normal_again(tb)) wait_for('client A agrees once quiet', lambda: agreed(root / 'a.check', 0)) wait_for('client B agrees once quiet', lambda: agreed(root / 'b.check', 0)) # A terminal attached by the session's name alone while a client's # view is live (its input the last): a client too, drawn. tt = Term(24, 80) terms.append(tt) stub = tt.spawn([binary, '--attach=files'], env) started.append(stub.pid) wait_for('the attached terminal\'s frame', lambda: b'line 3 of the notes' in tt.text(), timeout=20) stub.send_signal(signal.SIGHUP) stub.wait(timeout=10) # One put off the session's state (PARDES_TEST_DIVERGE, at its # 100th unit): the next unit's digest finds it, it says so in a line # and joins again for its view, a pane of its own in it, its keys # after go into that pane and it agrees. td = Term(24, 90) terms.append(td) d = td.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'd.check'), PARDES_TEST_DIVERGE='100')) started.append(d.pid) wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20) made_live(td, root / 'd.check') shown = view_panes(nine) nine.write('/exec', b'New\n') mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop() # Others' units, replayed on D's core: one after its 100th finds it. deadline = time.monotonic() + 60 while b'joined again' not in td.text(): assert time.monotonic() < deadline, 'client D diverged and joined again' os.write(ta.master, b'jk') time.sleep(.2) assert d.poll() is None made_live(td, root / 'd.check') assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout')) seen = len(checks(root / 'd.check')) os.write(td.master, b'Oafter-rejoin-D\x1b') wait_for('client D\'s keys after its rejoin', lambda: b'after-rejoin-D' in nine.read(f'/pane/{mine}/body')) wait_for('client D out of insert mode', lambda: normal_again(td)) wait_for('client D agrees after its rejoin', lambda: agreed(root / 'd.check', seen)) os.write(td.master, b' sD') wait_for('client D let go', lambda: d.poll() is not None, timeout=10) # Killed outright: the session and the other client carry on. os.kill(b.pid, signal.SIGKILL) b.wait(timeout=10) seen = len(checks(root / 'a.check')) os.write(ta.master, b'jjjAagain-A\x1b') wait_for('client A\'s keys after B went', lambda: b'again-A' in nine.read(f'/pane/{pane}/body')) wait_for('client A out of insert mode', lambda: normal_again(ta)) wait_for('client A agrees again', lambda: agreed(root / 'a.check', seen)) assert sess.poll() is None # Detach typed in it: it alone goes, and says so (exit 0). os.write(ta.master, b' sD') wait_for('client A let go', lambda: a.poll() is not None, timeout=10) assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.last(), ta.last()[-300:] # A third client, a shell: its keys wait for the session (a pty # write), its output comes back in units, the same on both sides. nine.write(f'/pane/{pane}/exec', b'Term\n') shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'term'), None)) wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body')) alone = fds(sess.pid) tc = Term(30, 100) terms.append(tc) c = tc.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check'))) started.append(c.pid) wait_for('client C\'s first frame', lambda: b'$' in tc.text(), timeout=20) said = run(nine, shell, b'echo from-the-session\n') assert said == b'exit 0\nfrom-the-session\n', said os.write(tc.master, b'echo from-C\r') wait_for('client C\'s keys in the shell', lambda: b'from-C' in nine.read(f'/pane/{shell}/body')) wait_for('client C agrees with a shell\'s output', lambda: agreed(root / 'c.check', 0)) # Its terminal hung up: it dies, and the session carries on. c.send_signal(signal.SIGHUP) c.wait(timeout=10) relay.kill() relay.wait() wait_for('the session\'s fds level', lambda: fds(sess.pid) == alone, timeout=10) print(f'daemon: two replica clients (one through a 40 ms relay) typed into a detached session; ' f'digests agreed {len(checks(root / "a.check"))} and {len(checks(root / "b.check"))} times; ' f'one put off the session\'s state joined again in its own view and agreed {len(checks(root / "d.check"))} times; ' f'one killed, the other typed on and detached; a third typed into a shell, agreed ' f'{len(checks(root / "c.check"))} times, and was hung up') exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) print('daemon: replica clients\' session ended, nothing left behind') finally: for t in terms: t.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def launch(binary): """`pardes new --detach=NAME` returns once its session is registered and listening: exit 0, the name on stdout, the session a process of its own in a session of its own, listed by `ps` and answering 9P at once; bare `--detach`, its pid is its name; a name taken is refused in words, exit 1; `pardes --detach=NAME` (no `new`) is still the session itself; nothing left behind.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch)) env = base_env() 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 / 'notes.txt').write_text('notes\n') def cli(*args, timeout=30): return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL) def status_pid(name): with Client(root / f'pardes-9p-{name}.sock') as c: return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid']) try: t0 = time.monotonic() try: out = cli('new', '--detach=work', 'notes.txt', timeout=15) except subprocess.TimeoutExpired: raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s') took = time.monotonic() - t0 assert out.returncode == 0 and out.stdout == b'work\n', out # Registered and listening when it returned: no wait here. assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir()) pid = status_pid('work') listed = cli('ps').stdout.decode() assert f'session work {pid} {listed_as('detached')}' in listed, listed assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid)) out = cli('new', '--detach') assert out.returncode == 0 and out.stdout.strip().isdigit(), out unnamed = int(out.stdout) assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} {listed_as('detached')}' in cli('ps').stdout.decode() taken = cli('new', '--detach=work') assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken # The flag alone runs the session in this process, as a supervisor # or a harness wants it. fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists) assert status_pid('fg') == fg.pid and fg.poll() is None print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening ' f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session') for name in ('work', str(unnamed), 'fg'): assert cli('kill', name).returncode == 0 fg.wait(timeout=10) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) print('launch: nothing left behind') finally: for p in processes(root): try: os.kill(p, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def pair(binary): """PARDES_PAIR: `pardes FILE` in a terminal is a session forked off for it with this terminal its first client (the last step's design, 1.1): the job the client, the terminal its own; the session its child, in a session of its own, registered (`ps`: detached, the client listed), the file drawn, keys in, the digests agreed once quiet; the session's Exit ends both. With no daemon the client killed outright ends the session (its last link). Nothing left behind.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch)) env = base_env() 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(30))) terms = [] def session_of(name): sock = root / f'pardes-9p-{name}.sock' wait_for(f'session {name}\'s 9P socket', sock.exists) nine = Client(sock) return nine, int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) try: t = Term(30, 100) terms.append(t) c = t.spawn([binary, '--9p=pair', str(notes)], dict(env, PARDES_REPLICA_CHECK=str(root / 'pair.check'))) nine, session = session_of('pair') assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid) wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30) listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() wait_for('the client listed', lambda: f'session pair {session} (tty)' in listed() and f'client {c.pid} ' in listed()) pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') os.write(t.master, b'Ofrom-the-pair\x1b') wait_for('its keys in the session\'s text', lambda: b'from-the-pair' in nine.read(f'/pane/{pane}/body')) wait_for('out of insert mode', lambda: normal_again(t)) wait_for('the client agrees once quiet', lambda: agreed(root / 'pair.check', 0)) exit_session(nine, pane) code = c.wait(timeout=60) assert code == 0 and not alive(session), (code, alive(session)) print(f'pair: client {c.pid} (the job) and session {session} (its child, setsid, listed detached with the client); ' f'drawn, typed, agreed; Exit ended both (the client exit {code})') nine.socket.close() lone = Term(24, 80) terms.append(lone) c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off')) nine2, session2 = session_of('lone') wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30) # An Upgrade refused, with why: its client could not find it again. nine2.write('/ctl', b'Upgrade\n') wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20) assert alive(session2) and c2.poll() is None nine2.socket.close() os.kill(c2.pid, signal.SIGKILL) c2.wait(timeout=10) wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind') 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_rows(binary): """PARDES_PAIR, the shell's view (the last step's design, 1.1) and a session's lifetime (2.2 B), one row a step. `ps` says a pair's session `kept` (started --detach, or a Detach typed in any client since), or nothing after its kind; an Upgrade carries which. Kept: a client ended by TERM, KILL or a closed terminal (HUP) leaves it running, as does a Detach typed in one (said, exit 0). With no daemon: a Detach refused (nothing could attach), the client on; its terminal closed, the session ends with its last link.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) env = base_env() 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(30))) terms = [] def listed(): return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() def state_of(name): """What `ps` says of session `name` after its pid: `(tty)`, `(tty, kept)`.""" for line in listed().splitlines(): if line.split()[:2] == ['session', name]: return line[line.index('('):] def drawn(t): wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) def typed_detach(t, nine, pane): # Its view the live one (it typed last), then the word. os.write(t.master, b'j') time.sleep(.3) nine.write(f'/pane/{pane}/exec', b'Detach\n') def started(name, e): t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--9p={name}', str(notes)], e) wait_for('the socket', (root / f'pardes-9p-{name}.sock').exists) nine = Client(root / f'pardes-9p-{name}.sock') session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') drawn(t) return t, c, nine, session, pane def attached(name): tt = Term(30, 100) terms.append(tt) a = tt.spawn([binary, 'attach', name], env) drawn(tt) wait_for('the client listed', lambda: f'client {a.pid} ' in listed()) return tt, a def ended_by(how, tt, a): """Client `a` on terminal `tt` ended: TERM, KILL, or HUP (its terminal closed); its exit status, once it is unlisted.""" if how == 'HUP': tt.close() terms.remove(tt) else: os.kill(a.pid, getattr(signal, 'SIG' + how)) code = a.wait(timeout=20) if how == 'TERM': wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h')) wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed()) return code def upgraded(name, nine, session): """An Upgrade to the same build: the session exec'd under its pid, its 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: sock.stat().st_ino != before, timeout=60) nine.socket.close() again = reconnect(root / f'pardes-9p-{name}.sock') assert alive(session) return again try: # Kept from birth: `new --detach`. Its clients end and it runs on. out = subprocess.run([binary, 'new', '--detach=kd', str(notes)], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) assert out.returncode == 0, out with Client(root / 'pardes-9p-kd.sock') as kn: kd = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid']) assert state_of('kd') == '(tty, kept)', listed() for how in ('HUP', 'TERM'): ended_by(how, *attached('kd')) assert alive(kd) and state_of('kd') == '(tty, kept)', (how, listed()) # Started by `new` with a file: an Upgrade keeps it (its `new` is the # verb still: taken for a file's name, the file was "the second" and # the session ended), and it is attached to after. upgraded('kd', Client(root / 'pardes-9p-kd.sock'), kd).socket.close() assert alive(kd) and state_of('kd') == '(tty, kept)', listed() ended_by('TERM', *attached('kd')) assert alive(kd) and state_of('kd') == '(tty, kept)', listed() print('pair rows: `new --detach` with a file: an Upgrade keeps it, and it is attached to after') assert subprocess.run([binary, 'kill', 'kd'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('kd ended', lambda: not alive(kd), timeout=30) print('pair rows: `new --detach` kept from birth (ps: (tty, kept)); its client ended by HUP, by TERM: it runs on') # Not kept: a client's close (its terminal closed, a TERM) ends the # session when it was the last; a KILL is a loss, it runs on. t, c, nine, session, pane = started('nk', env) # Dead of the signal, its goodbye said, as the own path's stub dies. assert ended_by('HUP', *attached('nk')) == -signal.SIGHUP assert alive(session) and state_of('nk') == '(tty)', ('not its last client', listed()) os.kill(c.pid, signal.SIGKILL) c.wait(timeout=10) wait_for('the client unlisted', lambda: f'client {c.pid} ' not in listed()) assert alive(session) and state_of('nk') == '(tty)', ('a loss', listed()) assert ended_by('TERM', *attached('nk')) == -signal.SIGTERM wait_for('the session ended at its last client\'s close', lambda: not alive(session), timeout=20) assert state_of('nk') is None, listed() nine.socket.close() print('pair rows: not kept: a client\'s terminal closed (not the last): it runs on; its own killed -9: it runs on, ' 'listed; the last client TERMed (exit 0, its terminal put back): the session ended') # The pair's own terminal closed after an Upgrade: its last client's # close, which the Upgrade did not make kept. t, c, nine, session, pane = started('nk2', env) nine = upgraded('nk2', nine, session) wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30) nine.socket.close() t.close() terms.remove(t) assert c.wait(timeout=20) == -signal.SIGHUP, c.returncode wait_for('the session ended with its terminal', lambda: not alive(session), timeout=20) print('pair rows: not kept, upgraded: its terminal closed (exit 0): the session ended') # Without the variable nothing changes: an attach client's TERM # leaves the session running, and its own terminal closed detaches it. own_env = {k: v for k, v in env.items() if k != 'PARDES_PAIR'} t, c, nine, session, pane = started('own', own_env) assert state_of('own') == '(tty, has a frontend)', listed() assert ended_by('TERM', *attached('own')) == -signal.SIGTERM assert alive(session) and state_of('own') == '(tty, has a frontend)', listed() nine.socket.close() t.close() terms.remove(t) c.wait(timeout=20) wait_for('the own session detached', lambda: state_of('own') == '(tty, detached)') assert alive(session) assert subprocess.run([binary, 'kill', 'own'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the own session ended', lambda: not alive(session), timeout=30) print('pair rows: without the variable: an attach client TERMed, the session on; its terminal closed, it detached (ps: (tty, detached))') # A pair: not kept, and not across an Upgrade either; a Detach typed # in its client keeps it, across an Upgrade too. t, c, nine, session, pane = started('rows', env) assert state_of('rows') == '(tty)', listed() nine = upgraded('rows', nine, session) wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty)') wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30) typed_detach(t, nine, pane) assert c.wait(timeout=20) == 0, c.returncode wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text()) assert alive(session) and state_of('rows') == '(tty, kept)', listed() nine = upgraded('rows', nine, session) wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty, kept)') print('pair rows: a pair (ps: (tty)), so after an Upgrade; Detach in its client: said, exit 0, it runs on, kept, so after an Upgrade') for how in ('TERM', 'KILL', 'HUP'): ended_by(how, *attached('rows')) assert alive(session) and state_of('rows') == '(tty, kept)', (how, listed()) print(f'pair rows: kept: a client ended by {how}: the session runs on') nine.socket.close() assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the session ended', lambda: not alive(session), timeout=30) t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off')) typed_detach(t, nine, pane) time.sleep(1) # Which went, if one did: the client's exit and its screen's last # words, the session's life (its stderr is /dev/null: no log). went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone] assert not went, (f'a Detach with no daemon is refused: {" and ".join(went)} went (client exit {c.poll()}, ' f'session {"alive" if alive(session) else "gone"}); the terminal\'s last bytes: {t.text()[-600:]!r}') nine.socket.close() t.close() terms.remove(t) c.wait(timeout=20) wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) print('pair rows: no daemon: a Detach refused, the client on; its terminal closed, the session ended; nothing left') 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 attach_upgrading(binary, rounds=6, dump=True): """`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 = base_env() 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) # A join whose dump is still on its way when the Upgrade comes (a # 100 MB file: the flush before the exec lets it go cut): it joins # again, as one told so does; never "let this client go". # Once a run (plain mode, --attach-upgrading): a slow round. if dump: big = root / 'big.txt' with open(big, 'w') as f: f.write('a line of a big file, long enough to be a fair line of text in a log: 0123456789\n' * 1_250_000) out = subprocess.run([binary, 'new', '--detach=big', str(big)], env=env, cwd=root, capture_output=True, timeout=60, stdin=subprocess.DEVNULL) assert out.returncode == 0, out sock = root / 'pardes-9p-big.sock' nine = Client(sock) session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) for k in range(2): t = Term(30, 100) terms.append(t) a = t.spawn([binary, 'attach', 'big'], env) listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() # noqa: E731 wait_for('the attach joined', lambda: f'client {a.pid} ' in listed() or a.poll() is not None, timeout=60) before = sock.stat().st_ino nine.write('/ctl', b'Upgrade\n') wait_for('joined again, or gone', lambda: b'joined again' in t.text() or a.poll() is not None, timeout=180) assert a.poll() is None, ('a join cut mid-dump', k, a.returncode, t.text()[-120:]) a.terminate() a.wait(timeout=20) wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60) nine.socket.close() nine = reconnect(sock) nine.socket.close() assert subprocess.run([binary, 'kill', 'big'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the big 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)' + ('; a join whose 100 MB dump the exec cut joined again, 2 of 2' if dump else '')) 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 kept_views(binary): """A view kept for its client's rejoin (views.away: a bye that says it joins again, a client cut off behind, every client at an Upgrade) is that client's for 30 s, then a join with no room takes it, in a session nobody types in: a `new --detach` session at its four views (a client attached, idle; raw replicas), two of them leaving to join again and never coming back; a join at once is refused and told for how long, one a second past that, nothing typed in between, is welcomed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) env = base_env() 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') t = Term(30, 100) rs = [] try: out = subprocess.run([binary, 'new', '--detach=kv'], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) assert out.returncode == 0, out a = t.spawn([binary, 'attach', 'kv'], env) wait_for('the client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30) sock, build = root / 'pardes-replica.sock', semantics(binary) while True: r = Replica(sock) said = r.hello('kv', build) if said[0] != 'welcome': break rs.append(r) assert said[0] == 'refused' and 'as many views' in said[1] and len(rs) >= 2, (said, len(rs)) for r in rs[:2]: r.send(0x02, b'\x01') r.close() # The goodbyes reach the session on their own connections and the # next join through the daemon, in no order between them: a join # judged before the session took them is refused with no view kept # yet. Dialled again until a refusal says one is. dials = 0 def refused(): nonlocal dials dials += 1 r = Replica(sock) said = r.hello('kv', build) r.close() assert said[0] == 'refused' and 'as many views as it takes' in said[1], said kept = re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]) return kept and (said, int(kept.group(1)), time.monotonic()) said, more, at = wait_for('a join refused, a view kept', refused) print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}" ({dials} dials)') time.sleep(max(0, at + more + 1 - time.monotonic())) said = Replica(sock).hello('kv', build) assert said[0] == 'welcome', ('a view kept past what its refusal said in an idle session, still kept', more, said) assert a.poll() is None print(f'kept views: a join {more + 1} s after, nothing typed in between, took a kept view') a.terminate() a.wait(timeout=20) assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) finally: for r in rs: r.close() for p in processes(root): try: os.kill(p, signal.SIGKILL) except OSError: pass t.close() 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 = base_env() 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 = base_env() 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 # Before the Upgrade: the exec'd client can draw before its exec is seen. mark = len(t.text()) 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 # The blink: its screen left and entered again, the notes drawn there. wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), 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 = base_env() 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) wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) # Its environment read once the new image runs (it entered the # screen): an exec names the new file in /proc/PID/exe before it has # written where the environment is, and a read between gets nothing # (two CPUs: 170 execs of 200 read so). assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True 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 = base_env() 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 listed as no one's, the other ended by name with its shell, a name no session has refused, the kept shell ended by --kill-all, and the daemon gone after it.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch)) env = base_env() 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 cli(*args): return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=30) started = [] try: sessions, shells = {}, {} for name in ('one', 'two'): (root / f'{name}.txt').write_text(f'{name}\n') started.append(subprocess.Popen([binary, f'--detach={name}', str(root / f'{name}.txt')], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True).pid) sock = root / f'pardes-9p-{name}.sock' wait_for(f'session {name}\'s 9P socket', sock.exists) with Client(sock) as c: status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines()) sessions[name] = int(status['pid']) started.append(sessions[name]) c.write('/pane/1/exec', b'Term\n') wait_for(f'session {name}\'s shell', lambda: terminals(c)) shell = terminals(c)[0] shells[name] = pid_in(c, shell) started.append(shells[name]) daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0] started.append(daemon) out = cli('--ps') assert out.returncode == 0, out listed = out.stdout.decode() assert f'pardes daemon {daemon}' in listed, listed for name in ('one', 'two'): assert f'session {name} {sessions[name]} {listed_as('detached')}' in listed, listed assert f'shell {shells[name]}' in listed, listed # The same, a record a line, in each session's /sessions. with Client(root / 'pardes-9p-one.sock') as c: records = c.read('/sessions').decode().splitlines() assert records[0] == f'daemon {daemon}', records for name in ('one', 'two'): at = records.index(f'session {sessions[name]} tty {"kept" if WITH_PAIR else "detached"} {name}') assert records[at + 1] == f'shell {shells[name]}', records print('manage: /sessions read over 9P listed the daemon, both sessions and their shells') os.kill(sessions['two'], signal.SIGKILL) wait_for('session two gone', lambda: not alive(sessions['two'])) wait_for('its shell no session\'s', lambda: 'no session holds' in cli('--ps').stdout.decode()) listed = cli('--ps').stdout.decode() assert 'session two' not in listed and listed.index(f'shell {shells["two"]}') > listed.index('no session holds'), listed assert alive(shells['two']) print('manage: --ps listed two sessions and their shells, then a killed one\'s shell as no one\'s') refused = cli('--kill=nobody') assert refused.returncode == 1 and b"no session called 'nobody'" in refused.stderr, refused killed = cli('--kill=one') assert killed.returncode == 0, killed assert not alive(sessions['one']) wait_for('session one\'s shell hung up with it', lambda: not alive(shells['one'])) assert alive(shells['two']) and 'session one' not in cli('--ps').stdout.decode() assert cli('--kill-all').returncode == 0 wait_for('the kept shell ended', lambda: not alive(shells['two'])) wait_for('the daemon gone once it keeps nothing', lambda: not alive(daemon)) none = cli('--ps') assert none.returncode == 1 and b'no pardes daemon is running' in none.stderr, none print('manage: --kill=one ended it and its shell, --kill-all the kept shell, a name nobody has refused; the daemon left') finally: for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass 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 = base_env() 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] shell_pid = pid_in(work, shell) 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 = pid_in(own, own_shell) started.append(own_shell_pid) expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("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 (pid := pid_in(own, pane)) == shell_pid, (pid, shell_pid) 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) 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 = base_env() 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 = pid_in(one, terminals(one)[0]) 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 (pid := pid_in(two, pane)) == shell_pid, (pid, shell_pid) 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 pipe's lone ESC would hold for the next key).""" def __init__(self, root, name, argv, env): (root / name).mkdir() self.err = root / f'{name}.err' self.p = subprocess.Popen(argv, env=dict(env, PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / name), SDL_VIDEO_DRIVER='offscreen'), cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=open(self.err, 'w'), start_new_session=True) self.pid = self.p.pid def keys(self, text): self.p.stdin.write(text.replace(b'\x1b', b'\x1b[27u')) self.p.stdin.flush() def mouse(self, kind, button, x, y): """A pointer event at window pixels (gui.zig's test feed).""" self.p.stdin.write(f'\x1b]777;mouse;{kind};{button};{x};{y}\x07'.encode()) self.p.stdin.flush() def said(self): return self.err.read_text(errors='replace') if self.err.exists() else '' def close(self): if self.p.poll() is None: self.p.stdin.close() self.p.wait(timeout=15) return self.p.returncode def sessions_listed(binary, env, root): """`pardes --ps`'s session lines, each `[name, pid, (kind, state)]`.""" out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30) assert out.returncode == 0, out rows = [line.split(maxsplit=3)[1:] for line in out.stdout.decode().splitlines() if line.lstrip().startswith('session ')] return [[name, pid, rest] for name, pid, rest in rows] def pdf_window(binary, gui_binary): """A PDF in a terminal's detached session (the pdf addon its prefix installs, `/lib/pardes/addons/pdf.so`), a window client attached and its wheel turned over the PDF: the session's page moves, the window's digest is the session's, and the window, which runs the addon's code itself (its state is plain: PA_PLAIN), draws its own pages from the file. Skipped when the build has no pdf.so.""" lib = Path(binary).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so' if not lib.exists(): print(f'daemon: no {lib}: the PDF window case skipped') return scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch)) env = base_env() 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') env.pop('XDG_DATA_HOME', None) (root / 'config' / 'pardes').mkdir(parents=True) (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') doc = root / 'design.pdf' shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc) notes = root / 'notes.txt' notes.write_text('notes\n') started = [] try: sess = subprocess.Popen([binary, '--detach=pdf', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-pdf.sock').exists) nine = Client(root / 'pardes-9p-pdf.sock') assert any(row.startswith(b'pdf ') for row in nine.read('/addons').splitlines()), nine.read('/addons') nine.write('/look', f'{doc}\n'.encode()) pdf = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'pdf') for row in nine.read('/index').splitlines(): if row.split()[1] == b'text': nine.write(f'/pane/{int(row.split()[0])}/ctl', b'Del\n') def page(): # A kind's prefix is its last frame's: one drawn first. nine.read('/screen') tag = nine.read(f'/pane/{pdf}/tag') return int(tag[1:tag.index(b'/')]) if tag.startswith(b'[') else 0 wait_for('the PDF at its first page', lambda: page() == 1) check = root / 'w.check' w = Window(root, 'w', [gui_binary, '--attach=' + str(sock) + ':pdf'], dict(env, PARDES_REPLICA_CHECK=str(check))) started.append(w.pid) wait_for('the window client agrees', lambda: agreed(check, 0), timeout=30) for _ in range(60): w.mouse('wheel', -3, 400, 400) time.sleep(0.02) wait_for('the session\'s PDF past its first page', lambda: page() > 1, timeout=30) n = len(checks(check)) wait_for('the window client agrees after the wheel', lambda: agreed(check, n), timeout=30) assert w.close() == 0, w.said()[-800:] print(f'daemon: a PDF in a detached session, a window client\'s wheel over it: the session at page {page()}, ' f'the window\'s digest the session\'s {len(checks(check))} times') exit_session(nine, pdf) sess.wait(timeout=60) nine.socket.close() finally: for pid in started: try: os.killpg(pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass shutil.rmtree(root, ignore_errors=True) def window_clients(binary, gui_binary): """Window replica clients (`pardes-gui --attach=:`): of a terminal's detached session, directly and through the delay relay at 30, 80 and 207 ms, beside a terminal's client, one put off the session's state that joins again, one that detaches; and a window's session served to a terminal's client and a window's. Each one's keys in the session's text, every client's digest the session's once quiet; nothing left.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch)) env = base_env() 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(300))) started = [] terms = [] windows = [] try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) nine = Client(root / 'pardes-9p-files.sock') pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') body = lambda: nine.read(f'/pane/{pane}/body') # A terminal's client beside the windows, typing as they do. ta = Term(30, 100) terms.append(ta) a = ta.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'a.check'))) started.append(a.pid) wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in ta.text(), timeout=30) agreements = [] for i, rtt in enumerate((0, 30, 80, 207)): to = sock relay = None if rtt: relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), str(root / f'relay{rtt}.sock'), str(sock), '--delay', str(rtt / 2)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) started.append(relay.pid) wait_for('the relay', (root / f'relay{rtt}.sock').exists) to = root / f'relay{rtt}.sock' check = root / f'w{rtt}.check' w = Window(root, f'w{rtt}', [gui_binary, f'--attach={to}:files'], dict(env, PARDES_REPLICA_CHECK=str(check))) windows.append(w) started.append(w.pid) seen = len(checks(root / 'a.check')) w.keys(b'jjjjjjj' * (i + 1) + f'Ofrom-window-{rtt}\x1b'.encode()) os.write(ta.master, b'jjjjOfrom-terminal-%d\x1b' % rtt) wait_for(f'the window\'s and the terminal\'s keys ({rtt} ms)', lambda: f'from-window-{rtt}'.encode() in body() and b'from-terminal-%d' % rtt in body(), timeout=30) wait_for('the terminal client normal again', lambda: normal_again(ta), timeout=20) wait_for(f'the window client agrees ({rtt} ms)', lambda: agreed(check, 0), timeout=30) wait_for('the terminal client agrees', lambda: agreed(root / 'a.check', seen), timeout=30) if not rtt: # Its clients are no sessions of the daemon's. listed = sessions_listed(binary, env, root) assert [(n, k) for n, _, k in listed] == [('files', listed_as('detached'))], listed # Moved and scrolled, its own view only: agreed again. n = len(checks(check)) w.keys(b'jjjjjkkk\x06\x06\x02') wait_for(f'the window client agrees again ({rtt} ms)', lambda: agreed(check, n), timeout=30) if rtt in (0, 207): # The pointer over the tags (the workspace's, the column's, # the pane's: the top rows, a test window's cells about 16 by # 33 pixels) and over the body, a click there: a window's # hits are its own frame's, which the session never draws, # so they are its input's, not re-made from a frame. Each # tag motion made it join again (the user's, 2026-10-30). n = len(checks(check)) for y in range(5, 170, 11): for x in range(4, 1280, 23): w.mouse('motion', 0, x, y) for k in range(40): w.mouse('motion', 0, 100 + 25 * k, 200 + 9 * k) w.mouse('down', 1, 400, 300) w.mouse('motion', 1, 600, 360) w.mouse('up', 1, 600, 360) wait_for(f'the window client agrees after its pointer ({rtt} ms)', lambda: agreed(check, n), timeout=30) assert 'joined again' not in w.said(), w.said()[-800:] agreements.append(len(checks(check))) assert w.close() == 0, w.said()[-800:] if relay: relay.kill() relay.wait() # One put off the session's state (PARDES_TEST_DIVERGE): the next # unit it replays finds it, it joins again, and its keys after go in. # Far (PARDES_REPLICA_FAR, as through ssh): its first join sent its # blobs by hash, in zstd; its rejoin finds them in the core it left. dcheck = root / 'wd.check' wd = Window(root, 'wd', [gui_binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(dcheck), PARDES_TEST_DIVERGE='1', PARDES_REPLICA_FAR='1', PARDES_REPLICA_STATS=str(root / 'wd.stats'), XDG_CACHE_HOME=str(root / 'wd-cache'))) windows.append(wd) started.append(wd.pid) time.sleep(2) wd.keys(b'jj') time.sleep(.5) os.write(ta.master, b'jj') wait_for('the window client diverged and joined again', lambda: 'joined again' in wd.said(), timeout=30) assert wd.p.poll() is None seen = len(checks(dcheck)) wd.keys(b'Oafter-rejoin-W\x1b') wait_for('the window\'s keys after its rejoin', lambda: b'after-rejoin-W' in body(), timeout=30) wait_for('the window client agrees after its rejoin', lambda: agreed(dcheck, seen), timeout=30) # An Upgrade (to the same build): the session lets it go in words # (`refused`), it dials again, joins, and its keys after go in. nine.write('/ctl', b'Upgrade\n') wait_for('the window client joined again after the upgrade', lambda: 'joined again: the session is upgrading' in wd.said(), timeout=60) nine.socket.close() nine = reconnect(root / 'pardes-9p-files.sock') seen = len(checks(dcheck)) wd.keys(b'jjjOafter-upgrade-W\x1b') wait_for('the window\'s keys after the upgrade', lambda: b'after-upgrade-W' in body(), timeout=30) wait_for('the window client agrees after the upgrade', lambda: agreed(dcheck, seen), timeout=30) assert wd.p.poll() is None # Detach typed in it: it alone goes, and says so (exit 0). wd.keys(b' sD') wait_for('the window client let go', lambda: wd.p.poll() is not None, timeout=15) assert wd.p.returncode == 0 and "detached from 'files', which is still running" in wd.said(), wd.said()[-500:] # A link a line: the first join sent every blob, its rejoins held them. links = joins(root / 'wd.stats') assert len(links) == 3 and links[0]['blobs'] > 0 and links[0]['from_memory'] + links[0]['from_disk'] == 0, links assert links[1]['from_memory'] == links[1]['blobs'] and links[1]['sent_kb'] == 0, links os.write(ta.master, b' sD') wait_for('the terminal client let go', lambda: a.poll() is not None, timeout=10) print(f'daemon: window clients of a terminal\'s session at 0/30/80/207 ms beside a terminal\'s, digests agreed ' f'{agreements} and {len(checks(root / "a.check"))} times; one put off the session\'s state joined again, ' f'joined again across an Upgrade, agreed {len(checks(dcheck))} times and detached (far: its joins {joins(root / "wd.stats")})') exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() # A window's session (its daemon on, as a desktop's is), served to a # terminal's client and a window's, the window typing as they do. win = Window(root, 'win', [gui_binary, '--9p=win', str(notes)], dict(env, PARDES_DAEMON='on')) windows.append(win) started.append(win.pid) wait_for('the window session\'s 9P socket', (root / 'pardes-9p-win.sock').exists, timeout=30) wait_for('the replica socket', sock.exists) nine = Client(root / 'pardes-9p-win.sock') pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') tb = Term(30, 100) terms.append(tb) b = tb.spawn([binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'b.check'))) started.append(b.pid) wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tb.text(), timeout=30) wg = Window(root, 'wg', [gui_binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'g.check'))) windows.append(wg) started.append(wg.pid) time.sleep(2) os.write(tb.master, b'jjjOfrom-T\x1b') wg.keys(b'jjjjjjOfrom-G\x1b') win.keys(b'jjjjjjjjjOfrom-W\x1b') wait_for('everyone\'s keys in the window\'s session', lambda: all(x in body() for x in (b'from-T', b'from-G', b'from-W')), timeout=30) wait_for('the terminal client normal again', lambda: normal_again(tb), timeout=20) for k in range(3): nb, ng = len(checks(root / 'b.check')), len(checks(root / 'g.check')) os.write(tb.master, b'jk') wg.keys(b'kj') win.keys(b'jj') wait_for('the terminal client agrees with the window', lambda: agreed(root / 'b.check', nb), timeout=30) wait_for('the window client agrees with the window', lambda: agreed(root / 'g.check', ng), timeout=30) listed = sessions_listed(binary, env, root) assert [(n, k) for n, _, k in listed] == [('win', listed_as('has a frontend', 'gui'))], listed assert wg.close() == 0, wg.said()[-800:] os.write(tb.master, b' sD') wait_for('the terminal client let go', lambda: b.poll() is not None, timeout=10) assert win.p.poll() is None print(f'daemon: a window\'s session served a terminal\'s client and a window\'s, digests agreed ' f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, {listed_as("has a frontend", "gui")}') win.close() nine.socket.close() # Under the variable the window is its session's client, and the # terminal client's Detach kept that session (P36): ended by name. if WITH_PAIR: subprocess.run([binary, '--kill=win'], env=dict(env, PARDES_DAEMON='on'), cwd=root, capture_output=True, timeout=30) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=15) print('daemon: window clients\' sessions ended, nothing left behind') finally: for t in terms: t.close() for w in windows: if w.p.poll() is None: w.p.kill() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def joins(path): """A replica client's joins (PARDES_REPLICA_STATS, a line a link): how many blobs each listed, how many it held already from the core it left and from disk, and the KB it was sent.""" out = [] for line in checks(path): words = line.split() if 'blobs' not in words: continue got = {words[i]: int(words[i + 1]) for i in range(0, len(words) - 1, 2) if words[i + 1].isdigit()} out.append(got) return out def cache_file(cache): """The blob cache (a far client's, XDG_CACHE_HOME/pardes/cache.xitdb).""" return cache / 'pardes' / 'cache.xitdb' def cached(cache): """The blob cache's size in bytes, 0 with none.""" f = cache_file(cache) return f.stat().st_size if f.exists() else 0 def far(binary): """Far replica clients (PARDES_REPLICA_FAR, as through ssh) of a detached session and their blob cache: the first one is sent every blob and keeps them; a second on the same machine, and one put off the session's state that joins again, are sent none they hold, from disk and from the core they leave; one started after the first ended gets what it made from disk; one after the cache was cut short by hand (a file that is no database: started afresh), and one with the cache full, are sent what they lack. Every client's digest is the session's once quiet.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch)) cache = root / 'cache' env = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='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))) big = root / 'big.txt' big.write_text(''.join(f'{i:06d} the quick brown fox jumps over the lazy dog {i * 7919 % 10007}\n' for i in range(20000))) started = [] terms = [] def client(name, extra=None): t = Term(24, 90) terms.append(t) c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats'), **(extra or {}))) started.append(c.pid) wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) # Its frame's request answered before a key goes: an answer behind # an Esc, in one read, is taken as Alt with it. time.sleep(.3) return t, c def texts(): return b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines() if row.split()[1] == b'text') def typed(name, t, words): seen = len(checks(root / f'{name}.check')) os.write(t.master, b'O' + words) wait_for(f'client {name}\'s keys in the session\'s text', lambda: words in texts()) time.sleep(.2) os.write(t.master, b'\x1b') wait_for(f'client {name} out of insert mode', lambda: normal_again(t)) wait_for(f'client {name} agrees once quiet', lambda: agreed(root / f'{name}.check', seen)) def detach(name, t, c): os.write(t.master, b' sD') wait_for(f'client {name} let go', lambda: c.poll() is not None, timeout=20) try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) wait_for('the replica socket', (root / 'pardes-replica.sock').exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) nine = Client(root / 'pardes-9p-files.sock') pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') nine.write(f'/pane/{pane}/exec', f'Look {big}\n'.encode()) nine.write(f'/pane/{pane}/exec', b'Edit 3a/ an edit the session made /\n') # A: the first, its cache empty: every blob sent, and kept. ta, a = client('a') typed('a', ta, b'from-A') # The notes and the big file, a megabyte and more between them. wait_for('client A\'s blobs on disk', lambda: cached(cache) > 1 << 20) time.sleep(.5) # B: a second client on this machine, and put off the session's # state once quiet: its first join from disk, its rejoin from the # core it left. tb, b = client('b', {'PARDES_TEST_DIVERGE': '1'}) os.write(tb.master, b'jj') time.sleep(.5) os.write(ta.master, b'jj') wait_for('client B diverged and joined again', lambda: b'joined again' in tb.text(), timeout=30) typed('b', tb, b'from-B') typed('a', ta, b'again-A') detach('b', tb, b) detach('a', ta, a) a_joins, b_joins = joins(root / 'a.stats'), joins(root / 'b.stats') assert len(a_joins) == 1 and len(b_joins) == 2, (a_joins, b_joins) assert a_joins[0]['from_disk'] == 0 and a_joins[0]['from_memory'] == 0 and a_joins[0]['sent_kb'] > 100, a_joins assert b_joins[0]['from_disk'] >= b_joins[0]['blobs'] - 2 and b_joins[0]['sent_kb'] < a_joins[0]['sent_kb'], b_joins assert b_joins[1]['from_memory'] >= b_joins[1]['blobs'] - 1 and b_joins[1]['sent_kb'] < 64, b_joins # C: a client started again after them: what they made since they # joined is on disk too (Have.keep at their end). tc, c = client('c') typed('c', tc, b'from-C') detach('c', tc, c) c_join = joins(root / 'c.stats')[0] assert c_join['from_disk'] >= c_join['blobs'] - 1 and c_join['sent_kb'] < 64, c_join # D: the cache cut short by hand: no database, started afresh, every # blob sent again. whole = cache_file(cache).read_bytes() cache_file(cache).write_bytes(whole[:len(whole) // 2]) td, d = client('d') typed('d', td, b'from-D') detach('d', td, d) d_join = joins(root / 'd.stats')[0] assert d_join['from_disk'] == 0 and d_join['sent_kb'] > 100, d_join # E: the cache full (D's, past a 1 MiB cap): the oldest go at its end, # the file compacted, under its cap but for xitdb's own few KB. before_e = cached(cache) assert before_e > 1 << 20, before_e te, e = client('e', {'PARDES_BLOB_CACHE_MB': '1'}) typed('e', te, b'from-E') detach('e', te, e) assert cached(cache) <= (1 << 20) + (64 << 10), cached(cache) tf, f = client('f', {'PARDES_BLOB_CACHE_MB': '1'}) typed('f', tf, b'from-F') detach('f', tf, f) f_join = joins(root / 'f.stats')[0] assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache)) far_joins(root / 'pardes-replica.sock', 'files', binary, 200) # Through ssh (a stand-in forwarding as `ssh -L` does, its socket # bound 0.5 s before it listens: the client dials until it answers): # a client refused and one detached each end their ssh and its # socket (one refused left both, 2026-10-30). fake = root / 'ssh' fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n' f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n') fake.chmod(0o755) senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root)) def forwarded(): return [q for q in processes(root) if alive(q) and any(b'pardes-ssh-' in a for a in cmdline(q))] or list(root.glob('pardes-ssh-*')) for name in ('nobody', 'files'): ts = Term(24, 90) terms.append(ts) sc = ts.spawn([binary, f'--attach=box:{name}'], senv) started.append(sc.pid) if name == 'files': wait_for('the client through ssh\'s first frame', lambda: b'line 3 of the notes' in ts.text(), timeout=30) time.sleep(.3) os.write(ts.master, b' sD') wait_for(f'the client through ssh ends ({name})', lambda: sc.poll() is not None, timeout=30) # Its words are read off its terminal by a thread of the Term's: # the process can be gone before they are in `text()`. if name == 'nobody': wait_for('the refusal said through ssh', lambda: b"no session called 'nobody'" in ts.text(), timeout=5) wait_for(f'its ssh and socket gone ({name})', lambda: not forwarded(), timeout=10) body = texts() for words in (b'from-A', b'from-B', b'again-A', b'from-C', b'from-D', b'from-E', b'from-F'): assert words in body, words print('daemon: far clients: the first sent {} KB; a second from disk ({} of {} blobs), its rejoin from memory ' '({} of {}); one started again from disk ({} of {}); after the cache was spoilt by hand sent {} KB; with ' 'the cache full it stayed under its cap; every digest agreed ({} checks)'.format( a_joins[0]['sent_kb'], b_joins[0]['from_disk'], b_joins[0]['blobs'], b_joins[1]['from_memory'], b_joins[1]['blobs'], c_join['from_disk'], c_join['blobs'], d_join['sent_kb'], sum(len(checks(root / f'{n}.check')) for n in 'abcdef'))) exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) finally: for t in terms: t.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def far_flood(binary): """A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py: 200 ms each way, 20 KB/s) while the session's shell runs `yes`. Its terminal is the pty's bytes in the session's units, so the flood queues for it: it falls behind, past replica.behind_max_ms its link is let go (`Link.lags`), and it joins again from a dump, saying so on its notice line ("joined again: N s behind") until a key. Once `yes` ends it agrees with the session, and its keys after go in. The shape is asserted, not the times: a link ended before its last (a line of PARDES_REPLICA_STATS a link), the notice, the agreement.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch)) env = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), 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(300))) started = [] terms = [] try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) nine = Client(root / 'pardes-9p-files.sock') pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') nine.write(f'/pane/{pane}/exec', b'Term\n') shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'term'), None)) wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body')) relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), str(root / 'relay.sock'), str(sock), '--delay', '200', '--rate', '0.02'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) started.append(relay.pid) wait_for('the relay', (root / 'relay.sock').exists) check = root / 'f.check' stats = root / 'f.stats' t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'], dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) # Queued behind the flood, let go for its lag, joined again from a # dump: a link of its ended (its stats line), and its notice says why. assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) seen = len(checks(check)) wait_for('the far client agrees after its keys', lambda: agreed(check, seen), timeout=60) # Its keys go to the shell: its terminal hangs up instead. c.send_signal(signal.SIGHUP) c.wait(timeout=10) print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` was let go for its lag and ' f'joined again ({len(joins(stats))} links), agreed once it ended ({len(checks(check))} checks) and its keys went in') relay.kill() relay.wait() exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) except BaseException: # Its evidence kept, the root going: the far client's checks and # stats, its terminal, and where each process's threads wait. kept = Path(tempfile.mkdtemp(prefix='fl-kept-', dir=scratch)) for f in ('f.check', 'f.stats'): if (root / f).exists(): shutil.copy(root / f, kept) for i, term in enumerate(terms): (kept / f'term-{i}.out').write_bytes(term.text()) with open(kept / 'threads', 'w') as out: for pid in started: out.write(f'{pid} {cmdline(pid)[:3]} alive={alive(pid)}\n') for task in sorted(Path(f'/proc/{pid}/task').glob('*')) if procfs and alive(pid) else []: try: out.write(f' {task.name} {(task / "comm").read_text().strip()} {(task / "wchan").read_text()}\n') except OSError: pass print(f'far flood: kept {kept}', file=sys.stderr) raise finally: for term in terms: term.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def by_hash(binary): """A file over the wire's 16 MiB bound opened while clients are attached (its read was one unit, dropped: the client joined again, a Debug session panicked): it goes by its hash, a client on this machine reading it itself and a far one sent it once, kept on disk; a far client that joins after is sent nothing of it.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch)) cache = root / 'cache' env = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(cache), 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(300))) big = root / 'big.txt' with open(big, 'wb') as f: for i in range(17 << 14): f.write(b'%08d %s\n' % (i, os.urandom(27).hex().encode()[:54])) started, terms = [], [] def client(name, far): t = Term(24, 90) terms.append(t) c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats'), **({'PARDES_REPLICA_FAR': '1'} if far else {}))) started.append(c.pid) wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) time.sleep(.3) return t, c def read(pid): return next(int(line.split()[1]) for line in open(f'/proc/{pid}/io') if line.startswith('rchar')) try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) wait_for('the replica socket', (root / 'pardes-replica.sock').exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) # Each reply waited for as long as the opens it answers take: the # 17 MiB file's Look took 1.6-6.6 s in a Debug build at a load of # 35 (ninep.py's 5 s is a reply's whole wait). nine = Client(root / 'pardes-9p-files.sock', timeout=60) pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') (ta, a), (tf, f) = client('a', False), client('f', True) seen = {n: len(checks(root / f'{n}.check')) for n in 'af'} was = {c.pid: read(c.pid) for c in (a, f)} nine.write(f'/pane/{pane}/exec', f'Look {big}\n'.encode()) for n in 'af': wait_for(f'client {n} agrees with the big file open', lambda: agreed(root / f'{n}.check', seen[n] + 1), timeout=60) assert sess.poll() is None and a.poll() is None and f.poll() is None assert not any(b'joined again' in t.text() for t in (ta, tf)) size = big.stat().st_size # This machine's read it from disk; the far one was sent it, zstd. got = {c.pid: read(c.pid) - was[c.pid] for c in (a, f)} assert size <= got[a.pid] < size + (512 << 10), (size, got) assert got[f.pid] < size, (size, got) tg, g = client('g', True) os.write(tg.master, b' sD') wait_for('client G let go', lambda: g.poll() is not None, timeout=20) g_join = joins(root / 'g.stats')[0] assert g_join['from_disk'] == g_join['blobs'] and g_join['sent_kb'] == 0, g_join print(f'daemon: a {size >> 20} MiB file opened under two clients went by its hash: the one on this machine read ' f'it itself, the far one was sent {got[f.pid] >> 10} KB and kept it; a far client that joined after was ' f'sent none of its {g_join["blobs"]} blobs') for t, c in ((ta, a), (tf, f)): os.write(t.master, b' sD') wait_for('a client let go', lambda: c.poll() is not None, timeout=20) exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() finally: for t in terms: t.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def games(binary, libs, secs=10): """The games (PA_PLAIN kinds: snake, life) run in the clients that show them, from `libs` (zig build addon-test's /lib): a client's keys into one apply at once (none stopped), the snake steps under a client's focus, and snake and life focused in two clients while a third types text agree with the session throughout, rollbacks and all. Then a kind that breaks its promise (test/liar.zig, its tick reads the clock): its client finds it, joins again once, says why, and agrees from then on.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch)) env = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), 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 / 'data' / 'pardes' / 'addons').mkdir(parents=True) for name in ('snake', 'life', 'liar'): shutil.copy(Path(libs) / f'lib{name}.so', root / 'data' / 'pardes' / 'addons' / f'{name}.so') notes = root / 'notes.txt' notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) started, terms = [], [] def client(name): t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats'))) started.append(c.pid) # Its frame: the notes, or what the third client typed into them. wait_for(f'client {name}\'s first frame', lambda: b'of the notes' in t.text() or b'typed by c' in t.text(), timeout=30) time.sleep(.3) return t, c def kind_pane(word): return next((int(r.split()[0]) for r in nine.read('/index').splitlines() if r.split()[1] == word), None) def steps(pane): return int(re.search(rb'steps (\d+)', nine.read(f'/pane/{pane}/body')).group(1)) def opened(t, word): # In this client's view: its key the last input, the session's # live view is its own when the word runs. os.write(t.master, b'j') time.sleep(.5) nine.write(f'/pane/{text}/exec', word.capitalize() + b'\n') return wait_for(f'a {word} pane', lambda: kind_pane(word)) def leave(name, t, c): c.send_signal(signal.SIGHUP) c.wait(timeout=20) line = (root / f'{name}.stats').read_text().split() got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)} assert not [l for l in checks(root / f'{name}.check') if l.startswith('differ')], name return got try: sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) wait_for('the replica socket', (root / 'pardes-replica.sock').exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) nine = Client(root / 'pardes-9p-files.sock') text = kind_pane(b'text') (tc, c), (ta, a) = client('c'), client('a') snake = opened(ta, b'snake') tb, b = client('b') life = opened(tb, b'life') os.write(ta.master, b'r') time.sleep(.3) s0 = steps(snake) time.sleep(.6) assert steps(snake) > s0, 'the snake steps under a client\'s focus' rnd = random.Random(7) end, n = time.monotonic() + secs, 0 while time.monotonic() < end: os.write(ta.master, bytes([rnd.choice(b'hjkl')]) if n % 40 else b'r') os.write(tb.master, bytes([rnd.choice(b'hjkl ')])) os.write(tc.master, b'Atyped by c %d\x1b' % n) n += 1 time.sleep(rnd.uniform(.02, .12)) for name in 'abc': wait_for(f'client {name} agrees once quiet', lambda: agreed(root / f'{name}.check', 0), timeout=30) assert not any(b'joined again' in t.text() for t in (ta, tb, tc)) got = {name: leave(name, t, cl) for name, t, cl in (('a', ta, a), ('b', tb, b), ('c', tc, c))} for name in 'ab': assert got[name]['stopped'] == '0' and got[name]['mispredicted'] == '0', (name, got[name]) # The liar: caught at a tick, its client joined again once, and agrees. td, d = client('d') opened(td, b'liar') wait_for('client D caught the liar', lambda: b'joined again' in td.text(), timeout=30) assert b'liar: its state after tick' in td.text(), td.text()[-600:] seen = len(checks(root / 'd.check')) os.write(td.master, b'j') wait_for('client D agrees after it', lambda: agreed(root / 'd.check', seen), timeout=30) assert td.text().count(b'joined again') == 1 and d.poll() is None print(f'daemon: games in clients, {secs:.0f} s: snake and life focused in two clients, keys stopped {got["a"]["stopped"]} and ' f'{got["b"]["stopped"]} of {got["a"]["inputs"]} and {got["b"]["inputs"]}, rollbacks {got["a"]["foreign"]}, {got["b"]["foreign"]}, ' f'{got["c"]["foreign"]} (the third typing text), every digest agreed; a kind whose tick reads the clock was caught and its ' f'client joined again once') exit_session(nine, text) sess.wait(timeout=60) nine.socket.close() finally: for t in terms: t.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def far_find(binary): """A far client types a query into a Find over 40,000 names: each key scores the names again a slice at a time (core/Names.zig `rescore`), the client's guess of the key first. The slice is a count, the same on both sides, so no guess is wrong (a slice the clock ended was the client's clock's verdict, which the session's own contradicted).""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) env = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') (root / 'config' / 'pardes').mkdir(parents=True) (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') tree = root / 'tree' for d in range(200): (tree / f'module_{d}').mkdir(parents=True) for f in range(200): (tree / f'module_{d}' / f'replica_{f}.zig').touch() notes = tree / 'notes.txt' notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) started, terms = [], [] try: sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) wait_for('the replica socket', (root / 'pardes-replica.sock').exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists) nine = Client(root / 'pardes-9p-find.sock') text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'], dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats'))) started.append(c.pid) wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) time.sleep(.3) # SPC f f: the Find, typed into, its names walked on the session's worker. os.write(t.master, b' ff') time.sleep(3) wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60) query = b'module_19/replica_3' for ch in query: os.write(t.master, bytes([ch])) time.sleep(.15) seen = len(checks(root / 'q.check')) wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60) c.send_signal(signal.SIGHUP) c.wait(timeout=20) line = (root / 'q.stats').read_text().split() got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)} print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs ' f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once') assert got['mispredicted'] == '0', got exit_session(nine, text) sess.wait(timeout=60) nine.socket.close() finally: for term in terms: term.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def restore_client(binary): """A Restore while a client is attached: the client is told and joins the restored session again by itself (P44, as at an Upgrade), saying nothing on its screen; its keys reach the replacement core (the session's: its tape adopts it, its options keep none) and it agrees with it, as does a client attached after. A 9P connection is the old core's: cut, dialled again.""" 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 = base_env() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), 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(300))) started, terms = [], [] try: sess = subprocess.Popen([binary, '--detach=back', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) wait_for('the replica socket', (root / 'pardes-replica.sock').exists) wait_for('the session\'s 9P socket', (root / 'pardes-9p-back.sock').exists) nine = Client(root / 'pardes-9p-back.sock') text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') def client(name): t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'], dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'))) started.append(c.pid) wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) time.sleep(.3) return t, c ta, ca = client('a') nine.write(f'/pane/{text}/exec', b'Dump\n') nine.write(f'/pane/{text}/exec', b'Restore\n') def cut(): try: nine.read('/index') return False except (OSError, EOFError): return True wait_for('the 9P connection cut at the Restore', cut, timeout=30) nine.socket.close() nine = reconnect(root / 'pardes-9p-back.sock') text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines() if row.split()[1] == b'text') # Client a, joined again by itself: its keys in the restored core. os.write(ta.master, b'Oa after the restore\x1b') wait_for('client a\'s keys in the restored session', lambda: b'a after the restore' in texts(), timeout=30) assert ca.poll() is None, 'client a ended at the Restore' seen = len(checks(root / 'a.check')) wait_for('client a agrees once quiet', lambda: agreed(root / 'a.check', seen), timeout=60) assert b'joined again' not in ta.text(), ('a notice left on client a\'s screen', ta.text()) tr, cr = client('r') os.write(tr.master, b'Or after the restore\x1b') wait_for('client r\'s keys in the restored session', lambda: b'r after the restore' in texts(), timeout=30) seen = len(checks(root / 'r.check')) wait_for('client r agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60) assert ca.poll() is None and cr.poll() is None, 'a client ended' print(f'daemon: a Restore with a client attached: it joined again by itself, saying nothing, its keys in the restored session and agreeing ({len(checks(root / "a.check"))} checks); the 9P connection cut; one attached after agreed ({len(checks(root / "r.check"))} checks)') exit_session(nine, text) sess.wait(timeout=60) nine.socket.close() finally: for term in terms: term.close() for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def far_joins(sock, session, binary, n): """`n` far joins of one session in a row, each read whole (its blobs asked for by none, its zstd frames unpacked) and answering a ping, then gone: the session's fds and threads as they were, its RSS within a bound. Each join made zstd contexts through the C heap, whose release builds named a new allocator at every malloc and aborted at the 65th (the box's session, after 15 far joins, 2026-10-30).""" from compression import zstd build = semantics(binary) def join(): r = Replica(sock, timeout=30) name = session.encode() r.send(0x01, struct.pack('= 5: t, m = struct.unpack_from(' 2000, timeout=30) 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, 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() term.close() wait_for('the killed session gone', lambda: not alive(session)) time.sleep(.3) assert alive(shell_pid), 'a killed session\'s shell is not hung up' assert alive(daemon) # Started from a shell, which leads the terminal's session and # outlives the stub, as a terminal's shell does (on FreeBSD the # leader's exit revokes the terminal for every process). term = Term() stub_pid = root / 'stub.pid' shell = term.spawn(['sh', '-c', '"$@" & echo $! > "$0"; wait; exec sleep 600', str(stub_pid), binary, '--tty', '--9p=fresh'], env) started.append(shell.pid) sock = root / 'pardes-9p-fresh.sock' wait_for('the second session', sock.exists) stub = int(stub_pid.read_text()) started.append(stub) client = Client(sock) status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) session = int(status['pid']) started.append(session) # Its stub killed outright, the terminal left open: the session # (the stub's child) takes that as the terminal's end and detaches. wait_for('the second session\'s first frame', lambda: b'\x1b[?1049h' in term.text()) drawn = len(term.text()) os.kill(stub, signal.SIGKILL) wait_for('the stub gone', lambda: not alive(stub)) wait_for('the session detached from its killed stub', lambda: sized(client)) assert b'\x1b[?1049l' in term.last()[drawn:], 'the terminal is put back' assert alive(session) shell.kill() shell.wait(timeout=10) term.close() before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid) print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') # Attached again: a client. (After the runs: a pty/run under a # client puts it off the session's state, and it joins again; one # that tries as the session ends says it could not.) term = Term() stub = term.spawn([binary, 'attach', 'fresh'], env) started.append(stub.pid) wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text()) listed = wait_for('the client in --ps', lambda: (lambda out: f'client {stub.pid} ' in out and out)( subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())) # (Under the variable the killed stub was the pair's client: a loss, # the session still a pair's, P36.) assert f'session fresh {session} {"(tty)" if WITH_PAIR else listed_as("detached")}' in listed, listed print('daemon: a session whose stub was killed outright detached, and was attached again, as a client') # The end: the session quits, its shells hang up, its client and # the daemon go. exit_session(client, pane) assert stub.wait(timeout=10) == 0, stub.returncode assert b'let this client go' not in term.last(), term.last()[-300:] client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5) left = [p for p in processes(root) if alive(p)] assert not left, [cmdline(p) for p in left] sockets = [p.name for p in root.iterdir() if p.is_socket()] assert not sockets, sockets print('daemon: nothing left behind') finally: for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def sized(client): """Whether the session takes a `size`: only with no window or terminal.""" try: client.write('/ctl', b'size 100 30\n') return True except OSError: return False def gui(binary, cycles): """A window's Detach closes it and keeps the process, detached for good: `pardes-gui attach` is a window client of it, a process of its own, and so is a terminal's `pardes attach`. Test mode: hidden windows, offscreen, the session's stdin the test feed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch)) env = base_env() (root / 'caps').mkdir() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'), SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on', TERM='xterm-256color') (root / 'config' / 'pardes').mkdir(parents=True) (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') feed_r, feed_w = os.pipe() proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) os.close(feed_r) def listed(): return subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() try: sock = root / 'pardes-9p-win.sock' wait_for('the window session', sock.exists, timeout=20) client = Client(sock) shell = terminals(client)[0] # The window's own process, or under the variable its child (a # pair: the window a client of it). session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) assert not sized(client), 'a window owns the size' # With its window: another window is a client of the session (its # own process, its captures its own), listed by --ps; closed, it # ends alone. second = Window(root, 'second', [binary, '--attach=win'], env) wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20) assert f'client {second.pid} ' in listed(), listed() second.close() # (a pair's own window is a client too: the second's pid is what goes) wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in listed()) assert not sized(client), 'the first window stays' assert alive(session) print('daemon: a second window on a window session a client of it (in --ps), closed alone') # Detached: the window closed, the process on; every attach after it # a window client, the session detached still. client.write(f'/pane/{shell}/exec', b'Detach\n') wait_for('the window closed', lambda: sized(client)) assert alive(session), 'the session carries on with no window' assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed() baseline = None for cycle in range(cycles): w = Window(root, f'w{cycle}', [binary, 'attach'] if cycle % 2 else [binary, '--attach=win'], env) wait_for('the client window drawn', lambda: (root / f'w{cycle}' / 'latest.ppm').exists(), timeout=20) wait_for('the client in --ps', lambda: f'client {w.pid} ' in listed()) assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed() now = (fds(proc.pid), len(processes(root))) baseline = baseline or now assert now == baseline, (cycle, now, baseline) w.close() wait_for('the client gone from --ps', lambda: 'client ' not in listed()) print(f'daemon: a window Detach, then {cycles} window attaches as clients, fds/processes level: {baseline}') # A terminal's client of the window's session, by its name alone. A # name nobody has is refused in words. term = Term() tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), 'attach', 'win'], env) wait_for('the window session drawn in the terminal', lambda: b'\x1b[?1049h' in term.text()) time.sleep(1) assert tty_attach.poll() is None, term.text()[-400:] tty_attach.terminate() tty_attach.wait(timeout=10) term.close() assert alive(session) print('daemon: a terminal attached to a window session by name, as a client') nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10, stdout=subprocess.PIPE, stderr=subprocess.PIPE) assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr # Detached and told to end: it ends. client.write(f'/pane/{shell}/exec', b'Exit\n') wait_for('the session ended', lambda: not alive(session)) client.socket.close() wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5) print('daemon: window session ended, nothing left behind') finally: os.close(feed_w) for pid in [proc.pid] + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def gui_pair(gui_binary): """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui FILE` is a window client and a session with no SDL, the `pardes` beside it exec'd in a child (a window's session needs SDL for its wake, a terminal's binary none): the session the window's child, in a session of its own, listed detached with the window its client; the file in the window's first frame, keys in. The window's close ends the session, its last client (a CLOSE); the window killed leaves it running (a LOSS), and with no daemon the session ends with its last link. Test mode: hidden windows, offscreen.""" binary = gui_binary.replace('pardes-gui', 'pardes') scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch)) env = base_env() 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') (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))) windows = [] def listed(): return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode() def started(name, e): w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e) windows.append(w) sock = root / f'pardes-9p-{name}.sock' wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30) nine = Client(sock) session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid) assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session)) wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30) pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s' return w, nine, session, pane try: w, nine, session, pane = started('gp', env) wait_for('the window listed its client', lambda: f'session gp {session} (gui)' in listed() and f'client {w.pid} ' in listed()) w.keys(b'Ofrom-the-window\x1b') wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body')) # The close button (the test feed's word for it): its last client # closed, the session ends. w.p.stdin.write(b'\x1b]777;close\x07') w.p.stdin.flush() assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:]) wait_for('the session ended with its window', lambda: not alive(session), timeout=20) nine.socket.close() print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, ' 'setsid, listed detached with the window); drawn, typed; the window closed ended both') w, nine, session, pane = started('gl', env) wait_for('the client listed', lambda: f'client {w.pid} ' in listed()) os.kill(w.pid, signal.SIGKILL) w.p.wait(timeout=10) wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed()) assert alive(session) and f'session gl {session} (gui)' in listed(), listed() nine.socket.close() assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the session ended', lambda: not alive(session), timeout=30) print('pair window: the window killed: the session runs on, listed (a loss); killed by name') # Kept from birth (`new --detach`): its window client's close leaves it. out = subprocess.run([binary, 'new', '--detach=gk', str(notes)], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) assert out.returncode == 0, out with Client(root / 'pardes-9p-gk.sock') as kn: gk = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid']) assert f'session gk {gk} (tty, kept)' in listed(), listed() w = Window(root, 'gkw', [gui_binary, 'attach', 'gk'], env) windows.append(w) wait_for('the window client listed', lambda: f'client {w.pid} ' in listed(), timeout=30) w.p.stdin.write(b'\x1b]777;close\x07') w.p.stdin.flush() assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:]) wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed()) assert alive(gk) and f'session gk {gk} (tty, kept)' in listed(), listed() assert subprocess.run([binary, 'kill', 'gk'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the session ended', lambda: not alive(gk), timeout=30) print('pair window: a `new --detach` session (kept): its window client closed, it runs on') w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off')) nine.socket.close() os.kill(w.pid, signal.SIGKILL) w.p.wait(timeout=10) wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) print('pair window: with no daemon, the window killed, its session ended; nothing left behind') finally: for w in windows: if w.p.poll() is None: w.p.kill() for p in processes(root): try: os.kill(p, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) def screen_text(client): shown = client.screen() cells = ''.join(cell[0] for cell in shown['cells']) return '\n'.join(cells[i:i + shown['cols']] for i in range(0, len(cells), shown['cols'])) def reconnect(sock, timeout=20): """The session's 9P again, once its upgraded process listens.""" return wait_for('the upgraded session\'s 9P', lambda: dial(sock), timeout=timeout) def dial(sock): try: return Client(sock) except (OSError, EOFError): # mid-exec: refused, or cut after the accept return None def saying(sock, words, timeout=30): """A connection to the session once its screen shows `words`: dialled afresh each look, since the process it talks to may exec meanwhile.""" last = [''] def look(): c = dial(sock) if c is None: return None try: last[0] = screen_text(c) if words in last[0]: return c except (OSError, EOFError): pass c.socket.close() return None try: return wait_for(f'the session saying {words!r}', look, timeout=timeout) except TimeoutError: raise TimeoutError(f'the session saying {words!r}; it shows:\n{last[0]}') def exe_of(pid): """What /proc says the process runs: (its path, whether that file is the one at the path now). FreeBSD's procstat names the path alone.""" if not procfs: rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines() return (rows[-1].split()[-1] if len(rows) > 1 else ''), None link = os.readlink(f'/proc/{pid}/exe') try: same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino except OSError: same = False return link, same def ppid(pid): if not procfs: return int(ps('-o', 'ppid=', '-p', str(pid))) return int(open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[1]) def where_waits(pid): """A process's state, a line each thread (its name, state, kernel wait channel and the syscall it is in): alive or not, and blocked where.""" if not alive(pid): return f'{pid}: gone\n' rows = [f'{pid}: alive, {b" ".join(cmdline(pid)).decode(errors="replace")[:300]}'] try: for tid in sorted(os.listdir(f'/proc/{pid}/task'), key=int): t = f'/proc/{pid}/task/{tid}' row = [] for leaf in ('comm', 'wchan', 'syscall'): try: row.append(open(f'{t}/{leaf}').read().strip().split(' ')[0]) except OSError: row.append('?') state = open(f'{t}/stat').read().rsplit(')', 1)[1].split()[0] rows.append(f' {tid} {row[0]} {state} wchan {row[1]} syscall {row[2]}') except OSError: pass return '\n'.join(rows + [f' fd {link}' for link in links(pid)]) + '\n' def keep_evidence(label, root, env, binary, sock, pids, clients): """What a failed step leaves for its reader, in a directory the run's cleanup does not remove (.scratch/daemon/kept/