#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate: run each case on both boards and compare the traces. Each case of a case table (``scripts/cases.tsv`` by default) runs ``lynx-trace`` (this board) and ``scripts/lynx_trace.py`` on the reference's interpreter (``external/venv``, lynx-python at ``af8b8ba``, 75b9be7's board, cloned in ``external/lynx-python``), into ``external/traces/``, several at a time under ``nice``; the two traces are compared line for line (one line per 266,667-tick slice: CPU registers, board time, interrupt bits, display and Suzy state, a CRC of every CPU bus cycle, of the finished picture and of RAM). A case passes when they are identical; otherwise the first differing line is reported. Rerun the case with ``--detail SLICE`` on both tools to see the bus cycles of that slice. lockstep.py [--only REGEX] [--jobs N] [--cases FILE ...] [--rust PATH] [--keep] [--reference-cache DIR] [--extra ARGS] [--save-at-half] Case rows: ``name slices cart arguments``. The cart is a path (``$LTB``, the lynx-tests ROMs built by lynx-python, default ``../lynx-python/tests/test_roms/build`` beside this repository; ``$NOINTRO`` = ``$NO_INTRO_DIR``; ``$INPUTS`` = ``scripts/inputs``) or ``title:NAME``, the first file whose name starts with NAME under the No-Intro Lynx sets (as lynx-python's ``romsets.find_cart``). Every run gets a fresh, empty ``XDG_DATA_HOME`` (no EEPROM save from an earlier run is loaded). Each side runs under ``timeout``. Stdlib only. """ from __future__ import annotations import argparse import os import re import shlex import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parent DEFAULTS = { "LTB": str(ROOT.parent / "lynx-python" / "tests" / "test_roms" / "build"), "NOINTRO": os.environ.get("NO_INTRO_DIR", "No-Intro"), "INPUTS": str(HERE / "inputs"), } SETS = ( "Atari - Atari Lynx (LNX)", "Atari - Atari Lynx (LYX)", "Atari - Atari Lynx (LYX) (Aftermarket)", "Atari - Atari Lynx (LYX) (Private)", "Atari - Atari Lynx (BLL)", ) PYTHON = Path(os.environ.get("LYNX_REFERENCE_PYTHON", ROOT / "external" / "venv" / "bin" / "python")) TIMEOUT = int(os.environ.get("LOCKSTEP_TIMEOUT", "3600")) def find_cart(title: str) -> str: root = os.environ.get("NO_INTRO_DIR") if root: for name in SETS: directory = Path(root) / name if directory.is_dir(): for path in sorted(directory.iterdir()): if path.name.startswith(title): return str(path) return f"title-not-found:{title}" def cases(table: Path) -> list[tuple[str, int, str, list[str]]]: env = {**DEFAULTS, **{k: os.environ[k] for k in DEFAULTS if k in os.environ}} rows = [] for line in table.read_text().splitlines(): if not line or line.startswith("#"): continue name, slices, cart, args = (line.split("\t") + [""])[:4] for key, value in env.items(): cart = cart.replace(f"${key}", value) args = args.replace(f"${key}", value) if cart.startswith("title:"): cart = find_cart(cart[6:]) rows.append((name, int(slices), cart, shlex.split(args))) return rows def fresh_home(traces: Path) -> str: base = traces.parent / "xdg" base.mkdir(parents=True, exist_ok=True) return tempfile.mkdtemp(dir=base) def one(case, rust: Path, traces: Path, keep: bool, cache: Path | None, extra: list[str], save_half: bool = False): name, slices, cart, args = case safe = re.sub(r"[^A-Za-z0-9._-]+", "_", name) ref, ours = traces / f"{safe}.ref", traces / f"{safe}.rust" if save_half: ours = traces / f"{safe}.half.rust" if cache is not None: # --save-at is this board's alone (the reference runs uninterrupted): not in the tag tag = re.sub(r"[^A-Za-z0-9._-]+", "_", " ".join(extra)).strip("_") or "plain" ref = cache / f"{safe}.{slices}.{tag}.ref" # the reference's trace does not change common = [cart, "--slices", str(slices), *args, *extra] began = time.monotonic() if cache is None or not ref.is_file(): partial = ref.with_suffix(".part") try: reference = subprocess.run( ["timeout", str(TIMEOUT), "nice", "-n", "19", str(PYTHON), "-I", str(HERE / "lynx_trace.py"), *common, "--out", str(partial)], capture_output=True, text=True, cwd="/", env={**os.environ, "PYPY_GC_NURSERY": os.environ.get("PYPY_GC_NURSERY", "1M"), "XDG_DATA_HOME": fresh_home(traces)}, ) except OSError as error: return name, False, f"reference failed: {error}" if reference.returncode: return name, False, "reference failed: " + reference.stderr.strip()[-400:] partial.rename(ref) rust_args = list(common) if save_half: rust_args += ["--save-at", str(slices // 2)] board = subprocess.run( ["timeout", str(TIMEOUT), "nice", "-n", "19", str(rust), *rust_args, "--out", str(ours)], capture_output=True, text=True, env={**os.environ, "XDG_DATA_HOME": fresh_home(traces)}, ) if board.returncode: return name, False, "rust failed: " + board.stderr.strip()[-400:] seconds = time.monotonic() - began with ref.open() as a, ours.open() as b: for number, (left, right) in enumerate(zip(a, b)): if left != right: return (name, False, f"line {number}: reference {left.strip()!r}\n rust {right.strip()!r}") if ref.stat().st_size != ours.stat().st_size: return name, False, "one trace is longer" if not keep: if cache is None: ref.unlink() ours.unlink() return name, True, f"identical, {slices} slices ({seconds:.0f} s)" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", help="a regular expression on the case name") parser.add_argument("--jobs", type=int, default=3) parser.add_argument("--cases", type=Path, action="append", help="a case table (repeatable; default scripts/cases.tsv)") parser.add_argument("--rust", type=Path, help="a trace binary to judge instead of this tree's") parser.add_argument("--traces", type=Path, default=ROOT / "external" / "traces") parser.add_argument("--keep", action="store_true", help="keep the traces of identical cases") parser.add_argument("--reference-cache", type=Path, help="reuse the reference's traces here") parser.add_argument("--extra", default="", help="arguments added to every case (both sides); " "use --extra=... for ones that start with --") parser.add_argument("--save-at-half", action="store_true", help="the save-state round trip: this board saves, boots a fresh console, " "loads and continues half way through each case (lynx-trace --save-at)") args = parser.parse_args() rust = args.rust if rust is None: build = subprocess.run(["cargo", "build", "--release", "-q", "--bin", "lynx-trace", "--manifest-path", str(ROOT / "Cargo.toml")]) if build.returncode: return 1 rust = ROOT / "target" / "release" / "lynx-trace" args.traces = args.traces.resolve() # the reference runs from / (no stray imports) args.traces.mkdir(parents=True, exist_ok=True) if args.reference_cache: args.reference_cache = args.reference_cache.resolve() args.reference_cache.mkdir(parents=True, exist_ok=True) tables = args.cases or [HERE / "cases.tsv"] todo = [c for t in tables for c in cases(t) if not args.only or re.search(args.only, c[0])] todo.sort(key=lambda c: -c[1]) # the longest first, so the pool does not end on one long case extra = shlex.split(args.extra) failed = 0 def run(case): return one(case, rust, args.traces, args.keep, args.reference_cache, extra, args.save_at_half) with ThreadPoolExecutor(args.jobs) as pool: for name, ok, text in pool.map(run, todo): print(f"{name}: {text}", flush=True) failed += not ok print(f"{len(todo) - failed} of {len(todo)} cases identical") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())