diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-30 15:57:57 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-30 16:29:54 -0300 |
| commit | d667965902512147f976fbbf89cb1ee77d0a37d0 (patch) | |
| tree | f5f9ed32160edaf7e1db23a0b805253206f54cfb /test | |
| parent | d0ed8056ba90a12fa3bc40ccd8642ec4ae8d9cc0 (diff) | |
| download | pardes-d667965902512147f976fbbf89cb1ee77d0a37d0.tar.gz pardes-d667965902512147f976fbbf89cb1ee77d0a37d0.zip | |
test/cross_replay.py: a session that meets the host's failures (a Look of a fifo and of a directory, a Save into a file, a Restore of no dump, a stat and a read under /os) recorded by one build of pardes and replayed by others, its errors by name in the tape; --record and --replay alone, for the box; pardes-snap --replay-with (zig build replay -Dreplay-with=<pardes-gui>) replays every script's tape with another build too, whose replica that draws nothing must agree (a replica client draws none of its session's frames)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'test')
| -rw-r--r-- | test/cross_replay.py | 136 | ||||
| -rw-r--r-- | test/snapshot.zig | 27 |
2 files changed, 160 insertions, 3 deletions
diff --git a/test/cross_replay.py b/test/cross_replay.py new file mode 100644 index 00000000..2a4a7ae7 --- /dev/null +++ b/test/cross_replay.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""A session's tape recorded by one build of pardes and replayed by another +(docs/next-daemon.md, the remote bugs): a window's build replaying a +terminal's session, a terminal's build a window's, a Linux build a FreeBSD +one's. A replica of another build reads its session's units as this replay +reads the tape, so what the tape carries must mean the same to both. + + python3 -B test/cross_replay.py <recorder> <replayer>... + a session of <recorder> recorded here, replayed by it and by each + replayer (a pardes-gui records in a hidden window) + python3 -B test/cross_replay.py --record <recorder> <dir> + the session alone, its tapes left in <dir> (on the box, say) + python3 -B test/cross_replay.py --replay <replayer> <tape>... + each tape replayed alone + +The session meets the host's failures, whose errors cross by name: a Look +of a fifo (a read the host refuses) and of a directory, a stat and a read +under /os over 9P, a Save into a file as if it were a directory and a +Restore of a dump that is not there (errors the host reports, anyerrors). +""" +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from daemon import Window, alive, processes, wait_for # noqa: E402 +from ninep import Client # noqa: E402 + + +def record(binary, out): + """One session of `binary`, recording into `out`: its tapes' paths.""" + out = Path(out).resolve() + out.mkdir(parents=True, exist_ok=True) + # A short runtime directory: a socket's path holds 108 bytes at most. + root = Path(tempfile.mkdtemp(prefix='xr-', dir=os.environ.get('TMPDIR', '/tmp'))) + 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_STATE_HOME=str(root / 'state'), XDG_CACHE_HOME=str(root / 'cache'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/sh') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'a.txt').write_text('hello\n') + (root / 'dir').mkdir() + (root / 'dir' / 'b.txt').write_text('in a directory\n') + os.mkfifo(root / 'fifo') + # No `MessageLinger 0` (test/daemon.py's sessions have it): with it, now + # and then, a tape does not replay even by its own build, on main too + # (pane 0's message differs a step after a failure is said). + (root / 'config' / 'pardes' / 'init').write_text('') + stem = Path(binary).name + env['PARDES_RECORD'] = str(out / f'{stem}-') + window = 'gui' in stem + started = [] + win = None + try: + if window: + win = Window(root, 'rec', [binary, '--9p=xr', str(root / 'a.txt')], env) + started.append(win.pid) + else: + started.append(subprocess.Popen([binary, '--detach=xr', str(root / 'a.txt')], env=env, cwd=root, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True).pid) + sock = root / 'pardes-9p-xr.sock' + wait_for('the session\'s 9P socket', sock.exists, timeout=30) + with Client(sock) as c: + status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines()) + started.append(int(status['pid'])) + pane = next(int(row.split()[0]) for row in c.read('/index').splitlines() if row.split()[1] == b'text') + for line in (f'Look {root / "fifo"}', f'Look {root / "dir"}', f'Save {root / "a.txt" / "x"}', + f'Restore {root / "nothing.dump"}'): + try: + c.write(f'/pane/{pane}/exec', line.encode() + b'\n') + except Exception: + pass # said as the write's error: a failure is what is wanted + time.sleep(.3) + c.stat(f'/os{root / "a.txt"}') + assert c.read(f'/os{root / "a.txt"}') == b'hello\n' + for _ in range(2): # the failed Save left the text edited: Exit asks again + try: + c.write(f'/pane/{pane}/exec', b'Exit\n') + except Exception: + pass + if win: + win.close() + wait_for('the session\'s end', lambda: not any(alive(p) for p in started), timeout=20) + finally: + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + tapes = sorted(out.glob(f'{stem}-*.tape')) + assert tapes, f'{binary} wrote no tape into {out}' + taped = b''.join(t.read_bytes() for t in tapes) + for name in (b'NotAFile', b'NotDir', b'FileNotFound'): # the fifo's, the Save's, the Restore's + assert name in taped, f'no {name} in the tapes' + return tapes + + +def replay(binary, tape): + """`binary`'s replay of `tape`: its replicas' digests agree. A replica + client never draws its session's frames, and only the replica that + draws none (`headless`) must agree with another frontend's tape: the + two that draw meet the other build's drawing (a window's, a terminal's).""" + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} + env['PARDES_REPLAY'] = str(tape) + got = subprocess.run([binary], env=env, capture_output=True, timeout=600) + said = got.stderr.decode(errors='replace') + alike = ('gui' in Path(tape).name) == ('gui' in Path(binary).name) + agreed = [line for line in said.splitlines() if line.endswith('digests agree')] + assert ('headless replica' in ''.join(agreed)) and (not alike or (got.returncode == 0 and len(agreed) == 3)), \ + f'{binary} replaying {tape}:\n{said[-3000:]}' + print(f'cross_replay: {Path(binary).name} replayed {Path(tape).name}: ' + + '; '.join(line.split(': ', 1)[1] for line in said.splitlines() if 'replica' in line)) + + +if __name__ == '__main__': + if sys.argv[1:2] == ['--record']: + for t in record(sys.argv[2], sys.argv[3]): + print(t) + elif sys.argv[1:2] == ['--replay']: + for t in sys.argv[3:]: + replay(sys.argv[2], t) + else: + out = Path(tempfile.mkdtemp(prefix='xr-tapes-', dir=os.environ.get('TMPDIR', '/tmp'))) + try: + for t in record(sys.argv[1], out): + for b in sys.argv[1:]: + replay(b, t) + finally: + shutil.rmtree(out, ignore_errors=True) diff --git a/test/snapshot.zig b/test/snapshot.zig index 030733d0..1bd4dabf 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -94,6 +94,10 @@ var record_dir: ?[]const u8 = null; /// --tape=DIR: each session records its tape there (PARDES_RECORD, src/tape.zig) /// and the script fails unless every tape replays without diverging. var tape_dir: ?[]const u8 = null; +/// --replay-with=EXE (with --tape): each tape replayed by that build of +/// pardes too, a window's build replaying a terminal's sessions (a replica +/// of another build reads them so: docs/next-daemon.md). +var replay_with: ?[:0]const u8 = null; /// --dump (with --tape): each replay also loads the session's dump at its /// end, which must be the same session and dump to the same bytes /// (PARDES_REPLAY_DUMP, src/tape.zig). @@ -139,6 +143,8 @@ pub fn main(init: std.process.Init) !void { tape_dir = try absPath(arena, orig_cwd, a["--tape=".len..]); } else if (std.mem.eql(u8, a, "--dump")) { dump_check = true; + } else if (std.mem.startsWith(u8, a, "--replay-with=")) { + replay_with = try arena.dupeSentinel(u8, try absPath(arena, orig_cwd, a["--replay-with=".len..]), 0); } else if (std.mem.startsWith(u8, a, "--jobs=")) { jobs = @max(1, try std.fmt.parseInt(usize, a["--jobs=".len..], 10)); } else if (exe == null) { @@ -166,6 +172,7 @@ pub fn main(init: std.process.Init) !void { std.mem.startsWith(u8, a, "--record=") or std.mem.startsWith(u8, a, "--tape=") or std.mem.eql(u8, a, "--dump") or + std.mem.startsWith(u8, a, "--replay-with=") or std.mem.startsWith(u8, a, "--jobs=")) continue; if (!saw_exe) { saw_exe = true; @@ -521,8 +528,18 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 } /// Every tape the script's sessions wrote, replayed by the same build -/// (PARDES_REPLAY): why the first that diverged did, or null. +/// (PARDES_REPLAY), and by --replay-with's: why the first that diverged +/// did, or null. Another build's replay need agree only in its replica that +/// draws nothing, as a replica client draws none of its session's frames: +/// the two that draw meet a window's drawing where the session had a +/// terminal's. fn replayTapes(arena: std.mem.Allocator, exe_z: [:0]const u8, stem: []const u8) ?[]const u8 { + if (replayTapesWith(arena, exe_z, stem, false)) |why| return why; + const other = replay_with orelse return null; + return replayTapesWith(arena, other, stem, true); +} + +fn replayTapesWith(arena: std.mem.Allocator, exe_z: [:0]const u8, stem: []const u8, headless: bool) ?[]const u8 { const dir = tape_dir.?; const io = std.Io.Threaded.global_single_threaded.io(); var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return "the tape directory cannot be read"; @@ -534,10 +551,14 @@ fn replayTapes(arena: std.mem.Allocator, exe_z: [:0]const u8, stem: []const u8) const pid = entry.name[stem.len..][0 .. entry.name.len - stem.len - ".tape".len]; if (pid.len < 2 or pid[0] != '-' or std.mem.indexOfNone(u8, pid[1..], "0123456789") != null) continue; tapes += 1; - const cmd = std.fmt.allocPrintSentinel(arena, "PARDES_RECORD= PARDES_REPLAY='{s}/{s}' {s}timeout 300 '{s}' > '{s}/{s}.replay' 2>&1", .{ dir, entry.name, if (dump_check) "PARDES_REPLAY_DUMP=1 " else "", exe_z, dir, entry.name }, 0) catch return "out of memory"; + const cmd = std.fmt.allocPrintSentinel(arena, "PARDES_RECORD= PARDES_REPLAY='{s}/{s}' {s}timeout 300 '{s}' > '{s}/{s}.replay' 2>&1", .{ dir, entry.name, if (dump_check and !headless) "PARDES_REPLAY_DUMP=1 " else "", exe_z, dir, entry.name }, 0) catch return "out of memory"; if (system(cmd) != 0) { const why_path = std.fmt.allocPrint(arena, "{s}/{s}.replay", .{ dir, entry.name }) catch return "out of memory"; - return readFileAlloc(arena, why_path) catch "the replay failed and said nothing"; + const said = readFileAlloc(arena, why_path) catch return "the replay failed and said nothing"; + if (headless) if (std.mem.indexOf(u8, said, ": headless replica: ")) |at| { + if (std.mem.startsWith(u8, std.mem.trimStart(u8, said[at + ": headless replica: ".len ..], "0123456789"), " digests agree")) continue; + }; + return said; } } if (tapes == 0) return "no session wrote a tape"; |
