#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rungs 4 and 5: run each scenario on both cores and compare the slice traces line for line. lockstep.py SCENARIO.json [...] [--jobs N] [--rust BINARY] [--reference-cache DIR] [--keep] Each scenario runs on arm7tdmi-python (``scripts/reference_trace.py`` on the reference's interpreter, ``$REFERENCE_PYTHON``) and on this crate (``target/release/arm7-trace``); the traces must be identical. The reference's traces are cached in ``--reference-cache``, keyed by the scenario's name and a CRC of its JSON and memory image, so a Rust change re-runs only the Rust side; scripts/env.sh moves a cache made at another pin aside. On a difference the first differing line is printed; ``--detail FROM TO`` on both tools shows the bus cycles. Stdlib only. """ from __future__ import annotations import argparse import os import subprocess import sys import zlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] NICE = ["nice", "-n", "19"] def key(scenario: Path) -> str: crc = zlib.crc32(scenario.read_bytes()) image = scenario.with_suffix(".bin") if image.exists(): crc = zlib.crc32(image.read_bytes(), crc) return f"{scenario.stem}.{crc:08x}" def one(scenario: Path, python: str, rust: Path, traces: Path, cache: Path | None, keep: bool): name = scenario.stem ref = (cache / f"{key(scenario)}.ref") if cache else traces / f"{name}.ref" ours = traces / f"{name}.rust" env = {**os.environ, "PYPY_GC_NURSERY": os.environ.get("PYPY_GC_NURSERY", "1M")} if cache is None or not ref.is_file(): part = ref.with_suffix(".part") done = subprocess.run([*NICE, python, str(ROOT / "scripts" / "reference_trace.py"), str(scenario), "--out", str(part)], capture_output=True, text=True, env=env, cwd="/") if done.returncode: return name, False, "reference failed: " + done.stderr.strip()[-400:] part.rename(ref) done = subprocess.run([*NICE, str(rust), str(scenario), "--out", str(ours)], capture_output=True, text=True, env=env) if done.returncode: return name, False, "rust failed: " + done.stderr.strip()[-400:] lines = 0 with ref.open() as a, ours.open() as b: for lines, (left, right) in enumerate(zip(a, b), 1): if left != right: return name, False, f"line {lines}:\n reference {left.strip()[:240]}\n rust {right.strip()[:240]}" if ref.stat().st_size != ours.stat().st_size: return name, False, "one trace is longer" if not keep: ours.unlink() if cache is None: ref.unlink() return name, True, f"identical ({lines:,} lines; {left.strip()})" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("scenarios", nargs="+", type=Path) parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--python", default=os.environ.get("REFERENCE_PYTHON")) 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("--reference-cache", type=Path) parser.add_argument("--keep", action="store_true") parser.add_argument("--quiet", action="store_true", help="print only differences and the total") args = parser.parse_args() if not args.python: raise SystemExit("no reference interpreter: set REFERENCE_PYTHON (scripts/env.sh does)") args.traces.mkdir(parents=True, exist_ok=True) if args.reference_cache: args.reference_cache.mkdir(parents=True, exist_ok=True) rust = args.rust or ROOT / "target" / "release" / "arm7-trace" if args.rust is None: if subprocess.run([*NICE, "cargo", "build", "--release", "-q", "--manifest-path", str(ROOT / "Cargo.toml")]).returncode: return 1 failed = 0 with ThreadPoolExecutor(min(args.jobs, 8)) as pool: work = lambda s: one(s.resolve(), args.python, rust, args.traces, args.reference_cache, args.keep) # noqa: E731 for name, ok, text in pool.map(work, args.scenarios): if not ok or not args.quiet: print(f"{name}: {text}", flush=True) failed += not ok print(f"{len(args.scenarios) - failed} of {len(args.scenarios)} scenarios identical") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())