diff options
Diffstat (limited to 'test')
| -rw-r--r-- | test/daemon.py | 370 | ||||
| -rw-r--r-- | test/replicas.zig | 141 |
2 files changed, 389 insertions, 122 deletions
diff --git a/test/daemon.py b/test/daemon.py index e600beb7..d134732b 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -2,8 +2,10 @@ """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) and attached again - from another terminal, N times; +- 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 @@ -16,13 +18,15 @@ private HOME and runtime directory: - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py <pardes> [cycles] - python3 -B test/daemon.py --gui <pardes-gui> [cycles] (a hidden window; - needs a Wayland display, and a pardes beside it for the refusal) + python3 -B test/daemon.py --gui <pardes-gui> [cycles] (hidden windows, + offscreen, and a pardes beside it for the terminal's client) python3 -B test/daemon.py --ping <socket> <session> <pardes> [n] a hello of <pardes>'s build and n pings on a replica socket (one `ssh -L` forwards, say), timed python3 -B test/daemon.py --clients <pardes> the replica clients alone + python3 -B test/daemon.py --relink <pardes> + the daemon killed: its sessions register again with the next python3 -B test/daemon.py --far <pardes> the far clients and their blob cache alone, and a file by its hash python3 -B test/daemon.py --games <pardes> <lib> [seconds] @@ -428,8 +432,8 @@ def clients(binary): 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 while a client's view is live (its input the - # last): it takes the session's own and is drawn. + # 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) @@ -507,7 +511,7 @@ def clients(binary): 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=10) + 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') @@ -606,6 +610,132 @@ def manage(binary): shutil.rmtree(root, ignore_errors=True) +def wakeups(pid, secs): + """Its threads' context switches over `secs` (Linux's /proc): none for + a process nothing wakes.""" + def count(): + n = 0 + for task in os.listdir(f'/proc/{pid}/task'): + try: + for line in open(f'/proc/{pid}/task/{task}/status'): + if line.split(':')[0] in ('voluntary_ctxt_switches', 'nonvoluntary_ctxt_switches'): + n += int(line.split()[1]) + except OSError: + pass + return n + before = count() + time.sleep(secs) + return count() - before + + +def relink(binary): + """The daemon killed outright (docs/next-run.md, "A session registering + again"): a detached session and a terminal's, each with a shell, dial + the next daemon themselves (the first to find none starts it) and + register again with their shells' masters, so `--ps` lists both and + their shells, a client attaches, and the session then killed outright + leaves its shell to an Adopt. An idle session stays idle before and + after.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + + def listed(): + out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30) + return out.stdout.decode() if out.returncode == 0 else '' + + def daemons(): + return [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon'] and alive(p)] + + started = [] + terms = [] + try: + (root / 'notes.txt').write_text('notes\n') + started.append(subprocess.Popen([binary, '--detach=work', str(root / 'notes.txt')], env=env, cwd=root, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True).pid) + wait_for('the detached session\'s 9P socket', (root / 'pardes-9p-work.sock').exists) + work = Client(root / 'pardes-9p-work.sock') + session = int(dict(line.split(maxsplit=1) for line in work.read('/status').decode().splitlines())['pid']) + started.append(session) + work.write('/pane/1/exec', b'Term\n') + wait_for('its shell', lambda: terminals(work)) + shell = terminals(work)[0] + wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n') + shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=own'], env) + started.append(stub.pid) + wait_for('the terminal\'s session', (root / 'pardes-9p-own.sock').exists) + own = Client(root / 'pardes-9p-own.sock') + own_pid = int(dict(line.split(maxsplit=1) for line in own.read('/status').decode().splitlines())['pid']) + started.append(own_pid) + wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text()) + own_shell = terminals(own)[0] + own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1]) + started.append(own_shell_pid) + expected = [f'session work {session} (tty, detached)', f'session own {own_pid} (tty, has a frontend)', + f'shell {shell_pid}', f'shell {own_shell_pid}'] + assert all(row in listed() for row in expected), listed() + daemon = daemons()[0] + idle = wakeups(session, 2) if procfs else 0 + os.kill(daemon, signal.SIGKILL) + wait_for('the daemon gone', lambda: not alive(daemon)) + # Nobody runs pardes again: the sessions start the next one. + again = wait_for('a daemon again', daemons)[0] + started.append(again) + wait_for('both sessions and their shells listed again', lambda: all(row in listed() for row in expected)) + idle_after = wakeups(session, 2) if procfs else 0 + assert idle <= 2 and idle_after <= 2, ('an idle session woke', idle, idle_after) + print(f'relink: daemon {daemon} killed, {again} started by its sessions, both listed again with their shells; ' + f'the detached one idle before and after ({idle} and {idle_after} wakeups in 2 s)') + tc = Term(30, 100) + terms.append(tc) + c = tc.spawn([binary, 'attach', 'work'], env) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30) + wait_for('the client in --ps', lambda: f'client {c.pid} ' in listed()) + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + os.kill(session, signal.SIGKILL) + wait_for('the killed session gone', lambda: not alive(session)) + wait_for('its shell no session\'s', lambda: 'no session holds' in listed()) + assert alive(shell_pid), 'the new daemon held its master' + before = set(terminals(own)) + own.write(f'/pane/{min(before)}/exec', b'Adopt\n') + pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() + assert run(own, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') + exit_session(own, pane) + stub.wait(timeout=10) + own.socket.close() + work.socket.close() + wait_for('the shells hung up', lambda: not alive(shell_pid) and not alive(own_shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(again), timeout=5) + left = [p for p in processes(root) if alive(p)] + assert not left, [cmdline(p) for p in left] + print('relink: nothing left behind') + finally: + for t in terms: + try: + t.close() + except OSError: + pass + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + shutil.rmtree(root, ignore_errors=True) + + class Window: """A pardes-gui in test mode, its window offscreen and hidden, its keys written to its stdin (the test feed: Escape as `CSI 27 u`, which a @@ -704,7 +834,7 @@ def pdf_window(binary, gui_binary): 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=10) + sess.wait(timeout=60) nine.socket.close() finally: for pid in started: @@ -850,7 +980,7 @@ def window_clients(binary, gui_binary): 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=10) + 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. @@ -1086,7 +1216,7 @@ def far(binary): 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=10) + 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: @@ -1169,7 +1299,7 @@ def by_hash(binary): 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=10) + sess.wait(timeout=60) nine.socket.close() finally: for t in terms: @@ -1282,7 +1412,7 @@ def games(binary, libs, secs=10): 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=10) + sess.wait(timeout=60) nine.socket.close() finally: for t in terms: @@ -1392,73 +1522,94 @@ def main(binary, cycles): far(binary) by_hash(binary) manage(binary) + relink(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) + # Detach in the terminal it was born with: the stub ends (exit 0, + # its words), the terminal put back; the session runs on detached, + # for good: every attach after it is a client. + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert stub.wait(timeout=10) == 0, stub.returncode + # The stub's last words are in its terminal before it ends, but + # this side's reader may not have them yet. + wait_for('the stub says it detached', lambda: b'detached from \'work\', which is still running; come back with `pardes attach work`' in term.text()) + assert b'\x1b[?1049l' in term.text(), 'the terminal is put back' + term.close() + assert alive(session) and alive(shell_pid) + assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' + + def attach(term, argv, typed): + """A client: its own process, drawn, listed by --ps under the + session, detached still, and its keys in the shell.""" + c = term.spawn(argv, env) + started.append(c.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 {c.pid} ' in out and out)( + subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())) + assert f'session work {session} (tty, detached)' in listed, listed + os.write(term.master, f'echo {typed}\r'.encode()) + wait_for('its keys in the shell', lambda: typed.encode() in client.read(f'/pane/{shell}/body')) + return c + + def let_go(how, c, term): + """Detach in it (its view the live one: it typed last), or its + terminal closed: it ends; the session and its shell run on.""" + if how == 'detach': + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert c.wait(timeout=10) == 1, c.returncode + wait_for('the client says it was let go', lambda: b'let this client go' in term.text()) + else: + term.close() + c.wait(timeout=10) + if how == 'detach': + term.close() + assert alive(session) and alive(shell_pid) + baseline = None for cycle in range(cycles): - client.write(f'/pane/{shell}/exec', b'Detach\n') - assert stub.wait(timeout=10) == 0, stub.returncode - # The stub's last words are in its terminal before it ends, but - # this side's reader may not have them yet. - wait_for('the stub says it detached', lambda: b'detached from \'work\'' in term.text()) - said = term.text() - assert b'\x1b[?1049l' in said, 'the terminal is put back' - term.close() - assert alive(session) and alive(shell_pid) - assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' term = Term(30, 100) - stub = term.spawn([binary, '--attach=work'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', - lambda: client.screen()['cols'] == 100 and client.screen()['rows'] == 30) + c = attach(term, [binary, '--attach=work'] if cycle % 2 else [binary, 'attach'], f'cycle-{cycle}') now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root))) if baseline is None: baseline = now assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} detach/attach cycles, fds/sockets/processes level: {baseline}') + let_go('detach' if cycle % 2 else 'close', c, term) + print(f'daemon: a Detach in its own terminal, then {cycles} attaches as clients (Detach in each, or its terminal closed), ' + f'fds/sockets/processes level: {baseline}') - # Another terminal while one is attached: a replica client of the - # session (a session shows one frontend of its own), listed under - # it by --ps, drawn beside the first, typed into as the first is. - # Detached from inside, it ends and the first draws on; closed - # outright, the same. + # Two clients at once, both listed by --ps, both typed into and + # drawn; the second let go by a Detach in it, or its terminal + # closed, and the first draws on. + term = Term(30, 100) + first = attach(term, [binary, 'attach', 'work'], 'first-in') for how in ('detach', 'close'): - # Bigger than the first: the shell, sized for the first (its - # last typist), shows whole in it. term2 = Term(40, 120) - stub2 = term2.spawn([binary, '--attach=work'], env) - started.append(stub2.pid) - wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text()) - wait_for('the second terminal\'s view live', lambda: client.screen()['cols'] == 120) - listed = subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode() - assert f'client {stub2.pid} ' in listed, listed + second = attach(term2, [binary, 'attach', 'work'], f'two-typed-{how}') os.write(term.master, f'echo one-typed-{how}\r'.encode()) wait_for('the first terminal\'s keys in the shell', lambda: f'one-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) - os.write(term2.master, f'echo two-typed-{how}\r'.encode()) - wait_for('the second terminal\'s keys in the shell', lambda: f'two-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) + # (Words no line before has a letter of in the same place: a + # terminal is sent the cells that changed.) + drawn = f'{how.upper()}BOTHDRAWN' seen = len(term.text()) - run(client, shell, f'echo both-drawn-{how}\n'.encode()) - wait_for('the first terminal drawn', lambda: f'both-drawn-{how}'.encode() in term.text()[seen:]) - wait_for('the second terminal drawn', lambda: f'both-drawn-{how}'.encode() in term2.text()) - assert stub.poll() is None and stub2.poll() is None - if how == 'detach': - # Its view is the live one (its terminal spoke last). - client.write(f'/pane/{shell}/exec', b'Detach\n') - stub2.wait(timeout=10) - term2.close() - else: - term2.close() - stub2.wait(timeout=10) - wait_for('the first terminal\'s view live again', lambda: client.screen()['cols'] == 100) - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn', lambda: drawn.encode() in term.text()[seen:]) + wait_for('the second terminal drawn', lambda: drawn.encode() in term2.text()) + assert first.poll() is None and second.poll() is None + # Its view the live one: it typed last. + os.write(term2.master, f'echo two-last-{how}\r'.encode()) + wait_for('the second terminal\'s keys in the shell', lambda: f'two-last-{how}'.encode() in client.read(f'/pane/{shell}/body')) + let_go(how, second, term2) + wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + drawn = f'{how.upper()}FIRSTON' seen = len(term.text()) - run(client, shell, f'echo first-on-{how}\n'.encode()) - wait_for('the first terminal drawn on', lambda: f'first-on-{how}'.encode() in term.text()[seen:]) - assert stub.poll() is None, 'the first terminal stays attached' + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn on', lambda: drawn.encode() in term.text()[seen:]) + assert first.poll() is None, 'the first client stays' now = (fds(session), fds(daemon), len(list(root.iterdir())), len([p for p in processes(root) if alive(p)])) assert now[:3] == baseline[:3], (how, now, baseline) - print('daemon: a second terminal on an attached session a client of it (in --ps), both typed into and drawn, then detached and closed; the first drew on') + print('daemon: two clients at once, each in --ps, both typed into and drawn; the second detached, then closed; the first drew on') + stub = first # Killed outright: its shells live on, their masters the daemon's, # and a replica client of it hears so at once, in words (one froze @@ -1470,7 +1621,10 @@ def main(binary, cycles): os.kill(session, signal.SIGKILL) killed = time.monotonic() wait_for('the replica client ended with its session', lambda: rc.poll() is not None, timeout=10) - assert time.monotonic() - killed < 2 and b'let this client go' in tr.text(), (time.monotonic() - killed, tr.text()[-300:]) + assert time.monotonic() - killed < 2, time.monotonic() - killed + # Its words are in its terminal before it ends, but this side's + # reader may not have them yet. + wait_for('the replica client says it was let go', lambda: b'let this client go' in tr.text()) tr.close() stub.wait(timeout=10) client.socket.close() @@ -1507,22 +1661,33 @@ def main(binary, cycles): shell.kill() shell.wait(timeout=10) term.close() - term = Term() - stub = term.spawn([binary, '--attach=fresh'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', lambda: not sized(client)) - print('daemon: a session whose stub was killed outright detached, and was attached again') 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() + # Sized twice (Ptys.take): a run into a prompt redrawn under it + # reads as not run (core/ninep/pty.zig). + wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') said = run(client, pane, b'echo $$\n') assert said.split(b'\n')[1] == str(shell_pid).encode(), said 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())) + assert f'session fresh {session} (tty, 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, the daemon goes. - client.write(f'/pane/{pane}/exec', b'Exit\n') - stub.wait(timeout=10) + # The end: the session quits, its shells hang up, its client and + # the daemon go. + exit_session(client, pane) + assert stub.wait(timeout=10) == 1, stub.returncode + wait_for('the client says it was let go', lambda: b'let this client go' in term.text()) client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) @@ -1551,62 +1716,67 @@ def sized(client): def gui(binary, cycles): - """A window's Detach closes it and keeps the process; `pardes-gui - --attach` opens it again. Test mode: a hidden window, its stdin the - test feed.""" + """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 = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} - display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) - if not display.is_absolute(): - display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display (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_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on') + 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] assert not sized(client), 'a window owns the size' - baseline = None - for cycle in range(cycles): - client.write(f'/pane/{shell}/exec', b'Detach\n') - wait_for('the window closed', lambda: sized(client)) - assert proc.poll() is None, 'the process carries on with no window' - attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - assert attach.returncode == 0, attach.stderr - wait_for('the window open again', lambda: not sized(client)) - now = (fds(proc.pid), len(processes(root))) - baseline = baseline or now - assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} window detach/attach cycles, fds/processes level: {baseline}') - # Attached already: another window is a replica client of the - # session (its own process, its captures its own), listed by --ps; - # closed, it ends alone. + # 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) - listed = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() - assert f'client {second.pid} ' in listed, listed + assert f'client {second.pid} ' in listed(), listed() second.close() - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode()) + wait_for('the client gone from --ps', lambda: 'client ' not in listed()) assert not sized(client), 'the first window stays' assert proc.poll() is None - print('daemon: a second window on an attached window session a client of it (in --ps), closed alone') - # Another kind joins as a replica client: a terminal of the window's - # session, by its name alone. A name nobody has is refused in words. + 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 proc.poll() is None, 'the process carries on with no window' + assert f'session win {proc.pid} (gui, detached)' 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 {proc.pid} (gui, detached)' 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) + 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:] @@ -2061,6 +2231,8 @@ if __name__ == '__main__': clients(sys.argv[2]) elif sys.argv[1:2] == ['--manage']: manage(sys.argv[2]) + elif sys.argv[1:2] == ['--relink']: + relink(sys.argv[2]) elif sys.argv[1:2] == ['--games']: games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10) elif sys.argv[1:2] == ['--far']: diff --git a/test/replicas.zig b/test/replicas.zig index ffe82790..2211952b 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -246,6 +246,9 @@ const Totals = struct { /// Deltas the replicas applied while the flood ran. flood_deltas: u64 = 0, flood_us: u64 = 0, + /// Kitty images a client held at quiescence, the session's pixels + /// (`--bytes`, `images`). + images_equal: u64 = 0, flood_delta_bytes: u64 = 0, flood_unit_bytes: u64 = 0, fetched: u64 = 0, @@ -795,9 +798,13 @@ const Soak = struct { /// encoding cost. framed: bool = false, encode_ns: u64 = 0, - /// The session's pty told the answer to the program's kitty query - /// (`questions`): once, whatever the clients. - kitty_answers: u32 = 0, + /// The session's pty told the answers to the program's kitty query and + /// its four images (`questions`, `images`, `kitty_oks`): each once, whatever the + /// clients. + kitty_answers: [kitty_oks.len]u32 = @splat(0), + /// The temporary file and the shared memory object an image was shown + /// by (`images`): gone once the session read them. + media: *const Media = undefined, /// A Peer's queue, swapped out as its writer swaps it (the Peers' /// allocator's). sending: std.ArrayListUnmanaged(u8) = .empty, @@ -818,7 +825,9 @@ const Soak = struct { const s = of(ctx); // Only the session's emulator answers its program: a client's // answers are its tape's, never written (`questions`). - if (std.mem.indexOf(u8, bytes, "\x1b_Gi=31;OK") != null) s.kitty_answers += 1; + for (kitty_oks, &s.kitty_answers) |ok, *n| if (std.mem.indexOf(u8, bytes, ok) != null) { + n.* += 1; + }; s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } @@ -1467,10 +1476,16 @@ const Soak = struct { for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); - if (bytes_kind and s.kitty_answers != 1) { + if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: the program's kitty query was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, s.kitty_answers }); - } + std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); + }; + if (bytes_kind) for (&s.media.temp, &s.media.object) |*temp, *object| { + for ([_][:0]const u8{ temp, object }, [_]bool{ libc.access(temp, libc.F_OK) == 0, shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDONLY }), 0) >= 0 }) |name, left| if (left) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: {s}, an image's medium, is still there\n", .{ s.r.seed, s.r.rtt_ms, name }); + }; + }; for (s.clients, 1..) |*cl, id| { totals.resizes += cl.resizes; totals.wakes += cl.wakes; @@ -1497,7 +1512,8 @@ const Soak = struct { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" }); } - // At quiescence, every terminal the session's, cell for cell. + // At quiescence, every terminal the session's, cell for cell, + // and its kitty images the session's, pixel for pixel. for (core.panes, 0..) |slot, pid| { const pane = slot orelse continue; const state = pane.terminal orelse continue; @@ -1509,6 +1525,13 @@ const Soak = struct { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); } + const theirs = imagesHash(state); + if (!std.mem.eql(u64, &theirs, &imagesHash(mine))) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s kitty images in terminal {d} are not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } else for (theirs) |h| { + if (h != 0) totals.images_equal += 1; + } } // ...and every file's text the session's, byte for byte: a digest // takes a text of 4 KiB and up by its length (core/walk.zig). @@ -1584,11 +1607,20 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); defer gpa.free(session_only); - const asked = if (bytes_kind) try questions(dir) else ""; - defer if (bytes_kind) gpa.free(asked); - const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, asked }); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, if (bytes_kind) questions else "" }); defer gpa.free(shell_session); - const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); + var media: Media = undefined; + const shown = if (bytes_kind) try images(dir, r.seed, &media) else ""; + defer if (bytes_kind) { + gpa.free(shown); + for (&media.temp, &media.object) |*temp, *object| { + _ = libc.unlink(temp); + _ = shm.shm_unlink(object); + } + }; + const yes_only = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); + defer gpa.free(yes_only); + const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); var soak: Soak = .{ @@ -1604,27 +1636,90 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .yes = yes, .own_left = r.steps, .typing = r.clients + 1, + .media = &media, }; // The session: THE session loop, from its start to its end. try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); if (soak.err) |err| return err; } +/// What `questions`'s kitty query and `images`'s four are answered with. +const kitty_oks = [_][]const u8{ "\x1b_Gi=31;OK", "\x1b_Gi=5;OK", "\x1b_Gi=6;OK", "\x1b_Gi=7;OK", "\x1b_Gi=8;OK" }; + +/// The temporary files and the shared memory objects `images` shows its +/// images by, which the session's emulator removes when it reads them. +const Media = struct { temp: [2][300:0]u8, object: [2][64:0]u8 }; + +const shm = struct { + extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: libc.mode_t) c_int; + extern "c" fn shm_unlink(name: [*:0]const u8) c_int; + extern "c" fn ftruncate(fd: c_int, len: i64) c_int; +}; + +/// The pixels of each of `images`'s kept images a terminal holds, hashed +/// (0: not held). +fn imagesHash(state: *pardes.Term.State) [4]u64 { + var out: [4]u64 = @splat(0); + const screen = pardes.Term.emulatorOf(state).vt.screens.active; + for (&out, 15..) |*h, id| if (screen.kitty_images.imageById(@intCast(id))) |img| { + h.* = std.hash.Wyhash.hash(1, img.data.bytes() orelse continue); + }; + return out; +} + /// What the shell's program asks its terminal at the end of its session /// (`--bytes`): device attributes, the cursor's place, the cell's size in -/// pixels, a kitty query; then a kitty image by direct data, shown, and one -/// by a file of the session's machine, stored (a=t), which no client loads -/// (P32): absent there, as every live terminal's image is under screen -/// state. Shown (a=T) it would move the session's cursor past it and not a -/// client's: a divergence until the file's bytes are taped (a later step). -fn questions(dir: []const u8) ![]u8 { +/// pixels, a kitty query. +const questions = "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n$ "; + +/// What the flood's program shows at its end (`--bytes`; after it, so the +/// clients still hold them at quiescence): kitty images shown (a=T) by +/// direct data, by a file of the session's machine, by a temporary file +/// (which its reader deletes) and by shared memory (which its reader +/// unlinks), twice: answered (ids 5 to 8, `kitty_oks`), and kept (ids 15 +/// to 18, q=1: the soak's tty echoes an answer back as output, and an +/// echoed `ESC _ G i=5;OK` is a transmission of image 5 that fails and +/// takes it away), the kept one by shared memory 1.4 MB, so its read +/// crosses to a client by hash. Each medium is the session's to read and +/// every client is handed its bytes (Term.media): each image in every +/// client, pixel for pixel; the program answered once; each temporary file +/// and object gone once. +fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { var path_buf: [300]u8 = undefined; const path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/pixels.rgb", .{dir}, 0); try writeText(path, &@as([12]u8, @splat(0x7f))); - var b64: [400]u8 = undefined; - const name = std.base64.standard.Encoder.encode(&b64, path); - return std.fmt.allocPrint(gpa, "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n" ++ - "\x1b_Ga=T,i=5,f=24,s=2,v=2;AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=t,i=6,t=f,f=24,s=2,v=2;{s}\x1b\\\r\n$ ", .{name}); + var out: std.ArrayListUnmanaged(u8) = .empty; + errdefer out.deinit(gpa); + var b64: [3][400]u8 = undefined; + const enc = std.base64.standard.Encoder; + for (0..2, [_]u32{ 2, 600 }, [_][]const u8{ "", ",q=1" }) |round, side, quiet| { + const temp = try std.fmt.bufPrintSentinel(&media.temp[round], "{s}/tty-graphics-protocol-{d}-{d}.rgb", .{ dir, seed, round }, 0); + try writeText(temp, &@as([12]u8, @splat(0x3f))); + const object = try std.fmt.bufPrintSentinel(&media.object[round], "/pardes-soak-{d}-{d}-{d}", .{ libc.getpid(), seed, round }, 0); + const fd = shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); + if (fd < 0) return error.ShmOpenFailed; + defer _ = libc.close(fd); + // Sized first: FreeBSD's write does not grow a shared memory object. + if (shm.ftruncate(fd, side * side * 4) != 0) return error.WriteFailed; + var row: [600 * 4]u8 = undefined; + for (0..side) |y| { + for (row[0 .. side * 4], 0..) |*c, i| c.* = @truncate(i * 7 + y * 13 + seed); + if (libc.write(fd, &row, side * 4) != side * 4) return error.WriteFailed; + } + const id = 5 + 10 * round; + try out.print(gpa, "\x1b_Ga=T,i={d},f=24,s=2,v=2{s};AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=T,i={d},t=f,f=24,s=2,v=2{s};{s}\x1b\\\r\n" ++ + "\x1b_Ga=T,i={d},t=t,f=24,s=2,v=2{s};{s}\x1b\\\r\n\x1b_Ga=T,i={d},t=s,f=32,s={d},v={d},c=8,r=4{s};{s}\x1b\\\r\n", .{ + id, quiet, + id + 1, quiet, + enc.encode(&b64[0], path), id + 2, + quiet, enc.encode(&b64[1], temp), + id + 3, side, + side, quiet, + enc.encode(&b64[2], object), + }); + } + try out.appendSlice(gpa, "$ "); + return out.toOwnedSlice(gpa); } /// A typist: keys 50-200 ms apart, a pause now and then. @@ -2836,7 +2931,7 @@ pub fn main(init: std.process.Init) !void { var t: Totals = .{}; pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); - if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000 }); + if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, |
