#!/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 runs ``a7800-trace`` (this board) and ``scripts/a7800_trace.py`` on the reference's interpreter (a7800-python's ``.venv-pypy``; the reference's source is the clone at ``external/a7800-python``, f70eeb2: d6b220d's board), into ``external/traces/``, at most ``--jobs`` at a time (default 3) under ``nice -n 19`` and a timeout; the two traces are compared line for line (one line per slice: board time, MARIA's or the TIA's position, the CPU's registers, a CRC of every bus cycle and of every finished line, and the audio CRC with ``--extra=--audio``). 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 [--cases FILE]... [--only REGEX] [--jobs N] [--rust PATH] [--keep] [--reference-cache DIR] [--extra ARGS] [--rust-extra ARGS] [--save-at-half] ``--rust-extra`` goes to this board only (a seeded fault, ``--fault NAME``: the trace must then differ from the reference's). The reference's traces are cached by case, slices and extra arguments in ``--reference-cache``; a cache made by another reference commit is moved aside by ladder.sh, never deleted. Case variables: ``$LICENSED``, ``$AFTERMARKET`` (the No-Intro 7800 sets), ``$A2600`` (the No-Intro 2600 set), ``$INPUTS`` (``external/inputs``: scripts/inputs.py). Both sides run with ``MAME_HASHPATH`` set to a2600-python's fetched lists (the 2600 cartridge identification), as a2600-rust's ladder does. Stdlib only. """ from __future__ import annotations import argparse import os import re import shlex import subprocess import sys import time import zlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parent NOINTRO = Path(os.environ.get("NO_INTRO_DIR", "NO_INTRO_DIR-is-unset")) DEFAULTS = { "LICENSED": str(NOINTRO / "Atari - Atari 7800 (BIN)"), "AFTERMARKET": str(NOINTRO / "Atari - Atari 7800 (BIN) (Aftermarket)"), "A2600": str(NOINTRO / "Atari - Atari 2600"), "INPUTS": str(ROOT / "external" / "inputs"), } PYTHON = Path(os.environ.get("A7800_REFERENCE_PYTHON", ROOT.parent / "a7800-python/.venv-pypy/bin/python")) TIMEOUT = int(os.environ.get("LOCKSTEP_TIMEOUT", "7200")) HASHPATH = os.environ.get("MAME_HASHPATH", str(ROOT.parent / "a2600-python/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 run(cmd: list[str], **kw) -> subprocess.CompletedProcess: env = {**os.environ, "MAME_HASHPATH": HASHPATH, "PYPY_GC_NURSERY": os.environ.get("PYPY_GC_NURSERY", "1M")} try: return subprocess.run(["nice", "-n", "19", *cmd], capture_output=True, text=True, timeout=TIMEOUT, env=env, **kw) except subprocess.TimeoutExpired: return subprocess.CompletedProcess(cmd, 124, "", f"timed out after {TIMEOUT} s") def safe(text: str) -> str: return re.sub(r"[^A-Za-z0-9._-]+", "_", text) def one(case, rust: Path, traces: Path, keep: bool, cache: Path | None, extra: list[str], rust_extra: list[str], save_half: bool): name, slices, rom, args = case ref, ours = traces / f"{safe(name)}.ref", traces / f"{safe(name)}.rust" if rust_extra or save_half: ours = traces / f"{safe(name)}.{safe(' '.join(rust_extra)) or 'save'}.rust" if cache is not None: tag = safe(" ".join(extra)).strip("_") or "plain" # the reference's trace does not change; keyed by the case's ROM and arguments too key = zlib.crc32("\t".join([rom, *args]).encode()) ref = cache / f"{safe(name)}.{slices}.{tag}.{key:08x}.ref" 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 = run([str(PYTHON), str(HERE / "a7800_trace.py"), *common, "--out", str(partial)], cwd="/") if reference.returncode: partial.unlink(missing_ok=True) return name, False, "reference failed: " + reference.stderr.strip()[-400:] partial.rename(ref) mine = [*common, *rust_extra, "--out", str(ours)] if save_half: mine += ["--save-at", str(slices // 2)] board = run([str(rust), *mine]) 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()[:300]!r}\n rust {right.strip()[:300]!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") 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("--rust-extra", default="", help="arguments for this board only (a seeded fault)") parser.add_argument("--save-at-half", action="store_true", help="the save-state round trip: this board saves half way through each case " "and goes on in a fresh console (a7800-trace --save-at)") args = parser.parse_args() args.jobs = min(args.jobs, 3) # the machine is shared rust = args.rust if rust is None: build = subprocess.run(["cargo", "build", "--release", "-q", "-j", "3", "--bin", "a7800-trace", "--manifest-path", str(ROOT / "Cargo.toml")]) if build.returncode: return 1 rust = ROOT / "target" / "release" / "a7800-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])] if args.save_at_half: todo = [c for c in todo if "--mode" not in c[3]] # save states are 7800 mode's todo.sort(key=lambda c: -c[1]) # the longest first, so the pool does not end on one long case extra, rust_extra = shlex.split(args.extra), shlex.split(args.rust_extra) failed = 0 def go(case): return one(case, rust, args.traces, args.keep, args.reference_cache, extra, rust_extra, args.save_at_half) with ThreadPoolExecutor(args.jobs) as pool: for name, ok, text in pool.map(go, 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())