#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The lockstep gate: run each case on both boards and compare the traces. Each case of ``scripts/cases.tsv`` runs ``a2600-trace`` (this board) and ``scripts/a2600_trace.py`` on the reference's interpreter (``external/venv``: a2600-python at 4ad24f2, 6502-python at 828b619: 28fb095's and 741419a's code), under ``nice`` with ``PYPY_GC_NURSERY=1M``, a few cases at a time (``--jobs``, default 3: each job runs its two sides one after the other); the traces (one line per 19,912-cycle slice: CPU state, board time, TIA position, RIOT registers, a CRC of every bus cycle, of every finished line and of the audio samples) are compared line for line. A case passes when they are identical; otherwise the first differing line is reported (rerun both tools with ``--detail SLICE`` to see that slice's bus cycles). lockstep.py [--only REGEX] [--jobs N] [--cases FILE] [--rust PATH] [--keep] [--reference-cache DIR] [--save-at-half] [--extra ARGS] Case variables come from the environment: ``$NOINTRO`` (the 2600 set under ``NO_INTRO_DIR``), ``$AFTERMARKET`` (its aftermarket set), ``$REF`` (an a2600-python checkout with its references fetched, for the test ROMs: ``A2600_PYTHON_ROOT``, default ``../a2600-python``), ``$INPUTS`` (``scripts/inputs``). Both sides read MAME's software list from ``MAME_HASHPATH`` (default: ``$REF/reference/src/mame/hash``), so they identify a dump alike. With ``--reference-cache`` the reference's traces are kept by case and reused; when the reference changes, move that directory aside (never delete it) and let it refill. Stdlib only. """ from __future__ import annotations import argparse import os import re import shlex import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parent REF = Path(os.environ.get("A2600_PYTHON_ROOT") or ROOT.parent / "a2600-python") NO_INTRO = os.environ.get("NO_INTRO_DIR", "No-Intro") DEFAULTS = { "NOINTRO": str(Path(NO_INTRO) / "Atari - Atari 2600"), "AFTERMARKET": str(Path(NO_INTRO) / "Atari - Atari 2600 (Aftermarket)"), "REF": str(REF), "INPUTS": str(HERE / "inputs"), } PYTHON = Path(os.environ.get("A2600_REFERENCE_PYTHON", ROOT / "external" / "venv" / "bin" / "python")) ENV = { **os.environ, "MAME_HASHPATH": os.environ.get("MAME_HASHPATH") or str(REF / "reference/src/mame/hash"), } def cases(table: Path) -> list[tuple[str, int, str, list[str]]]: rows = [] for line in table.read_text().splitlines(): if not line or line.startswith("#"): continue name, slices, rom, args = (line.split("\t") + [""])[:4] for key, value in DEFAULTS.items(): rom = rom.replace(f"${key}", value) args = args.replace(f"${key}", value) rows.append((name, int(slices), rom, shlex.split(args))) return rows def one(case, rust: Path, traces: Path, keep: bool, cache: Path | None, extra: list[str], save_half: bool): name, slices, rom, args = case safe = re.sub(r"[^A-Za-z0-9._-]+", "_", name) ref, ours = traces / f"{safe}.ref", traces / f"{safe}.rust" if cache is not None: tag = re.sub(r"[^A-Za-z0-9._-]+", "_", " ".join(extra)) or "plain" ref = cache / f"{safe}.{slices}.{tag}.ref" # the reference's trace does not change common = [rom, "--slices", str(slices), *args, *extra] began = time.monotonic() if cache is None or not ref.is_file(): partial = ref.with_suffix(".part") reference = subprocess.run( ["nice", "-n", "19", "timeout", "3600", str(PYTHON), str(HERE / "a2600_trace.py"), *common, "--out", str(partial)], capture_output=True, text=True, cwd="/", env={**ENV, "PYPY_GC_NURSERY": os.environ.get("PYPY_GC_NURSERY", "1M")}, ) # fmt: skip if reference.returncode: partial.unlink(missing_ok=True) return name, False, "reference failed: " + reference.stderr.strip()[-300:] partial.rename(ref) board_args = [*common, "--save-at", str(slices // 2)] if save_half else common board = subprocess.run( ["nice", "-n", "19", "timeout", "1800", str(rust), *board_args, "--out", str(ours)], capture_output=True, text=True, env=ENV, ) # fmt: skip if board.returncode: return name, False, "rust failed: " + board.stderr.strip()[-300:] 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, default=HERE / "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)") parser.add_argument("--save-at-half", action="store_true", help="this board saves, reloads into a fresh console and goes on half way") # fmt: skip args = parser.parse_args() rust = args.rust if rust is None: build = subprocess.run(["cargo", "build", "--release", "-q", "--bin", "a2600-trace", "--manifest-path", str(ROOT / "Cargo.toml")]) # fmt: skip if build.returncode: return 1 rust = ROOT / "target" / "release" / "a2600-trace" args.traces = args.traces.resolve() 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) todo = [c for c in cases(args.cases) if not args.only or re.search(args.only, c[0])] todo.sort(key=lambda c: -c[1]) # the longest first 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())