#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The whole-machine lockstep: run each case on both boards and compare the traces. Each case of ``scripts/cases.tsv`` runs ``s32x-trace`` (this board) and ``scripts/s32x_trace.py`` on the reference (sega32x-python) and compares the two traces line for line. A case passes when they are identical; otherwise the first differing line is reported with its frame. The reference is slow (about 2 frames a second), so its traces are cached: under ``external/reference-cache/KEY/``, where KEY names the reference's source tree (``git rev-parse HEAD:src``), the pins its interpreter has installed and a digest of the two trace scripts, one file per case named by a digest of the case's arguments. A Rust change re-runs only the Rust side; a new reference makes a new KEY (the old traces stay where they are, never deleted). python3 scripts/lockstep.py [--only NAME ...] [--jobs N] [--rust PATH] [--refresh] Found through the environment (no machine path here): ``SEGA32X_BIOS_DIR`` (the user's boot ROMs), ``NO_INTRO_DIR`` (``$NI32`` is its "Sega - 32X"), ``SEGA32X_PY`` (the reference's interpreter; default ``../sega32x-python/.venv-sh2-8824075/bin/python``), ``TESTPICO`` (default the reference checkout's ``reference/build/testpico`` build). The reference's source is ``external/sega32x-python`` (``scripts/external.sh``). A case whose cartridge cannot be found is MISSING and counts as a failure. Python runs at most ``--jobs`` at a time (default 6) under ``nice`` with ``PYPY_GC_NURSERY=1M``. Stdlib only. """ from __future__ import annotations import argparse import hashlib import json import os import shlex import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent REPO = HERE.parent REFERENCE = REPO / "external" / "sega32x-python" _NO_INTRO = os.environ.get("NO_INTRO_DIR") DEFAULTS = { "NI32": f"{_NO_INTRO}/Sega - 32X" if _NO_INTRO else None, "TESTPICO": str(REPO.parent / "sega32x-python" / "reference/build/testpico/hardware/testpico-30a5783.bin"), # Dasutin's 240p Test Suite for 32X 1.0 (homebrew), as the reference fetches it. "SUITE240P": str(REPO.parent / "sega32x-python" / "reference/test-roms/240pSuite_32X_1.0.32x"), } NEEDS = {"NI32": "NO_INTRO_DIR"} def expand(text: str) -> str: for name, default in DEFAULTS.items(): value = os.environ.get(name, default) if value is not None: text = text.replace(f"${name}", value) return text def missing(cart: str) -> str | None: for name in DEFAULTS: if f"${name}" in cart: return f"set {NEEDS.get(name, name)}" if not Path(cart).exists(): return f"not found: {cart}" return None def cases(path: Path) -> list[tuple[str, int, str, str, list[str]]]: out = [] for line in path.read_text().splitlines(): if not line.strip() or line.startswith("#"): continue fields = line.split("\t") name, frames, raw = fields[0], int(fields[1]), fields[2] args = shlex.split(fields[3]) if len(fields) > 3 else [] out.append((name, frames, raw, expand(raw), args)) return out def reference_key(python: Path) -> str: """The reference's commit, its interpreter's pins and the trace scripts' digest.""" head = subprocess.run(["git", "-C", str(REFERENCE), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip # Keyed by the source tree, so a commit that changes only docs keeps the cache. tree = subprocess.run(["git", "-C", str(REFERENCE), "rev-parse", "HEAD:src"], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip dirty = subprocess.run(["git", "-C", str(REFERENCE), "status", "--porcelain", "--", "src"], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip if dirty: raise SystemExit("the reference's src has changes: commit them (the cache is by commit)") pins = subprocess.run( [str(python), "-c", "import importlib.metadata as m, json\n" "print(json.dumps({p: json.loads(m.distribution(p).read_text('direct_url.json') or '{}')" ".get('vcs_info', {}).get('commit_id') for p in ('megadrive-python', 'sh2-python', " "'m68000-python', 'z80-python', 'ym2612-python', 'sn76489-python')}, sort_keys=True))"], capture_output=True, text=True, check=True, ).stdout.strip() # fmt: skip scripts = hashlib.sha1() for path in (HERE / "s32x_trace.py", REPO / "external/megadrive-rust/scripts/md_trace.py"): scripts.update(path.read_bytes()) digest = hashlib.sha1(pins.encode() + scripts.digest()).hexdigest()[:12] return f"src-{tree[:12]}-{digest}", head, pins def first_difference(a: Path, b: Path) -> str: frame = "-" with a.open() as left, b.open() as right: for number, (x, y) in enumerate(zip(left, right), 1): if x.startswith("F "): frame = x.split()[1] if x != y: return f"line {number} (frame {frame}): {x.split()[0]} line differs" return "one trace is longer" def default_python() -> Path: return Path(os.environ.get("SEGA32X_PY", REPO.parent / "sega32x-python/.venv-sh2-8824075/bin/python")) def cached_trace(cache: Path, case) -> Path: """Where the reference's trace of `case` is kept: named by what it runs, not by where the files are.""" name, count, raw, _cart, args = case key = hashlib.sha1(json.dumps([raw, count, args]).encode()).hexdigest()[:16] return cache / f"{name}-{key}.py.trace" def run_case(case, rust: Path, python: Path, out: Path, cache: Path, refresh: bool, cached_only: bool = False): name, count, raw, cart, args = case why = missing(cart) if why: return name, count, "MISSING", why, 0.0, None bios = os.environ.get("SEGA32X_BIOS_DIR") if not bios: return name, count, "MISSING", "set SEGA32X_BIOS_DIR", 0.0, None common = [cart, "--bios-dir", bios, "--frames", str(count), *args] py = cached_trace(cache, case) if cached_only and not py.exists(): return name, count, "MISSING", "no cached reference trace", 0.0, None rs = out / f"{name}.rs.trace" started = time.perf_counter() r = subprocess.run(["nice", str(rust), *common, "--out", str(rs)], capture_output=True, text=True) rust_s = time.perf_counter() - started python_s = None if refresh or not py.exists(): started = time.perf_counter() env = dict(os.environ, PYPY_GC_NURSERY="1M", PYTHONPATH=str(REFERENCE / "src")) partial = py.with_suffix(".partial") p = subprocess.run( ["nice", str(python), str(HERE / "s32x_trace.py"), *common, "--out", str(partial)], capture_output=True, text=True, env=env, ) # fmt: skip python_s = time.perf_counter() - started if p.returncode: return name, count, "ERROR", p.stderr.strip()[-300:], rust_s, python_s partial.rename(py) if r.returncode: return name, count, "ERROR", r.stderr.strip()[-300:], rust_s, python_s if rs.read_bytes() == py.read_bytes(): lines = sum(1 for _ in rs.open()) lock = next((line for line in rs.open() if line.startswith("L ")), "") note = f"{lines} lines" + (f"; both stop: {lock.strip()}" if lock else "") return name, count, "identical", note, rust_s, python_s return name, count, "DIFFERENT", first_difference(rs, py), rust_s, python_s def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", action="append", default=[]) parser.add_argument("--cases", type=Path, default=HERE / "cases.tsv") parser.add_argument("--jobs", type=int, default=6) parser.add_argument("--rust", type=Path, default=REPO / "target/release/s32x-trace") parser.add_argument("--python", type=Path, default=default_python()) parser.add_argument("--cached-only", action="store_true", help="never run the reference: a case without a cached trace is MISSING") # fmt: skip parser.add_argument("--out", type=Path, default=REPO / "external/traces") parser.add_argument("--refresh", action="store_true", help="rerun the reference even if cached") args = parser.parse_args() key, head, pins = reference_key(args.python) cache = REPO / "external/reference-cache" / key cache.mkdir(parents=True, exist_ok=True) (cache / "key.json").write_text(json.dumps({"reference": head, "pins": json.loads(pins)}, indent=1)) args.out.mkdir(parents=True, exist_ok=True) selected = [c for c in cases(args.cases) if not args.only or c[0] in args.only] print(f"reference {head[:12]}, cache {key}", flush=True) failed = 0 with ThreadPoolExecutor(args.jobs) as pool: jobs = [pool.submit(run_case, c, args.rust, args.python, args.out, cache, args.refresh, args.cached_only) for c in selected] # fmt: skip for job in jobs: name, count, verdict, note, rust_s, python_s = job.result() failed += verdict != "identical" python = "cached" if python_s is None else f"{python_s:7.1f} s" print(f"{name:24} {count:6} frames {verdict:9} rust {rust_s:6.1f} s python {python:>9} {note}", flush=True) # fmt: skip print(f"{len(selected) - failed} of {len(selected)} identical") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())