diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-22 16:50:34 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-22 16:53:19 -0300 |
| commit | 9863a63b614d200852853825031189364dcacfdc (patch) | |
| tree | d235648a2ac14b3e311746ced3433ed6865e2061 /test | |
| parent | 6544f73a6b50e5ba68564beea7784593bb54348e (diff) | |
| parent | bad506bd45846e012246a33b5d3097b3e92f02bc (diff) | |
| download | pardes-9863a63b614d200852853825031189364dcacfdc.tar.gz pardes-9863a63b614d200852853825031189364dcacfdc.zip | |
integration: the old road deleted and the emulator's boundary on the gathered line: pardes-merge56 (`qvwrwxtu`: the installed tree and the source view's changes to their last slice) and pardes-term-join-9 (`twssqzqw`, fourteen changes on pardes-merge55: every client's terminals by the pty's bytes and nothing else: the delta protocol, its flow control and core/term/screen_state.zig deleted (-3,605 +504 lines), the wire at 30, one soak; S1: abi/term.zig's Ops in replicated and local, the terminal's digest covering what a step reads, every call of the core's into a terminal listed with its rule as a test; a client's own join again judged after its goodbye; a pty's size one fact the core hands its host for every fork, adopt and resize; a closed view sizes no terminal); no textual conflict; one semantic one, resolved here: core/jj.zig's Churn test (the layers' last round) called Authority.init and Replica.init with the road's flag the deletion took away: the argument removed; core-test 916/1073 (157 skipped), shell-test 1115/1118; its gate: .scratch/sketch/reorg/merge57, the numbers in PARDES.md (2026-11-22)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'test')
| -rw-r--r-- | test/daemon.py | 179 | ||||
| -rw-r--r-- | test/panes.zig | 30 | ||||
| -rw-r--r-- | test/perf.zig | 4 | ||||
| -rw-r--r-- | test/process.zig | 5 | ||||
| -rw-r--r-- | test/process/terminals.zig | 93 | ||||
| -rw-r--r-- | test/replicas.zig | 553 | ||||
| -rw-r--r-- | test/rollback_bench.zig | 2 | ||||
| -rw-r--r-- | test/terminal.zig | 95 |
8 files changed, 355 insertions, 606 deletions
diff --git a/test/daemon.py b/test/daemon.py index 2e666ad1..55cffaf4 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -69,12 +69,6 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from ninep import Client # noqa: E402 -# The caller's PARDES_* is dropped (a session of the user's), these kept: a -# road for every session the run starts (PARDES_TERM_SCREEN: its terminals to -# its clients as screen state, the way back). -KEEP = ('PARDES_TERM_SCREEN',) - - def wait_for(what, check, timeout=10): deadline = time.monotonic() + timeout while True: @@ -108,13 +102,15 @@ class Term: try: if not select.select([self.master], [], [], 0.05)[0]: continue - got = os.read(self.master, 65536) + # Read and kept in one hold of the lock: `last` counts what + # waits on the master under it. + with self.lock: + got = os.read(self.master, 65536) + self.out += got except OSError: return if not got: return - with self.lock: - self.out += got # A request split across two reads is answered too. seen, self.tail = self.tail + got, got[-3:] if b'\x1b[5n' in seen: @@ -133,6 +129,23 @@ class Term: with self.lock: return bytes(self.out) + def last(self): + """Its text once what was written to it is read, for a read after + its writer ended (or wrote its last before an event seen + elsewhere): the reader may not have the last bytes yet (it reads + every 50 ms, later under load). Nothing waiting on the master and + nothing more read for 0.1 s.""" + quiet = None + def done(): + nonlocal quiet + with self.lock: + now = (struct.unpack('i', fcntl.ioctl(self.master, termios.FIONREAD, b'\0\0\0\0'))[0], len(self.out)) + if now[0] or quiet is None or quiet[0] != now: + quiet = (now, time.monotonic()) + return time.monotonic() - quiet[1] >= .1 + wait_for('the terminal\'s last bytes read', done) + return self.text() + def close(self): self.closing = True self.reader.join(timeout=2) @@ -263,7 +276,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 = 29 + WIRE = 30 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout @@ -319,13 +332,13 @@ class Replica: return 'refused', why def ping(self, value): - """One round trip, in ms (the session's units and terminal - messages on the way are passed over).""" + """One round trip, in ms (the session's units on the way are + passed over).""" t = time.monotonic() self.send(0x03, struct.pack('<Q', value)) while True: tag, body = self.read() - if tag not in (0x05, 0x06): + if tag != 0x05: break assert (tag, body) == (0x03, struct.pack('<Q', value)), (tag, body) return (time.monotonic() - t) * 1000 @@ -441,7 +454,7 @@ def clients(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -529,7 +542,7 @@ def clients(binary): # Detach typed in it: it alone goes, and says so (exit 0). os.write(ta.master, b' sD') wait_for('client A let go', lambda: a.poll() is not None, timeout=10) - assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-300:] + assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.last(), ta.last()[-300:] # A third client, a shell: its keys wait for the session (a pty # write), its output comes back in units, the same on both sides. nine.write(f'/pane/{pane}/exec', b'Term\n') @@ -583,7 +596,7 @@ def launch(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -651,7 +664,7 @@ def pair(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -725,7 +738,7 @@ def pair_rows(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -915,7 +928,7 @@ def attach_upgrading(binary, rounds=6, dump=True): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1002,11 +1015,11 @@ def kept_views(binary): nobody types in: a `new --detach` session at its four views (a client attached, idle; raw replicas), two of them leaving to join again and never coming back; a join at once is refused and told for how long, one - 31 s later, nothing typed in between, is welcomed.""" + a second past that, nothing typed in between, is welcomed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1029,15 +1042,29 @@ def kept_views(binary): for r in rs[:2]: r.send(0x02, b'\x01') r.close() - left = time.monotonic() - said = Replica(sock).hello('kv', build) - assert said[0] == 'refused' and re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]), said - print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}"') - time.sleep(max(0, left + 31 - time.monotonic())) + + # The goodbyes reach the session on their own connections and the + # next join through the daemon, in no order between them: a join + # judged before the session took them is refused with no view kept + # yet. Dialled again until a refusal says one is. + dials = 0 + + def refused(): + nonlocal dials + dials += 1 + r = Replica(sock) + said = r.hello('kv', build) + r.close() + assert said[0] == 'refused' and 'as many views as it takes' in said[1], said + kept = re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]) + return kept and (said, int(kept.group(1)), time.monotonic()) + said, more, at = wait_for('a join refused, a view kept', refused) + print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}" ({dials} dials)') + time.sleep(max(0, at + more + 1 - time.monotonic())) said = Replica(sock).hello('kv', build) - assert said[0] == 'welcome', ('a view kept 31 s in an idle session, still kept', said) + assert said[0] == 'welcome', ('a view kept past what its refusal said in an idle session, still kept', more, said) assert a.poll() is None - print('kept views: a join 31 s after, nothing typed in between, took a kept view') + print(f'kept views: a join {more + 1} s after, nothing typed in between, took a kept view') a.terminate() a.wait(timeout=20) assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0 @@ -1064,7 +1091,7 @@ def pair_upgrade_views(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1170,7 +1197,7 @@ def pair_exec_reaps(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1234,7 +1261,7 @@ def far_exec(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1300,7 +1327,7 @@ def pair_window_geometry(gui_binary, new_gui): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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', SDL_VIDEO_DRIVER='offscreen') @@ -1372,7 +1399,7 @@ def manage(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1476,7 +1503,7 @@ def relink(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1582,7 +1609,7 @@ def answer_late(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1700,7 +1727,7 @@ def pdf_window(binary, gui_binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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') env.pop('XDG_DATA_HOME', None) @@ -1766,7 +1793,7 @@ def window_clients(binary, gui_binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -1988,7 +2015,7 @@ def far(binary): scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch)) cache = root / 'cache' - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') @@ -2147,15 +2174,18 @@ def far(binary): def far_flood(binary): """A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py: - 200 ms each way, 20 KB/s) while the session's shell runs `yes`: once - `yes` ends it agrees with the session, and its keys after go in. It - pulls its terminal's screen (screen state), so the flood does not - queue for it: it keeps up without joining again (two runs, 2026-11-20), - and replica.behind_max_ms is not reached this way.""" + 200 ms each way, 20 KB/s) while the session's shell runs `yes`. Its + terminal is the pty's bytes in the session's units, so the flood queues + for it: it falls behind, past replica.behind_max_ms its link is let go + (`Link.lags`), and it joins again from a dump, saying so on its notice + line ("joined again: N s behind") until a key. Once `yes` ends it agrees + with the session, and its keys after go in. The shape is asserted, not + the times: a link ended before its last (a line of + PARDES_REPLICA_STATS a link), the notice, the agreement.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') @@ -2184,16 +2214,21 @@ def far_flood(binary): started.append(relay.pid) wait_for('the relay', (root / 'relay.sock').exists) check = root / 'f.check' + stats = root / 'f.stats' t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'], - dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check))) + dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) + # Queued behind the flood, let go for its lag, joined again from a + # dump: a link of its ended (its stats line), and its notice says why. + assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) + wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) seen = len(checks(check)) @@ -2201,14 +2236,33 @@ def far_flood(binary): # Its keys go to the shell: its terminal hangs up instead. c.send_signal(signal.SIGHUP) c.wait(timeout=10) - print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` agreed once it ended ' - f'({len(checks(check))} checks) and its keys went in') + print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` was let go for its lag and ' + f'joined again ({len(joins(stats))} links), agreed once it ended ({len(checks(check))} checks) and its keys went in') relay.kill() relay.wait() exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) + except BaseException: + # Its evidence kept, the root going: the far client's checks and + # stats, its terminal, and where each process's threads wait. + kept = Path(tempfile.mkdtemp(prefix='fl-kept-', dir=scratch)) + for f in ('f.check', 'f.stats'): + if (root / f).exists(): + shutil.copy(root / f, kept) + for i, term in enumerate(terms): + (kept / f'term-{i}.out').write_bytes(term.text()) + with open(kept / 'threads', 'w') as out: + for pid in started: + out.write(f'{pid} {cmdline(pid)[:3]} alive={alive(pid)}\n') + for task in sorted(Path(f'/proc/{pid}/task').glob('*')) if procfs and alive(pid) else []: + try: + out.write(f' {task.name} {(task / "comm").read_text().strip()} {(task / "wchan").read_text()}\n') + except OSError: + pass + print(f'far flood: kept {kept}', file=sys.stderr) + raise finally: for term in terms: term.close() @@ -2230,7 +2284,7 @@ def by_hash(binary): scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch)) cache = root / 'cache' - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2316,7 +2370,7 @@ def games(binary, libs, secs=10): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -2427,7 +2481,7 @@ def far_find(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -2494,7 +2548,7 @@ def restore_client(binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -2621,14 +2675,14 @@ def cpu_ticks(pid): def kitty_image(binary, secs=5): - """A plain attach (screen state) watching a terminal in which a program + """A plain attach watching a terminal in which a program shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it agrees with its session and does not join again (it joined again ~3.3 times a second: the tag said ` petscii:on` on the session's side only).""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ri-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -2689,7 +2743,7 @@ def main(binary, cycles): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -2859,7 +2913,7 @@ def main(binary, cycles): os.kill(stub, signal.SIGKILL) wait_for('the stub gone', lambda: not alive(stub)) wait_for('the session detached from its killed stub', lambda: sized(client)) - assert b'\x1b[?1049l' in term.text()[drawn:], 'the terminal is put back' + assert b'\x1b[?1049l' in term.last()[drawn:], 'the terminal is put back' assert alive(session) shell.kill() shell.wait(timeout=10) @@ -2887,7 +2941,7 @@ def main(binary, cycles): # the daemon go. exit_session(client, pane) assert stub.wait(timeout=10) == 0, stub.returncode - assert b'let this client go' not in term.text(), term.text()[-300:] + assert b'let this client go' not in term.last(), term.last()[-300:] client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) @@ -2923,7 +2977,7 @@ def gui(binary, cycles): 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_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} (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'), @@ -3018,7 +3072,7 @@ def gui_pair(gui_binary): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -3189,7 +3243,7 @@ def upgrades(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rtu-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -3271,7 +3325,8 @@ def upgrades(old, new): replica.close() stale.wait(timeout=30) # (Across a change of the replica protocol, it says that instead.) - assert b'upgrade this client too' in term3.text() or b'run the same pardes at both ends' in term3.text(), term3.text()[-400:] + said = term3.last() + assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] term3.close() print('upgrade: a replica client of the old build was let go, dialled again and was told to upgrade too') # The old image's prompt files swept, the new one's made. @@ -3498,7 +3553,7 @@ def upgrade_clients(old, new): 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_') or k in KEEP) and 'PAGER' not in k} + 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) @@ -3600,7 +3655,7 @@ def gui_upgrades(old, new): another build.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + 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 diff --git a/test/panes.zig b/test/panes.zig index 38eb0a71..32cfd530 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -3775,9 +3775,9 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); - const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const Land = struct { a: *R.Authority, @@ -3839,7 +3839,7 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); const Land = struct { a: *R.Authority, @@ -3875,7 +3875,7 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); const Land = struct { a: *R.Authority, @@ -3937,9 +3937,9 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); - const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const Land = struct { a: *R.Authority, @@ -3974,7 +3974,7 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); const Land = struct { a: *R.Authority, @@ -3998,10 +3998,10 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); // A terminal's client on the session's view, a window's on its own. - const tty = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const tty = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer tty.deinit(); const Land = struct { a: *R.Authority, @@ -4175,9 +4175,9 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); - const win = try R.Replica.init(gpa, 2, try a.unit(0, 0), false); + const win = try R.Replica.init(gpa, 2, try a.unit(0, 0)); defer win.deinit(); const land = struct { a: *R.Authority, @@ -4262,9 +4262,9 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); - const win = try R.Replica.init(gpa, 2, try a.unit(0, 0), false); + const win = try R.Replica.init(gpa, 2, try a.unit(0, 0)); defer win.deinit(); const c = try clientOf(a, win, .{ .frontend = .{ .windowed = false, .native_images = false } }); try (Confirmed{ .a = a, .r = win }).step(.tick); @@ -4298,9 +4298,9 @@ const PdfAddon = struct { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }); defer a.deinit(); - const win = try R.Replica.init(gpa, 2, try a.unit(0, 0), false); + const win = try R.Replica.init(gpa, 2, try a.unit(0, 0)); defer win.deinit(); const c = try clientOf(a, win, .{ .frontend = .{ .windowed = true, .native_images = true } }); // The client's click in the PDF: its pane the client's own view's. diff --git a/test/perf.zig b/test/perf.zig index 8c88ef01..e9ee43d7 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -702,9 +702,9 @@ fn measureClient(op: Op, path: []const u8, reps: usize) !Cell { const warmup = 3; const samples = try gpa.alloc(u64, reps); defer gpa.free(samples); - const a = try pardes.replica.Authority.init(gpa, .{ .tty_only = true, .file = path, .cols = screen_cols, .rows = screen_rows }, .{ .vtable = &client_host_vtable }, false); + const a = try pardes.replica.Authority.init(gpa, .{ .tty_only = true, .file = path, .cols = screen_cols, .rows = screen_rows }, .{ .vtable = &client_host_vtable }); defer a.deinit(); - const r = try pardes.replica.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try pardes.replica.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); // Idle first, as a client is: its copy taken ahead and a pump's unit of // the session's kept over it. Two units kept a key after that put the diff --git a/test/process.zig b/test/process.zig index a1647ff1..791a5b8e 100644 --- a/test/process.zig +++ b/test/process.zig @@ -945,9 +945,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; - // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`); - // PARDES_TERM_SCREEN, their terminals as screen state. - if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=") and !std.mem.startsWith(u8, entry, "PARDES_TERM_SCREEN=")) 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 d9c3bcca..151b221b 100644 --- a/test/process/terminals.zig +++ b/test/process/terminals.zig @@ -16,6 +16,7 @@ pub const cases = .{ .{ "terminals: a program's prompt shows and holds still, input sent unsubmitted shows, and ^U takes the screen back to what it was", prompt }, .{ "terminals: what a program prints past a screenful stays in the terminal's body, and its prompt after it shows", history }, .{ "terminals: a control byte through pty/data reaches a program in raw mode, which then carries on", rawKey }, + .{ "terminals: a shell started into a pane runs at the pane's grid, not the screen's: a new terminal, its shell started again by pty/ctl's exec, a finished command pane run again", sizedFork }, }; fn has(hay: []const u8, needle: []const u8) bool { @@ -78,6 +79,98 @@ const Other = struct { } }; +/// What `stty size` in terminal `term` says, beside the grid its pty/ctl +/// reads back, each as "rows cols". +fn sttySize(a: std.mem.Allocator, c: *process.Conn, term: u32) ![2][]const u8 { + var lines = std.mem.splitScalar(u8, try run(a, c, term, "stty size\n"), '\n'); + _ = lines.next(); + return .{ lines.next() orelse "", try grid(a, c, term) }; +} + +/// Pane `n`'s grid, as pty/ctl reads it back ("winsize C R"): "rows cols". +fn grid(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const u8 { + var w = std.mem.tokenizeAny(u8, try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/pty/ctl", .{n})), " \n"); + _ = w.next(); + const cols = w.next() orelse ""; + return std.fmt.allocPrint(a, "{s} {s}", .{ w.next() orelse "", cols }); +} + +/// The lines of pane `n`'s body that are two numbers (`stty size`'s). +fn sizeLines(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{n})), '\n'); + while (rows.next()) |row| { + var w = std.mem.tokenizeScalar(u8, std.mem.trim(u8, row, " \r"), ' '); + const r = w.next() orelse continue; + const k = w.next() orelse continue; + if (w.next() != null) continue; + _ = std.fmt.parseInt(u16, r, 10) catch continue; + _ = std.fmt.parseInt(u16, k, 10) catch continue; + try out.append(a, try std.fmt.allocPrint(a, "{s} {s}", .{ r, k })); + } + return out.items; +} + +/// A shell takes runs: its first prompt, or the one started again. +fn prompted(a: std.mem.Allocator, c: *process.Conn, term: u32) !void { + const deadline = eh.nowMs() + 10_000; + while (!std.mem.eql(u8, try run(a, c, term, "true\n"), "exit 0\n")) { + if (eh.nowMs() > deadline) return error.NoPrompt; + process.sleep(50); + } +} + +fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "sized", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const text = (try serials(a, c))[0]; + try c.write("/exec", "Shell bash\n"); + // A terminal beside the text: its grid is its rect less the tag, never + // the screen's 160x50. + try c.write("/exec", "Term\n"); + const term = try c.newest(gpa); + try prompted(a, c, term); + var got = try sttySize(a, c, term); + try expect(!std.mem.eql(u8, got[1], "50 160")); + try expectEqualStrings(got[1], got[0]); + // Its shell started again: the pane is sized already, and nothing + // resizes it after. + const pid = try run(a, c, term, "echo $$\n"); + try c.write(f.at("/pane/{d}/pty/ctl", .{term}), "exec\n"); + const again_by = eh.nowMs() + 10_000; + while (true) { + const now = run(a, c, term, "echo $$\n") catch ""; + if (std.mem.startsWith(u8, now, "exit 0\n") and !std.mem.eql(u8, now, pid)) break; + if (eh.nowMs() > again_by) return error.NeverStartedAgain; + process.sleep(50); + } + got = try sttySize(a, c, term); + try expectEqualStrings(got[1], got[0]); + // A command pane, then the same line again: the finished pane is run + // again (exec.zig `runCommand`), a pane sized already. (The new one is + // placed a step after its fork: its first size can be the screen's.) + try c.exec(text, "stty size"); + var words = std.mem.tokenizeAny(u8, try c.pane(a, text, "exec"), " \n"); + var last: []const u8 = ""; + while (words.next()) |w| last = w; + const cmd = try std.fmt.parseInt(u32, last, 10); + for (1..3) |k| { + if (k == 2) try c.exec(text, "stty size"); + const by = eh.nowMs() + 10_000; + while ((try sizeLines(a, c, cmd)).len < k) { + if (eh.nowMs() > by) return error.NoSize; + process.sleep(50); + } + if (k == 2) try expectEqualStrings(try grid(a, c, cmd), (try sizeLines(a, c, cmd))[1]); + } +} + fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var d = try process.Detached.start(gpa, exe, "run", .{}); defer d.deinit(); diff --git a/test/replicas.zig b/test/replicas.zig index 48eaa857..90f7c10d 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -12,39 +12,34 @@ //! and joins again for its view, and those past the views a session has //! are refused until one is let go. //! -//! Terminals cross as screen state (core/term/screen_state.zig): the session's -//! shell pane runs a full-screen program and then a flood (`--flood` MB of -//! `yes`, then as much of a `cat` of source text) while the clients type, its output stepped by the authority -//! and sent to each replica as deltas, once a frame and before any input -//! the authority steps, each replica acknowledging them over its link and -//! asking for the rows it scrolls back into and does not hold. +//! Terminals cross as the pty's bytes in the session's units: the +//! session's shell pane runs a full-screen program and then a flood +//! (`--flood` MB of `yes`, then as much of a `cat` of source text) while the +//! clients type, and each client feeds its own emulators what its units +//! carry, in the tape's order. //! //! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] //! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K] -//! zig build replicas -Dplatform=tui -Doptimize=ReleaseFast -- --screen-state <dir> //! //! `--echo` types a corpus into a shell instead, with and without the //! predicted echo (core/term/echo.zig), and gates what it draws: below, at -//! "predicted echo". `--screen-state` runs recorded pty streams through -//! screen_state's soak and measures its encoder: below, at screenState. +//! "predicted echo". //! //! Gates, per seed and RTT: no replica diverges (every confirmed unit's //! digests agree as it is replayed), and at quiescence every replica's -//! digest and every file's text are the authority's; every delta a replica applies leaves its -//! terminal what the authority's was at that version, and at quiescence it -//! is the authority's, cell for cell. Reported per RTT: how inputs went +//! digest and every file's text are the authority's, and every terminal +//! the authority's, cell for cell. Reported per RTT: how inputs went //! (applied at once, stopped at a host call, left to the authority), how //! units were taken (fast path, rollback for a misprediction or another's //! input), what a speculative apply, a copy and a rollback cost against a -//! frame, and the terminals': deltas a second, wire bytes a second under -//! the flood, encode a frame (every peer), apply a delta. +//! frame, and a peer's unit bytes a second under the flood. const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; const client_loop = @import("runtime").client; const session_loop = @import("runtime").session; -const screen_state = @import("term").screen_state; +const term = @import("term"); const Echo = pardes.Echo; const Key = pardes.Key; @@ -53,10 +48,6 @@ const gpa = std.heap.c_allocator; pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; -/// `--bytes`: its clients are replicas of the bytes kind, each terminal fed -/// the pty's bytes its units carry into an emulator of its own, joined from -/// a dump with every emulator whole (core/replica.zig `Peers.bytes`). -var bytes_kind = false; /// `--witness`: the witness judged at every run's end, not only after a /// divergence (`Witness`). var witness_always = false; @@ -157,8 +148,6 @@ const Kind = enum { echo, frame, output, - screen_down, - screen_up, client_frame, /// The session's own frontend's input, in its own view. own, @@ -247,25 +236,12 @@ const Totals = struct { copy_ns: std.ArrayListUnmanaged(u64) = .empty, rollback_ns: std.ArrayListUnmanaged(u64) = .empty, // Terminals. - apply_ns: std.ArrayListUnmanaged(u64) = .empty, - frame_ns: std.ArrayListUnmanaged(u64) = .empty, - deltas: u64 = 0, - delta_bytes: u64 = 0, unit_bytes: u64 = 0, - /// 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, - /// Bytes of rows sent before a step's unit, the step having read them. - filled_bytes: u64 = 0, - resets: u64 = 0, - screens_wrong: u64 = 0, - screens_checked: u64 = 0, /// Joins from a dump, refused, again after a divergence put on it /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. joins: u64 = 0, @@ -322,7 +298,6 @@ const Totals = struct { try t.spec_ns.appendSlice(gpa, s.spec_ns.items); try t.copy_ns.appendSlice(gpa, s.copy_ns.items); try t.rollback_ns.appendSlice(gpa, s.rollback_ns.items); - try t.apply_ns.appendSlice(gpa, s.apply_ns.items); } }; @@ -464,21 +439,11 @@ fn writeText(path: [:0]const u8, text: []const u8) !void { const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, flood_mb: u64 }; -/// The terminal pane's screen as a hash of screen_state's dump of it. -/// The module's own replica behind the core's handle (Replica.screens). -fn replicaOf(r: *pardes.Term.Replica) *screen_state.Replica { - return @ptrCast(@alignCast(r)); -} - -/// The module's own track behind the core's handle (Screens.tracks). -fn trackOf(t: *pardes.Term.Track) *screen_state.Track { - return @ptrCast(@alignCast(t)); -} - -fn screenHash(t: *screen_state.Terminal) u64 { +/// The terminal pane's screen as a hash of a dump of its cells. +fn screenHash(t: anytype) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); - screen_state.dumpScreen(t, &h.writer) catch {}; + term.terminal.dumpScreen(t, &h.writer) catch {}; h.writer.flush() catch {}; return h.hasher.final(); } @@ -1019,10 +984,7 @@ const Witness = struct { // No client's id: every unit is another's. const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); rp.guess = false; - if (bytes_kind) { - rp.t.screen_state = false; - rp.core().echo = null; - } + rp.core().echo = null; rp.t.local_files = true; return rp; } @@ -1225,19 +1187,12 @@ const Soak = struct { frames_left: u32 = 0, flood_end: u64 = 0, program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}, - /// The session's version of each terminal, as its screen showed then. - versions: std.AutoHashMapUnmanaged(u64, u64) = .empty, - flood_deltas: [8]u64 = @splat(0), kinds_seen: u32 = 0, /// Each client's link made (its first join), and its replica's. has_link: [8]bool = @splat(false), /// An input of its own frontend's held for the next wait, a pty's /// output taken in this one (tui.zig `split`). held: ?Msg = null, - /// The step boundary after a frame's wake under the flood: what its - /// encoding cost. - framed: bool = false, - encode_ns: u64 = 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. @@ -1340,8 +1295,6 @@ const Soak = struct { pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; - l.peers.bytes = bytes_kind; - l.peers.flushed = .{ .ctx = s, .f = flushed }; const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; l.core.host = host; return host; @@ -1368,7 +1321,6 @@ const Soak = struct { if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); for (s.echo.items) |e| gpa.free(e.bytes); s.echo.deinit(gpa); - s.versions.deinit(gpa); } /// The tty's own boot (a raw shell, a text pane under it), then three @@ -1409,7 +1361,7 @@ const Soak = struct { 2 => 1_200_000, // One joins in the middle of the flood, its emulators loaded // whole and every other side's reloaded. - 3 => if (bytes_kind) flood_at + 100_000 else 2_300_000, + 3 => flood_at + 100_000, else => 2_000_000 + c * 100_000, }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); @@ -1511,7 +1463,7 @@ const Soak = struct { cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; - if (bytes_kind) Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); // never given the screen deltas, it checks no screen-state run + Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); }; // A Detach typed in a client's view, or one cut off for its lag: its @@ -1542,10 +1494,6 @@ const Soak = struct { }; for (s.echo.items) |e| try net.send(.{ .at = now + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); s.echo.clearRetainingCapacity(); - if (s.framed) { - s.framed = false; - if (now >= flood_at and (s.flood_end == 0 or now <= s.flood_end)) try s.totals.frame_ns.append(gpa, ps.screens.encode_ns - s.encode_ns); - } } /// The units the session queued for client `cl` since, their heads @@ -1610,14 +1558,6 @@ const Soak = struct { if (flooding) s.totals.flood_unit_bytes += f.payload.len; try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); }, - .screen => { - if (f.payload[5] == 1) { - s.totals.deltas += 1; - s.totals.delta_bytes += f.payload.len; - if (flooding) s.totals.flood_delta_bytes += f.payload.len; - } else s.totals.filled_bytes += f.payload.len; - try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); - }, .check => { const d = try gpa.alloc(u8, 8); std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); @@ -1644,20 +1584,6 @@ const Soak = struct { try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); } - /// Each terminal at its version as the session's screen shows it now - /// (after a flush: `Peers.flushed`). - fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { - const s: *Soak = @ptrCast(@alignCast(ctx)); - for (&screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; - if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue; - _ = core.panes[id] orelse continue; - s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)) catch |err| { - s.err = err; - }; - }; - } - pub fn upgradeAsked(_: *Soak) void {} pub fn restoring(_: *Soak, _: *pardes.Pardes) void {} pub fn restored(_: *Soak, _: *SessionLoop) void {} @@ -1672,8 +1598,8 @@ const Soak = struct { fn wait(s: *Soak, timeout_ms: u32) !bool { const core = s.l.core; const net = s.net; - // An input of its own held while a pty's output was taken: the step - // after reads the terminal as the clients' deltas bring it. + // An input of its own held while a pty's output was taken: its step + // comes after that output's. if (s.held) |m| { s.held = null; try s.own(m); @@ -1713,7 +1639,7 @@ const Soak = struct { // tape is stepped in it between its steps (tape.enter's check), // and no rollback epoch's trees are held. const in_client = switch (m.kind) { - .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => true, + .refused, .dump, .input, .to_replica, .checked, .blob, .wake, .quit, .gone, .word => true, .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), else => false, }; @@ -1777,11 +1703,7 @@ const Soak = struct { const busy = s.typing > 0 or s.flood_end == 0; s.frames_left = if (busy) 120 else s.frames_left -| 1; if (s.frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); - if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) { - s.framed = true; - s.encode_ns = s.l.peers.screens.encode_ns; - return false; - } + if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) return false; }, // Room in the far link: its Peer's writer goes on. .drain => { @@ -1812,8 +1734,6 @@ const Soak = struct { if (m.gen != cl.gen or cl.read_done or cl.shut) continue; const f = (try pardes.wire.framed(m.bytes)) orelse return error.BadFrame; if (ending and f.tag == @backingInt(pardes.wire.ClientTag.check)) continue; - if (f.tag == @backingInt(pardes.wire.ClientTag.screen_ack) and f.payload.len >= 22 and f.payload[5] == 2) - s.totals.fetched += std.mem.readInt(u64, f.payload[14..22], .little) - std.mem.readInt(u64, f.payload[6..14], .little); if (!peer.take(f.tag, f.payload)) { cl.read_done = true; s.l.peers.post(.{ .gone = peer }); @@ -1884,7 +1804,7 @@ const Soak = struct { } }, .dump => try s.joined(cl, c, m), - .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => { + .input, .to_replica, .checked, .blob, .wake, .quit, .gone, .word => { if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1931,26 +1851,6 @@ const Soak = struct { }, .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), - .screen_down => { - const pane = m.bytes[0]; - const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; - cl.loop.take(.{ .screen = try std.heap.c_allocator.dupe(u8, m.bytes) }); - if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { - const now_seq = replicaOf(sc.rep).seq; - if (now_seq == was) s.totals.resets += 1 else { - // Applied: the screen is the session's at that version. - s.totals.screens_checked += 1; - const want = s.versions.get(@as(u64, sc.serial) << 32 | now_seq); - const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; - if (want == null or want.? != screenHash(vt)) { - s.totals.screens_wrong += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the session's\n", .{ s.r.seed, s.r.rtt_ms, m.who, pane, now_seq }); - } - // Deltas while the flood runs (an RTT/2 behind it). - if (m.at >= flood_at + net.one_way and (s.flood_end == 0 or m.at <= s.flood_end + net.one_way)) s.flood_deltas[c] += 1; - } - }; - }, .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), .wake => { // One the next replaced is no wake. @@ -1967,7 +1867,7 @@ const Soak = struct { try woke(cl, c, net, m.at, s.totals, s.r); if (cl.loop.link.quit) try ended(cl, c, net, m.at, s.totals, s.r, &s.typing); }, - .to_authority, .screen_up, .client_frame, .check_up, .bye_up => unreachable, + .to_authority, .client_frame, .check_up, .bye_up => unreachable, } } } @@ -2049,10 +1949,7 @@ const Soak = struct { } } // Its terminals its own emulators, fed what the units carry. - if (bytes_kind) { - rp.t.screen_state = false; - rp.core().echo = null; - } + rp.core().echo = null; rp.stats.samples = true; rp.t.local_files = true; rp.echo.now = m.at * 1000; @@ -2089,21 +1986,20 @@ const Soak = struct { const totals = s.totals; const core = s.l.core; totals.flood_us += s.flood_end -| flood_at; - for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); totals.cut += s.l.peers.cut; - 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.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + 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.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); - if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { + 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 {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 (&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; @@ -2227,22 +2123,22 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a // flood of `yes` and of a `cat`, read 4 KB at a time as a pty gives it. - const tui = try screen_state.tuiStream(gpa); + const tui = try tuiStream(); defer gpa.free(tui); - const session_only = try screen_state.shellStream(gpa); + const session_only = try shellStream(); defer gpa.free(session_only); - const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, if (bytes_kind) questions else "" }); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, questions }); defer gpa.free(shell_session); var media: Media = undefined; - const shown = if (bytes_kind) try images(dir, r.seed, &media) else ""; - defer if (bytes_kind) { + const shown = try images(dir, r.seed, &media); + defer { 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)); + } + const yes_only = try yesStream(@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); @@ -2365,6 +2261,56 @@ fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { /// `before`, then `n` bytes of what a `cat` of source text prints through a /// pty: this file's lines, CR LF after each, again and again. +/// A shell's: prompts marked (OSC 133), colours of the three kinds, wide +/// and combined graphemes, hyperlinks, tabs, a title and a directory, long +/// lines that wrap, and a clear (ED2, ED3) now and then. +fn shellStream() ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07"); + for (0..400) |i| { + try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i}); + try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 }); + try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i}); + if (i % 7 == 0) { + for (0..12) |_| try w.writeAll("a long line that wraps "); + try w.writeAll("\r\n"); + } + try w.writeAll("\x1b]133;D;0\x07"); + if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J"); + if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 }); + } + return out.toOwnedSlice(); +} + +/// A full-screen program's: the alternate screen and its modes, a status +/// line, a scrolling region scrolled both ways, lines inserted and +/// deleted, cursor shapes, the kitty keyboard pushed and popped. +fn tuiStream() ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J"); + for (0..300) |f| { + try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f}); + try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f }); + if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m"); + if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M"); + try w.writeAll("\x1b[r"); + try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 }); + if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q"); + } + try w.writeAll("\x1b[<u\x1b[?1049l\x1b[?25h\x1b[?1000l\x1b[0 qafter the program\r\n"); + return out.toOwnedSlice(); +} + +fn yesStream(lines: usize) ![]u8 { + const out = try gpa.alloc(u8, lines * 3); + for (0..lines) |i| @memcpy(out[i * 3 ..][0..3], "y\r\n"); + return out; +} + fn catAfter(before: []const u8, n: usize) ![]u8 { var out: std.ArrayListUnmanaged(u8) = .empty; errdefer out.deinit(gpa); @@ -2426,11 +2372,11 @@ fn diffCase(dir: []const u8) !bool { const look = try std.fmt.bufPrint(&lbuf, "Look {s}", .{patch}); var ok = true; for ([_]bool{ false, true }) |own| { - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first); defer rp.deinit(); if (own) { const msg = try gpa.dupe(u8, try rp.input(.{ .command = look })); @@ -2491,11 +2437,11 @@ fn plumbCase(dir: []const u8) !bool { const open = try std.fmt.bufPrint(&obuf, "Look {s}", .{notes}); var ok = true; for ([_][]const u8{ "Look https://ziglang.org", "Look 3f2a9c1" }) |look| for ([_]bool{ false, true }) |own| { - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first); defer rp.deinit(); rp.confirm(try a.local(.{ .command = open })); rp.settle(); @@ -2543,11 +2489,11 @@ fn plumbCase(dir: []const u8) !bool { // The rule from the session's plumbing file, read at boot. var pbuf: [256]u8 = undefined; try writeText(try std.fmt.bufPrintSentinel(&pbuf, "{s}/plumbing", .{dir}, 0), "type is text\ndata matches 'https://letters/.*'\nplumb to seemail\n\ninclude basic\n"); - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first); defer rp.deinit(); rp.confirm(try a.local(.{ .command = open })); rp.settle(); @@ -2590,48 +2536,8 @@ fn push(q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, m: Msg) !void { try q.push(gpa, mm); } -/// What each peer is owed of the terminals, onto its link (before the -/// authority steps an input, and once a frame); each version as the -/// authority's screen showed it. -fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *std.ArrayListUnmanaged([]u8), q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, now: u64, dl: []Link, rnd: std.Random, ow: u64, jt: u64, vs: *std.AutoHashMapUnmanaged(u64, u64), tot: *Totals) !void { - for (ps, 0..) |peer, c| { - list.clearRetainingCapacity(); - // Terminals alone cross: the view is not read. - try sc.flush(core, peer, list); - for (list.items) |bytes| { - tot.deltas += 1; - tot.delta_bytes += bytes.len; - try push(q, nn, .{ .at = dl[c].arrive(rnd, now, ow, jt), .n = 0, .kind = .screen_down, .who = @intCast(c + 1), .bytes = bytes }); - } - } - // Each version as the authority's screen showed it. - for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; - if (trackOf(tr.track).version == 0 or vs.contains(key)) continue; - _ = core.panes[id] orelse continue; - try vs.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)); - }; -} - -/// A unit of the authority's to every replica, down its link: first the -/// rows of its terminals its step read that a replica holds as holes. -fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void { - var rows: std.ArrayListUnmanaged([]u8) = .empty; - defer rows.deinit(gpa); - for (down, peers, 1..) |*l, peer, who| { - rows.clearRetainingCapacity(); - try screens.fill(core, peer, &rows); - for (rows.items) |bytes| { - totals.filled_bytes += bytes.len; - try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes }); - n.* += 1; - } - } - screens.filled(core); - // The sizes its steps gave terminals, after their rows (Peers.unit). - pardes.panes.resizeDeferred(core); - totals.unit_bytes += unit.len * down.len; - if (flooding) totals.flood_unit_bytes += unit.len * down.len; +/// A unit of the authority's to every replica, down its link. +fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64) !void { for (down, 1..) |*l, who| { try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .to_replica, .who = @intCast(who), .bytes = try gpa.dupe(u8, unit) }); n.* += 1; @@ -2647,8 +2553,8 @@ fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const // plain echo, no marks). Each key's echo comes back 2 ms after the authority // writes it, as a shell's. The client types at a typist's pace and in bursts; // each of its frames (60 Hz, a phase of its own) is what its screen shows: -// the predicted echo where it is drawn (core/term/echo.zig), the screen state -// under it. Per key the shell echoed at a prompt or in cat: the time from +// the predicted echo where it is drawn (core/term/echo.zig), its own +// emulator under it, fed the units' bytes. Per key the shell echoed at a prompt or in cat: the time from // the key to its character on that screen, with prediction and without. Per // key predicted: whether the authority's screen, right after its echo, // shows what was predicted where it was. Per key drawn wrong: its frames. @@ -2961,10 +2867,10 @@ const Typed = struct { pred: ?struct { x: u16, y: u16, cp: u21 } = null, pcur: ?struct { x: u16, y: u16 } = null, /// The shell's mode as it took the key; whether it printed anything for - /// it; the authority's version of the screen before that. + /// it; the authority's last unit before that (its echo is in a later one). mode: ?FakeShell.Mode = null, echoed: bool = false, - version_before: u32 = 0, + unit_before: u32 = 0, /// The authority's screen right after its echo: its cursor and the /// cursor's row; whether that is what was predicted. after: ?struct { x: u16, y: u16, row: [128]u21 } = null, @@ -2972,7 +2878,7 @@ const Typed = struct { /// Its prediction drawn: first, and in how many frames. first_visible: ?u64 = null, visible_frames: u32 = 0, - /// The screen state showing its echo, first. + /// The client's emulator showing its echo, first. seen: ?u64 = null, }; @@ -2994,7 +2900,6 @@ const EchoTotals = struct { alt_predicted: u64 = 0, divergences: u64 = 0, unequal: u64 = 0, - screens_wrong: u64 = 0, /// The replica's frame drawn while it shows a prediction (its core's /// render, the tty's and the GUI's), and the overlay's part of it (ns); /// cells drawn otherwise than predicted. @@ -3043,14 +2948,11 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } var sh: FakeShell = .{}; defer sh.out.deinit(gpa); - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host()); defer a.deinit(); - var screens: replica.Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const peers = [_]u16{peer}; - const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0), true); + const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0)); defer rp.deinit(); + rp.core().echo = &rp.echo; rp.echo.on = on; const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -3065,11 +2967,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { t.spec_ns.deinit(gpa); t.copy_ns.deinit(gpa); t.rollback_ns.deinit(gpa); - t.apply_ns.deinit(gpa); - t.frame_ns.deinit(gpa); } - var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty; - defer versions.deinit(gpa); var queue: std.PriorityQueue(Msg, void, Msg.order) = .empty; defer { while (queue.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); @@ -3080,8 +2978,8 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const jitter = one_way / 10; var up: [1]Link = @splat(.{}); var down: [1]Link = @splat(.{}); - var owed: std.ArrayListUnmanaged([]u8) = .empty; - defer owed.deinit(gpa); + // The last of the authority's own units the replica fed its emulator. + var fed: u32 = 0; // The shell's first prompt. sh.put(prompt_bytes); @@ -3131,12 +3029,11 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { if (next_step < corpus.steps.items.len) try push(&queue, &n, .{ .at = m.at + corpus.steps.items[next_step].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} }); }, .to_authority => { - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); - try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); host.current = (replica.parseInput(m.bytes) orelse return error.BadInput).seq; const unit = try a.take(m.bytes); host.current = 0; - try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); + try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter); for (host.writes.items) |w| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = shell, .bytes = w.bytes, .seq = w.seq }); host.writes.clearRetainingCapacity(); }, @@ -3145,7 +3042,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const state = a.core.panes[shell].?.terminal.?; if (ty) |k| { k.mode = sh.mode; - k.version_before = if (screens.tracks[shell]) |*tr| trackOf(tr.track).version else 0; + k.unit_before = a.seq; } sh.key(m.bytes); if (sh.out.items.len > 0) { @@ -3161,8 +3058,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } }, .frame => { - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); - try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; left[0] = if (busy) 60 else left[0] -| 1; if (left[0] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }) else periodic -= 1; @@ -3200,8 +3096,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } } }; - const applied = if (rp.screens[shell]) |sc| replicaOf(sc.rep).seq else 0; - for (typed.items) |*k| if (k.echoed and k.seen == null and applied > k.version_before) { + for (typed.items) |*k| if (k.echoed and k.seen == null and fed > k.unit_before) { k.seen = m.at; }; const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; @@ -3211,22 +3106,9 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .to_replica => { rp.confirm(m.bytes); rp.settle(); - }, - .screen_down => { - if (rp.screen(m.bytes)) |reply| { - const pane = m.bytes[0]; - if (reply[5] == 1) { - const sc = rp.screens[pane].?; - if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| { - if (want != screenHash(&pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt)) t.screens_wrong += 1; - } else t.screens_wrong += 1; - } - try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, reply) }); - } - if (rp.screenRequest()) |req| try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, req) }); - }, - .screen_up => { - if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); + if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0) { + fed = u.seq; + }; }, .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } @@ -3237,7 +3119,6 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { et.confirmed += s.confirmed; et.mispredicted += s.mispredicted; et.cursor_missed += s.cursor_missed; - et.screens_wrong += t.screens_wrong; for (typed.items) |k| { et.keys += 1; const sec = &et.sec[k.section]; @@ -3288,7 +3169,7 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { var draw_lines: std.ArrayList(u8) = .empty; defer draw_lines.deinit(gpa); std.debug.print("predicted echo: one client typing the corpus into a shell, {d} seeds a cell; from a key to its character on the client's screen (ms, frames at 60 Hz)\n", .{seeds}); - std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal screens-wrong\n", .{}); + std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal\n", .{}); var by_section: std.ArrayList(u8) = .empty; defer by_section.deinit(gpa); var off: [sections.len][2]u64 = undefined; @@ -3301,13 +3182,13 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { return @as(f64, @floatFromInt(us)) / 1000; } }.f; - std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7} {d:>13}\n", .{ + std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7}\n", .{ rtt, if (on) "on" else "off", et.keys, et.echo_keys, ms(pct(et.latency.items, 50)), ms(pct(et.latency.items, 90)), ms(pct(et.latency.items, 100)), et.predicted, et.unpredicted, et.right, et.wrong, et.confirmed, et.mispredicted, et.cursor_missed, et.wrong_shown, et.wrong_frames, et.wrong_max, et.secret_frames, et.alt_predicted, et.divergences, - et.unequal, et.screens_wrong, + et.unequal, }); for (&et.sec, &off, sections) |*x, *o, name| { const p50 = pct(x.latency.items, 50) / 1000; @@ -3319,7 +3200,7 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { try by_section.print(gpa, "{d:>4} {s:<14} {d:>5} {d:>9} {d:>7} {d:>4} -> {d:<4} {d:>4} -> {d:<4} {d:>12}\n", .{ rtt, name, x.keys, x.predicted, x.latency.items.len, o[0], p50, o[1], p90, x.wrong_frames }); } if (on) try draw_lines.print(gpa, "{d:>4} {d:>12} {d:>6}/{d:<6} {d:>5}/{d:<5} {d:>10}\n", .{ rtt, et.drawn_frames, pct(et.render_ns.items, 50) / 1000, pct(et.render_ns.items, 99) / 1000, pct(et.paint_ns.items, 50), pct(et.paint_ns.items, 99), et.paint_wrong }); - if (et.divergences > 0 or et.unequal > 0 or et.screens_wrong > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true; + if (et.divergences > 0 or et.unequal > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true; }; std.debug.print("by part of the corpus (all seeds): keys typed, predicted, echoed (the latency sample); key to its character on the screen, ms, without -> with; frames a wrong prediction was drawn\n rtt part keys predicted echoed p50 off/on p90 off/on drawn-wrong\n{s}", .{by_section.items}); std.debug.print("the client's frames drawn with a prediction shown: its render (us) and the overlay's part (ns); cells drawn otherwise than predicted\n rtt frames-drawn render p50/p99 paint p50/p99 drawn-wrong\n{s}", .{draw_lines.items}); @@ -3341,174 +3222,6 @@ fn pct(samples: []u64, p: usize) u64 { return samples[@min(samples.len - 1, samples.len * p / 100)]; } -/// `--screen-state <dir>`: every recorded pty stream in `dir` (a -/// `-<cols>x<rows>` in its name sizes it, 80x24 otherwise) through -/// screen_state's soak at three seeds, then the encode's cost and the bytes -/// floods put on the wire (numbers from a ReleaseFast build). -fn screenState(io: std.Io, dir_path: []const u8, w: *std.Io.Writer) !void { - var dir = try std.Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }); - defer dir.close(io); - var it = dir.iterate(); - var files: usize = 0; - var failed: usize = 0; - while (try it.next(io)) |entry| { - if (entry.kind != .file) continue; - const bytes = try dir.readFileAlloc(io, entry.name, gpa, .unlimited); - defer gpa.free(bytes); - var cols: u16 = 80; - var rows: u16 = 24; - if (std.mem.lastIndexOfScalar(u8, entry.name, '-')) |dash| { - const size = std.mem.sliceTo(entry.name[dash + 1 ..], '.'); - if (std.mem.indexOfScalar(u8, size, 'x')) |x| { - cols = std.fmt.parseInt(u16, size[0..x], 10) catch cols; - rows = std.fmt.parseInt(u16, size[x + 1 ..], 10) catch rows; - } - } - files += 1; - for (0..3) |seed| { - const st = screen_state.soak(gpa, io, bytes, cols, rows, 128 * 1024, seed, seed != 0) catch |err| { - try w.print("screen-state {s} seed {d}: {s}\n", .{ entry.name, seed, @errorName(err) }); - failed += 1; - continue; - }; - if (seed == 0) try w.print("screen-state {s} {d}x{d}: {d} bytes, {d} deltas ({d} lost, {d} refused, {d} in flight at most), {d} wire bytes, {d} history rows checked, {d} fetched\n", .{ entry.name, cols, rows, bytes.len, st.deltas, st.lost, st.refused, st.most_in_flight, st.bytes, st.history_checked, st.fetched }); - } - } - try w.print("screen-state corpus: {d} streams x 3 seeds, {d} failed\n", .{ files, failed }); - try w.flush(); - try encodeBench(io, w); -} - -fn encodeBench(io: std.Io, w: *std.Io.Writer) !void { - const t = try gpa.create(screen_state.Terminal); - defer gpa.destroy(t); - t.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 }); - defer t.deinit(gpa); - var stream = t.vtStream(); - defer stream.deinit(); - var enc: screen_state.Encoder = .init(gpa); - defer enc.deinit(); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - var line: [1024]u8 = undefined; - // A full 200x60 screen, every row new to the peer: each a blob. - var full: [200]u64 = undefined; - var same: [200]u64 = undefined; - var full_bytes: usize = 0; - var same_bytes: usize = 0; - var changes: u32 = 0; - for (&full, &same, 0..) |*f, *u, rep| { - for (0..60) |y| { - var lw: std.Io.Writer = .fixed(&line); - try lw.print("\x1b[{d};1H\x1b[0;3{d};4{d}m{d} {d} ", .{ y + 1, rep % 8, y % 8, rep, y }); - while (lw.end < 190) try lw.writeAll("\x1b[1mbold\x1b[22m text "); - stream.nextSlice(lw.buffered()); - } - changes += 1; - var tr: screen_state.Track = .init(gpa); - defer tr.deinit(gpa, t); - var peer: screen_state.Peer = .{}; - defer peer.deinit(gpa); - out.clearRetainingCapacity(); - var t0 = std.Io.Clock.awake.now(io).nanoseconds; - _ = try screen_state.encode(&enc, &tr, &peer, t, changes, "", &out.writer); - f.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0); - full_bytes = out.written().len; - // The same screen again as a new version: every row held. - out.clearRetainingCapacity(); - t0 = std.Io.Clock.awake.now(io).nanoseconds; - _ = try screen_state.encode(&enc, &tr, &peer, t, changes + 1, "", &out.writer); - u.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0); - same_bytes = out.written().len; - } - std.mem.sort(u64, &full, {}, std.sort.asc(u64)); - std.mem.sort(u64, &same, {}, std.sort.asc(u64)); - try w.print("screen-state encode 200x60, every row new: p50 {d} us p99 {d} us, {d} bytes\n", .{ full[100] / 1000, full[198] / 1000, full_bytes }); - try w.print("screen-state encode 200x60, nothing new: p50 {d} us p99 {d} us, {d} bytes\n", .{ same[100] / 1000, same[198] / 1000, same_bytes }); - try w.flush(); - - // Floods: a second of output as fast as ghostty takes it, a frame every - // 16 ms: one version, a delta for each peer (the same bytes for peers - // at the same base), each replica applying its own at once. Under the C - // allocator, as a replica's. - try floods(io, w); -} - -fn floods(io: std.Io, w: *std.Io.Writer) !void { - var enc: screen_state.Encoder = .init(gpa); - defer enc.deinit(); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - const yes = try screen_state.yesStream(gpa, 1 << 16); - defer gpa.free(yes); - const shell = try screen_state.shellStream(gpa); - defer gpa.free(shell); - for ([_]struct { name: []const u8, bytes: []const u8 }{ .{ .name = "yes", .bytes = yes }, .{ .name = "varied text", .bytes = shell } }) |flood| for ([_]usize{ 1, 3 }) |npeers| { - const a = try gpa.create(screen_state.Terminal); - defer gpa.destroy(a); - a.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 }); - defer a.deinit(gpa); - var as = a.vtStream(); - defer as.deinit(); - var tr: screen_state.Track = .init(gpa); - defer tr.deinit(gpa, a); - var peers: [3]screen_state.Peer = @splat(.{}); - var reps: [3]screen_state.Replica = @splat(.{}); - var bs: [3]screen_state.Terminal = undefined; - for (bs[0..npeers]) |*b| b.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 32 << 20 }); - defer for (bs[0..npeers], reps[0..npeers], peers[0..npeers]) |*b, *r, *peer| { - b.deinit(gpa); - r.deinit(gpa); - peer.deinit(gpa); - }; - var applies: std.ArrayList(u64) = .empty; - defer applies.deinit(gpa); - var frames: std.ArrayList(u64) = .empty; - defer frames.deinit(gpa); - const start = std.Io.Clock.awake.now(io).nanoseconds; - var next = start; - var fed: u64 = 0; - var deltas: u64 = 0; - var wire: u64 = 0; - var version: u32 = 0; - while (true) { - const now = std.Io.Clock.awake.now(io).nanoseconds; - if (now - start >= std.time.ns_per_s) break; - as.nextSlice(flood.bytes); - version += 1; - fed += flood.bytes.len; - if (now < next) continue; - next += 16 * std.time.ns_per_ms; - var frame_ns: u64 = 0; - for (peers[0..npeers], reps[0..npeers], bs[0..npeers]) |*peer, *rep, *b| { - out.clearRetainingCapacity(); - const e0 = std.Io.Clock.awake.now(io).nanoseconds; - if (!try screen_state.encode(&enc, &tr, peer, a, version, "", &out.writer)) continue; - frame_ns += @intCast(std.Io.Clock.awake.now(io).nanoseconds - e0); - const a0 = std.Io.Clock.awake.now(io).nanoseconds; - peer.ack((try rep.apply(gpa, io, b, out.written())).seq); - try applies.append(gpa, @intCast(std.Io.Clock.awake.now(io).nanoseconds - a0)); - deltas += 1; - wire += out.written().len; - } - try frames.append(gpa, frame_ns); - } - std.mem.sort(u64, applies.items, {}, std.sort.asc(u64)); - std.mem.sort(u64, frames.items, {}, std.sort.asc(u64)); - const p = struct { - fn at(s: []const u64, q: usize) u64 { - return if (s.len == 0) 0 else s[@min(s.len - 1, s.len * q / 100)] / 1000; - } - }.at; - try w.print("screen-state flood of {s}, {d} peer(s): {d} MB/s of output, {d} deltas/s a peer, {d} wire bytes/s a peer ({d} a delta); encode a frame, all peers: p50 {d} us p99 {d} us; apply a delta p50 {d} us p99 {d} us\n", .{ - flood.name, npeers, fed / 1_000_000, deltas / npeers, wire / npeers, - wire / @max(1, deltas), p(frames.items, 50), p(frames.items, 99), p(applies.items, 50), - p(applies.items, 99), - }); - }; - try w.flush(); -} - pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); // A loop that does not end names itself (`Watchdog`): its gdb, a child, @@ -3522,7 +3235,6 @@ pub fn main(init: std.process.Init) !void { var rtts: []const u64 = &.{ 30, 80, 207 }; var echo_mode = false; var flood_mb: u64 = 8; - var screen_dir: ?[]const u8 = null; var rtt_buf: [8]u64 = undefined; var addons: std.ArrayListUnmanaged([]const u8) = .empty; defer addons.deinit(gpa); @@ -3533,10 +3245,6 @@ pub fn main(init: std.process.Init) !void { echo_mode = true; continue; } - if (std.mem.eql(u8, name, "--bytes")) { - bytes_kind = true; - continue; - } if (std.mem.eql(u8, name, "--witness")) { witness_always = true; continue; @@ -3544,7 +3252,7 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { + if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { var whole: [libc.PATH_MAX]u8 = undefined; pdf_path = try init.arena.allocator().dupe(u8, std.mem.span(libc.realpath(try init.arena.allocator().dupeSentinel(u8, value, 0), &whole) orelse return error.NoPdf)); } else if (std.mem.eql(u8, name, "--rtt")) { @@ -3554,11 +3262,6 @@ pub fn main(init: std.process.Init) !void { rtts = rtt_buf[0..k]; } else return error.UnknownOption; } - if (screen_dir) |d| { - var buf: [4096]u8 = undefined; - var out = std.Io.File.stderr().writer(init.io, &buf); - return screenState(init.io, d, &out.interface); - } trace = libc.getenv("PARDES_REPLICA_TRACE") != null; if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff; var dir_buf: [256]u8 = undefined; @@ -3610,7 +3313,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; {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 }); + 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, @@ -3623,20 +3326,10 @@ pub fn main(init: std.process.Init) !void { }); const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6; - try term_lines.print(gpa, "{d:>4} {d:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>9} {d:>6} {d:>6}/{d:<6}\n", .{ + try term_lines.print(gpa, "{d:>4} {d:>9.0} {d:>9}\n", .{ rtt, - @as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)), - @as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), @as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), - pct(t.frame_ns.items, 50) / 1000, - pct(t.frame_ns.items, 99) / 1000, - pct(t.apply_ns.items, 50) / 1000, - pct(t.apply_ns.items, 99) / 1000, - t.fetched, - t.filled_bytes / 1024, - t.resets, - t.screens_checked, - t.screens_wrong, + t.unit_bytes >> 10, }); try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); @@ -3656,10 +3349,10 @@ pub fn main(init: std.process.Init) !void { // The far client shows the final screen in every run, and the near // ones never fall behind with it. if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; - if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true; + if (t.divergences > 0 or t.unequal > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } - std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); - std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items}); + std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{}); + std.debug.print(" rtt unit B/s units KB\n{s}", .{term_lines.items}); std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); @@ -3828,9 +3521,9 @@ fn corpusCase(dir: []const u8) !bool { defer own_host.shown.deinit(); var noop: Host = .{}; const options: pardes.Options = .{ .cols = 100, .rows = 22, .file = shapes }; - const a = try replica.Authority.init(gpa, options, own_host.host(), true); + const a = try replica.Authority.init(gpa, options, own_host.host()); defer a.deinit(); - const b = try replica.Authority.init(gpa, options, noop.host(), true); + const b = try replica.Authority.init(gpa, options, noop.host()); defer b.deinit(); noop.core = b.core; _ = try b.unit(0, 0); diff --git a/test/rollback_bench.zig b/test/rollback_bench.zig index 24203308..0d269327 100644 --- a/test/rollback_bench.zig +++ b/test/rollback_bench.zig @@ -140,7 +140,7 @@ fn digestBench(dir: []const u8, mb: usize) !void { } const vtable: pardes.Host.VTable = .{ .watched = watched }; }; - const a = try pardes.replica.Authority.init(gpa, .{ .cols = 120, .rows = 40, .file = path }, .{ .vtable = &NoHost.vtable }, true); + const a = try pardes.replica.Authority.init(gpa, .{ .cols = 120, .rows = 40, .file = path }, .{ .vtable = &NoHost.vtable }); defer a.deinit(); _ = try a.unit(0, 0); var unit_ns: [40]u64 = undefined; diff --git a/test/terminal.zig b/test/terminal.zig index ec050c7a..7e7106a1 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -1,6 +1,6 @@ //! The terminal through the core (docs/next-terminal.md, Phase 1): what -//! were core/term/terminal.zig's and screen_state.zig's tests of a terminal -//! pane, moved as they were. They boot a core and read the emulator behind +//! were core/term/terminal.zig's tests of a terminal pane, moved as they +//! were. They boot a core and read the emulator behind //! it, so they need both modules, which only a suite outside both has: //! pane-test's (test/panes.zig). The emulator's own tests stay in core/term/. const std = @import("std"); @@ -9,12 +9,6 @@ const plain = @import("plain"); const term = @import("term"); const ghostty_vt = @import("ghostty-vt"); const emu = term.terminal; -const screen_state = term.screen_state; -const Encoder = screen_state.Encoder; -const Track = screen_state.Track; -const Peer = screen_state.Peer; -const Replica = screen_state.Replica; -const encode = screen_state.encode; const Surface = pardes.Surface; const Pane = pardes.Pane; const FilterPalette = Term.FilterPalette; @@ -100,39 +94,6 @@ test "replay ownership is terminal-only and construction rolls back on allocatio try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); } -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawResize(buf, a, n, ra); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - self.child.rawFree(buf, a, ra); - } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try panes.createTerminal(gpa, 40, 12); - defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); - try std.testing.expect(of(pane.terminal.?).resize_to == null); -} - test "document construction allocates only the pane and has inert terminal defaults" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); const allocator = failing.allocator(); @@ -926,55 +887,3 @@ test "colors.xterm is the palette the emulator starts from, all 256" { for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); } -test "a replica's terminal pane draws as its authority's does" { - const testing = std.testing; - const gpa = testing.allocator; - const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer a.deinit(); - const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer b.deinit(); - while (a.nextEffect()) |_| {} - while (b.nextEffect()) |_| {} - var fa = std.heap.ArenaAllocator.init(gpa); - defer fa.deinit(); - var fb = std.heap.ArenaAllocator.init(gpa); - defer fb.deinit(); - // Laid out once, so both panes have their size before the first delta. - _ = try a.render(fa.allocator()); - _ = try b.render(fb.allocator()); - const ta = &of(a.panes[0].?.terminal.?).vt; - const tb = &of(b.panes[0].?.terminal.?).vt; - var enc: Encoder = .init(gpa); - defer enc.deinit(); - var peer: Peer = .{}; - defer peer.deinit(gpa); - var tr: Track = .init(gpa); - defer tr.deinit(gpa, ta); - var rep: Replica = .{}; - defer rep.deinit(gpa); - var delta: std.Io.Writer.Allocating = .init(gpa); - defer delta.deinit(); - var line: [256]u8 = undefined; - for (0..60) |i| { - const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 }); - a.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); - delta.clearRetainingCapacity(); - try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer)); - peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq); - b.needs_frame = true; - _ = fa.reset(.retain_capacity); - _ = fb.reset(.retain_capacity); - const sa = try a.render(fa.allocator()); - const sb = try b.render(fb.allocator()); - const r = a.view().rects[0]; - // The body: below the pane's tag row. - for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { - const ca = sa.at(@intCast(x), @intCast(y)); - const cb = sb.at(@intCast(x), @intCast(y)); - if (!ca.visuallyEqual(cb)) { - std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() }); - return error.ReplicaDrawsDifferently; - } - }; - } -} |
