diff options
Diffstat (limited to 'test/daemon.py')
| -rw-r--r-- | test/daemon.py | 246 |
1 files changed, 235 insertions, 11 deletions
diff --git a/test/daemon.py b/test/daemon.py index 26508a0b..b28d16ea 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -30,7 +30,8 @@ private HOME and runtime directory: python3 -B test/daemon.py --pair <pardes> PARDES_PAIR: a terminal's session and its first client python3 -B test/daemon.py --relink <pardes> - the daemon killed: its sessions register again with the next + the daemon killed: its sessions register again with the next; and + one stopped: an Adopt waits for its answer to the hello python3 -B test/daemon.py --far <pardes> the far clients and their blob cache alone, and a file by its hash python3 -B test/daemon.py --games <pardes> <lib> [seconds] @@ -269,8 +270,11 @@ class Replica: is read, whole. A daemon of another replica protocol (an older build's, across an Upgrade) is dialled again in its own.""" name = session.encode() - self.send(0x01, struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff') - self.send(0x06, b'\x00') + # Its first word (not far) in the same write, as a client's join + # sends it (core/replica.zig joinOn): a refused hello's connection + # is closed, and a second write after it would meet that. + hello = struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff' + self.s.sendall(struct.pack('<BI', 0x01, len(hello)) + hello + struct.pack('<BIB', 0x06, 1, 0)) tag, body = self.read() if tag == 0x01: pid, n = struct.unpack_from('<IH', body) @@ -972,6 +976,78 @@ def relink(binary): shutil.rmtree(root, ignore_errors=True) +def answer_late(binary): + """A session's Adopt asked at once, while its daemon has not answered + its hello (stopped 3 s, as a loaded machine can keep it), and before + the session's reader of the daemon has run: answered when the daemon + answers, never refused on a clock (daemon.zig `kept`).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + started = [] + terms = [] + wake = None + try: + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=one'], env) + started.append(stub.pid) + wait_for('the first session', (root / 'pardes-9p-one.sock').exists) + one = Client(root / 'pardes-9p-one.sock') + session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid']) + started.append(session) + shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0] + started.append(daemon) + wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run( + [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + os.kill(session, signal.SIGKILL) + one.socket.close() + wait_for('the killed session gone', lambda: not alive(session)) + os.kill(daemon, signal.SIGSTOP) + wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT)) + wake.start() + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=two'], env) + started.append(stub.pid) + wait_for('the next session', (root / 'pardes-9p-two.sock').exists) + two = Client(root / 'pardes-9p-two.sock', timeout=30) + started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid'])) + before = set(terminals(two)) + asked = time.monotonic() + two.write(f'/pane/{min(before)}/exec', b'Adopt\n') + took = time.monotonic() - asked + pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop() + assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, ' + f'and shell {shell_pid} was adopted') + exit_session(two, pane) + two.socket.close() + wait_for('the shells hung up', lambda: not alive(shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5) + finally: + if wake: + wake.cancel() + for t in terms: + try: + t.close() + except OSError: + pass + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + shutil.rmtree(root, ignore_errors=True) + + class Window: """A pardes-gui in test mode, its window offscreen and hidden, its keys written to its stdin (the test feed: Escape as `CSI 27 u`, which a @@ -1419,12 +1495,13 @@ def far(binary): 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): a client - # refused and one detached each end their ssh and its socket (one - # refused left both, 2026-10-30). + # 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\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)) @@ -1508,7 +1585,10 @@ def by_hash(binary): 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') + # 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'} @@ -1661,6 +1741,138 @@ def games(binary, libs, secs=10): 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 = {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'), 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 let go (its link + ends), the replacement core is the session's (its tape adopts it, its + options keep none), and a client attached after agrees with it, its + keys reaching it.""" + 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'), 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 + t, c = client('a') + nine.write(f'/pane/{text}/exec', b'Dump\n') + nine.write(f'/pane/{text}/exec', b'Restore\n') + wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30) + # The 9P link was the old core's. + 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') + t, c = client('r') + os.write(t.master, b'Oafter the restore\x1b') + 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') + wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30) + seen = len(checks(root / 'r.check')) + wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60) + assert c.poll() is None, 'the client ended' + print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session') + 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 @@ -1762,6 +1974,7 @@ def main(binary, cycles): pair_rows(binary) manage(binary) relink(binary) + answer_late(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) @@ -2436,10 +2649,15 @@ def upgrades(old, new): sock = root / 'pardes-9p-again.sock' wait_for('the next session', sock.exists) client = Client(sock) - started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])) - # Its reader of the daemon starts after its first frame: an Adopt - # before that waits for an `ok` nobody reads, and is refused. + again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) + started.append(again) + # A build before daemon.zig's `kept` waited for the hello's answer + # (the new-to-old run) refused an Adopt before its reader of the + # daemon ran (after its first frame), or within 2 s of a slow `ok`: + # it is asked once the daemon lists it (answer_late tests the wait). wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text()) + wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run( + [str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop() @@ -2691,11 +2909,17 @@ if __name__ == '__main__': pair_rows(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: relink(sys.argv[2]) + answer_late(sys.argv[2]) elif sys.argv[1:2] == ['--games']: games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) by_hash(sys.argv[2]) + far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-find']: + far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--restore']: + restore_client(sys.argv[2]) elif sys.argv[1:2] == ['--window-clients']: window_clients(sys.argv[2], sys.argv[3]) pdf_window(sys.argv[2], sys.argv[3]) |
