summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rw-r--r--test/daemon.py732
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/e2e_harness.zig18
-rw-r--r--test/panes.zig4
-rw-r--r--test/perf.zig138
-rw-r--r--test/process.zig3
-rw-r--r--test/process/terminals.zig9
-rw-r--r--test/process/tty_terminals.zig4
-rw-r--r--test/replicas.zig3
-rw-r--r--test/session.zig15
10 files changed, 896 insertions, 40 deletions
diff --git a/test/daemon.py b/test/daemon.py
index 775a487b..2325f721 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -25,8 +25,13 @@ private HOME and runtime directory:
`ssh -L` forwards, say), timed
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
+ python3 -B test/daemon.py --launch <pardes>
+ `pardes new --detach` returns once its session runs
+ 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]
@@ -236,7 +241,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 24
+ WIRE = 25
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -265,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)
@@ -479,10 +487,10 @@ def clients(binary):
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.
+ # 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 b'let this client go' in ta.text(), ta.text()[-300:]
+ assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-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')
@@ -526,6 +534,238 @@ def clients(binary):
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 = {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')
+ (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} (tty, 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} (tty, 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 = {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', 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, detached)' 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. With a daemon: a Detach in
+ the pair's client says so and exits 0, the session runs on (listed); an
+ attach is a client again; TERM to the client puts its terminal back and
+ the session runs on; so does a KILL, and a closed terminal (HUP): each a
+ loss, not a close. With none: 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 = {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', 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 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
+
+ try:
+ t, c, nine, session, pane = started('rows', env)
+ 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 f'session rows {session} (tty, detached)' in listed()
+ print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ for how in ('TERM', 'KILL', 'HUP'):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', 'rows'], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ 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())
+ assert alive(session), how
+ print(f'pair rows: 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)
+ assert c.poll() is None and alive(session), 'a Detach with no daemon is refused'
+ 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 manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -736,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
@@ -966,10 +1278,10 @@ def window_clients(binary, gui_binary):
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 why.
+ # 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 'let this client go' in wd.said(), wd.said()[-500:]
+ 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
@@ -1183,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))
@@ -1272,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'}
@@ -1425,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
@@ -1521,8 +1969,12 @@ def main(binary, cycles):
clients(binary)
far(binary)
by_hash(binary)
+ launch(binary)
+ pair(binary)
+ 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)
@@ -1557,8 +2009,8 @@ def main(binary, cycles):
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())
+ assert c.wait(timeout=10) == 0, c.returncode
+ wait_for('the client says it detached', lambda: b"detached from 'work', which is still running" in term.text())
else:
term.close()
c.wait(timeout=10)
@@ -1686,8 +2138,8 @@ def main(binary, cycles):
# 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())
+ assert stub.wait(timeout=10) == 0, stub.returncode
+ assert b'let this client go' not in term.text(), term.text()[-300:]
client.socket.close()
term.close()
wait_for('the adopted shell hung up', lambda: not alive(shell_pid))
@@ -1804,6 +2256,90 @@ def gui(binary, cycles):
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 = {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'),
+ 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} (tty, detached)' 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} (tty, detached)' 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')
+ 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'])
@@ -1984,7 +2520,9 @@ def upgrades(old, new):
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
- gone = 2 if b'detached from' in term2.text() else 1
+ # (A client of a build that execs at an Upgrade comes back: its
+ # connection is the session's again.)
+ gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -2004,8 +2542,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text() or
- b'run the same pardes at both ends' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2094,7 +2633,10 @@ def upgrades(old, new):
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
- stub2.wait(timeout=10)
+ try:
+ stub2.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
@@ -2107,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()
@@ -2134,6 +2681,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', 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')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ 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 gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2228,24 +2893,43 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
+ elif sys.argv[1:2] == ['--launch']:
+ launch(sys.argv[2])
+ elif sys.argv[1:2] == ['--pair']:
+ pair(sys.argv[2])
+ 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])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig
index f7d65b03..26e942e7 100644
--- a/test/e2e_harness.zig
+++ b/test/e2e_harness.zig
@@ -149,9 +149,25 @@ pub const Harness = struct {
return true;
}
+ /// The app ended as closing its terminal ends it: the master closed (its
+ /// hangup), the app given `end_ms` to end, SIGKILLed only after, and
+ /// reaped: what it ends at its own end (its shells, its language servers'
+ /// groups) does not outlive the case.
pub fn deinit(self: *Harness) void {
- posix.kill(self.pid, posix.SIG.KILL) catch {};
_ = libc.close(self.master);
+ const end_ms = 5000;
+ const until = nowMs() + end_ms;
+ var status: c_int = 0;
+ var none: [0]posix.pollfd = .{};
+ while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) {
+ if (nowMs() < until) {
+ _ = posix.poll(&none, 5) catch 0;
+ continue;
+ }
+ posix.kill(self.pid, posix.SIG.KILL) catch {};
+ _ = libc.waitpid(self.pid, &status, 0);
+ break;
+ }
self.stream.deinit();
self.gpa.destroy(self.raw);
self.term.deinit(self.gpa);
diff --git a/test/panes.zig b/test/panes.zig
index 6bda3519..38eb0a71 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -3949,6 +3949,10 @@ const PdfAddon = struct {
}
};
const id = try opened(a, Land{ .a = a, .r = r });
+ // The effects `jobs` took last are the session's steps: a unit of
+ // its own before the client's input.
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
const guessed = r.stats.mispredicted;
const stopped = r.stats.stopped;
const told = a.core.panes[id].?.addon.?.views;
diff --git a/test/perf.zig b/test/perf.zig
index 7920dedf..8c88ef01 100644
--- a/test/perf.zig
+++ b/test/perf.zig
@@ -391,6 +391,8 @@ const Options = struct {
creation: bool = false,
startup: bool = false,
mini: bool = false,
+ /// The scans a frame's slice bounds, a call at a time (`measureSearch`).
+ search: bool = false,
terminal_mib: ?usize = null,
/// The real binary's keystroke-to-present, `yes` stream and big open
/// (a tty pardes), or its keystrokes alone (a pardes-gui).
@@ -407,13 +409,14 @@ const Options = struct {
while (i < args.len) : (i += 1) {
const arg = args[i];
if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption;
- const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
+ const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
return error.UnknownOption;
switch (option) {
.json => opts.json = true,
.creation => opts.creation = true,
.startup => opts.startup = true,
.mini => opts.mini = true,
+ .search => opts.search = true,
.@"self-test" => opts.self_test = true,
else => {
i += 1;
@@ -475,6 +478,7 @@ pub fn main(init: std.process.Init) !void {
if (opts.creation) return measureCreation(init.io, reps, opts.json);
if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json);
if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json);
+ if (opts.search) return measureSearch(init.io);
if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json);
if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json);
// The image-frame cells load the image addon by the path the build baked
@@ -1742,6 +1746,138 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool)
}
}
+/// `--search`: the two scans a frame's slice bounds, each call timed and
+/// its instructions counted (user space, this thread): a find's names
+/// scored again as a query is typed into it over 200,000 paths
+/// (core/Names.zig `rescore`, Names' cap), and a search's places found a
+/// tick at a time over the large fixture, the view in its middle
+/// (core/Places.zig `settle` on a tick). The longest call of each is the
+/// slice a key or a frame can take.
+fn measureSearch(io: std.Io) !void {
+ var random: [12]u8 = undefined;
+ io.random(&random);
+ const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-perf-{x}", .{random});
+ defer gpa.free(dir);
+ try std.Io.Dir.createDirAbsolute(io, dir, .default_dir);
+ defer std.Io.Dir.cwd().deleteTree(io, dir) catch {};
+ var counter: Instructions = try .open();
+ defer counter.close();
+
+ const Names = @FieldType(pardes.panes.Query, "names");
+ var names: Names = .{};
+ defer names.deinit(gpa);
+ const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" };
+ const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" };
+ var row: [160]u8 = undefined;
+ for (0..200_000) |i| {
+ const path = try std.fmt.bufPrint(&row, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i });
+ try names.add(gpa, path, 0, path.len, Names.baseOf(path), 0);
+ }
+ // Typed a key at a time, as into a find: each key's call, then the
+ // calls of the frames after it while it is busy.
+ for ([_][]const u8{ "m", "tape", "places zig", "core/module_9/replica_1", "zig-pkg/ghostty/src/terminal/module_99/kitty" }) |query| {
+ var slow: Slowest = .{};
+ names.typed(gpa, "");
+ for (1..query.len + 1) |n| {
+ var calls: usize = 0;
+ while (true) : (calls += 1) {
+ const was = counter.read();
+ const t0 = nowNs();
+ if (calls == 0) names.typed(gpa, query[0..n]) else names.rescore(gpa);
+ slow.add(nowNs() -| t0, counter.read() -| was, names.hits.items.len);
+ if (!names.busy()) break;
+ }
+ }
+ slow.report("rescore", query, names.hits.items.len);
+ }
+
+ const fx = fixtures[2];
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, fx.name });
+ defer gpa.free(path);
+ const text = try generate(fx);
+ try writeFile(path, text);
+ gpa.free(text);
+ for ([_][]const u8{ "e", "lorem.*amet", "helper_[0-9]+", "qqq" }) |pattern| {
+ const core = try boot();
+ defer core.deinit();
+ pardes.look.lookAt(core, 0, path);
+ pump(core);
+ const id = filePane(core) orelse return error.OpenDidNotOpenFile;
+ const pane = core.panes[id].?;
+ seek(pane, fx, 0);
+ pane.file.?.scroll = fx.lines / 2;
+ pane.body.cur_row = @intCast(fx.lines / 2);
+ _ = try frame(core);
+ const set = &pane.places;
+ set.search(core, pane, .typed, pane.serial, pattern, false, null, false);
+ var slow: Slowest = .{};
+ while (set.busy(pane) and slow.calls < 100_000) {
+ const was = counter.read();
+ const t0 = nowNs();
+ set.settle(core, pane, true);
+ slow.add(nowNs() -| t0, counter.read() -| was, 0);
+ }
+ slow.report("fill", pattern, set.hits.items.len);
+ }
+}
+
+/// The longest of a scan's calls.
+const Slowest = struct {
+ calls: usize = 0,
+ total_ns: u64 = 0,
+ ns: u64 = 0,
+ /// The instructions of the longest call (by time), and the most of any.
+ ins: u64 = 0,
+ most_ins: u64 = 0,
+ /// The same of the calls that left under 1,000 hits to sort: the scan
+ /// alone, nearly (`Names.rescore` sorts every hit at each call).
+ few_ns: u64 = 0,
+ few_ins: u64 = 0,
+
+ fn add(s: *Slowest, ns: u64, ins: u64, hits: usize) void {
+ s.calls += 1;
+ if (hits < 1000 and ns > s.few_ns) {
+ s.few_ns = ns;
+ s.few_ins = ins;
+ }
+ s.total_ns += ns;
+ if (ns > s.ns) {
+ s.ns = ns;
+ s.ins = ins;
+ }
+ s.most_ins = @max(s.most_ins, ins);
+ }
+
+ fn report(s: *const Slowest, what: []const u8, of: []const u8, hits: usize) void {
+ std.debug.print("{s} \"{s}\": {d} calls, {d} hits, {d:.2} ms in all; longest {d} us ({d} instructions); most instructions {d}; longest with under 1,000 hits {d} us ({d} instructions)\n", .{
+ what, of, s.calls, hits, @as(f64, @floatFromInt(s.total_ns)) / 1e6, s.ns / 1000, s.ins, s.most_ins, s.few_ns / 1000, s.few_ins,
+ });
+ }
+};
+
+/// This thread's instructions in user space (perf_event_open).
+const Instructions = struct {
+ fd: std.posix.fd_t,
+
+ fn open() !Instructions {
+ const linux = std.os.linux;
+ var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } };
+ const rc = linux.perf_event_open(&attr, 0, -1, -1, 0);
+ if (linux.errno(rc) != .SUCCESS) return error.NoInstructionCounter;
+ return .{ .fd = @intCast(rc) };
+ }
+
+ fn read(c: Instructions) u64 {
+ var n: u64 = 0;
+ _ = std.os.linux.read(c.fd, std.mem.asBytes(&n), 8);
+ return n;
+ }
+
+ fn close(c: Instructions) void {
+ _ = std.os.linux.close(c.fd);
+ }
+};
+
fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void {
const f = &pane.file.?;
const span = @max(1, fx.lines * 8 / 10);
diff --git a/test/process.zig b/test/process.zig
index 8bcbddeb..e2a4f592 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -916,7 +916,8 @@ pub const Child = struct {
while (environ[i]) |kv| {
const entry = std.mem.span(kv);
const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len;
- if (std.mem.startsWith(u8, entry, "PARDES_") or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
+ // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`).
+ if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
var name: [256]u8 = undefined;
const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126);
_ = unsetenv(n);
diff --git a/test/process/terminals.zig b/test/process/terminals.zig
index 24772ced..d9c3bcca 100644
--- a/test/process/terminals.zig
+++ b/test/process/terminals.zig
@@ -262,7 +262,9 @@ fn rawKey(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
/// thousand: nothing printed is nothing kept), then a probe typed and
/// taken back with ^U.
fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8, rows: usize) !void {
- var d = try process.Detached.start(gpa, exe, "agent", .{});
+ // No builtin announces itself: Term's name would linger on the screen
+ // (MessageLinger, 800 ms) and go between `before` and ^U's answer.
+ var d = try process.Detached.start(gpa, exe, "agent", .{ .init = "Verbose off\n" });
defer d.deinit();
const f = &d.files;
try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script}));
@@ -300,7 +302,10 @@ fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8
try f.write(data, "\x15");
const back_by = eh.nowMs() + 10_000;
while (!std.mem.eql(u8, try f.screen(), before)) {
- if (eh.nowMs() > back_by) return error.ScreenNotRestored;
+ if (eh.nowMs() > back_by) {
+ std.debug.print("before:\n{s}\nafter ^U:\n{s}\n", .{ before, try f.screen() });
+ return error.ScreenNotRestored;
+ }
sleepMs(10);
}
}
diff --git a/test/process/tty_terminals.zig b/test/process/tty_terminals.zig
index d5540818..dfb027e2 100644
--- a/test/process/tty_terminals.zig
+++ b/test/process/tty_terminals.zig
@@ -844,7 +844,9 @@ fn exec_bigdrag(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try t.drag("middle", "150", 31);
try t.drag("middle", "198", 59);
try t.release("middle", "198", 59);
- try t.stable(500, 8000);
+ // Bash fails each swept chunk as a command, one by one: under load
+ // that runs well past 8 s, so the quiet is waited for once, with the
+ // cap the sweep's other waits have.
try t.stable(800, 30000);
// still alive: type and execute a marker command
try t.press("left", "105", 41);
diff --git a/test/replicas.zig b/test/replicas.zig
index 7bf79055..6a6d43b4 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -699,7 +699,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null });
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {
@@ -1120,7 +1120,6 @@ const Soak = struct {
}
pub fn upgradeAsked(_: *Soak) void {}
- pub fn note(_: *Soak, _: anytype) void {}
pub fn restoring(_: *Soak, _: *pardes.Pardes) void {}
pub fn restored(_: *Soak, _: *SessionLoop) void {}
diff --git a/test/session.zig b/test/session.zig
index 1cbee9df..d437ecf2 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -53,7 +53,7 @@ pub const Session = struct {
/// A session showing one file pane holding `text`, keeping what outlives
/// it in a database in memory (core/Db.zig).
pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile(text);
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -75,7 +75,7 @@ pub const Session = struct {
/// A session showing one file pane, its startup file `init` (as
/// `~/.config/pardes/init` is read) applied first.
pub fn initStartup(gpa: std.mem.Allocator, init: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile("x\n");
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -85,7 +85,7 @@ pub const Session = struct {
/// A session showing its terminal pane, as `pardes` starts.
pub fn initTerm(gpa: std.mem.Allocator) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
@@ -99,7 +99,7 @@ pub const Session = struct {
var arena: std.heap.ArenaAllocator = .init(gpa);
errdefer arena.deinit();
const config = try std.fmt.allocPrint(arena.allocator(), "DumpDir {s}\n", .{dir});
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config, .tape = recording });
var s: Session = .{ .core = p, .arena = arena };
s.drain();
return s;
@@ -206,12 +206,16 @@ pub const Session = struct {
s.drain();
}
+ /// The tape `recordTape` started: every session made after it records on it.
+ var recording: ?*pardes.tape.Tape = null;
+
/// Every session started from here on records what it consumes as a
/// tape in memory, as PARDES_RECORD has a real one record it
/// (core/tape.zig); `replayTape` replays it once the session is gone.
pub fn recordTape(gpa: std.mem.Allocator) !void {
const t = try gpa.create(pardes.tape.Tape);
t.* = pardes.tape.memory(gpa);
+ recording = t;
pardes.tape.on = t;
}
@@ -221,7 +225,8 @@ pub const Session = struct {
/// its end loaded to its digest and dumped to its bytes again. False
/// when a replica diverged (said on stderr). After `deinit`.
pub fn replayTape(gpa: std.mem.Allocator) bool {
- const t = pardes.tape.on orelse return true;
+ const t = recording orelse return true;
+ recording = null;
pardes.tape.on = null;
defer {
pardes.tape.release(t);