#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The trace lockstep: run each scenario on both cores and compare the traces. lockstep.py SCENARIO.json [...] [--jobs N] [--python P] [--rust BIN] [--reference-cache DIR] Each scenario runs on 65816-python (``scripts/reference_trace.py`` on the reference's interpreter) and on this crate (``target/release/trace``), each trace streamed into a SHA-256; the scenario passes when the two digests and line counts are equal, which is the two traces equal byte for byte (every boundary's kind, cycles, instruction bytes, state before and after, and every bus cycle with its address, value and pins). With ``--reference-cache`` the reference's digest is kept there, keyed by the scenario's content (and its ROM's), so a Rust change re-runs only the Rust side; when the reference changes, its cache directory is moved aside and regenerated (methodology, "Gates"). On a difference both traces are written to ``external/traces/`` and ``compare_traces.py`` (the reference's ``first_trace_divergence``) says where. Stdlib only. """ from __future__ import annotations import argparse import hashlib import json import os import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TRACES = ROOT / "external" / "traces" NICE = ["nice", "-n", "19"] def digest_of(command: list[str], environment: dict | None = None) -> tuple[str, int, str]: """(sha256 hex, lines, error text) of a command's standard output, streamed.""" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment) digest = hashlib.sha256() lines = 0 for line in process.stdout: digest.update(line) lines += 1 error = process.stderr.read().decode(errors="replace") if process.wait(): return "", lines, error.strip()[-600:] or f"exit {process.returncode}" return digest.hexdigest(), lines, "" def scenario_key(scenario: Path) -> str: text = scenario.read_bytes() digest = hashlib.sha256(text) rom = json.loads(text).get("rom") if rom: path = Path(rom) if Path(rom).is_absolute() else scenario.parent / rom digest.update(path.read_bytes()) return f"{scenario.stem}.{digest.hexdigest()[:16]}" def one(scenario: Path, python: str, rust: Path, cache: Path | None) -> tuple[str, bool, str]: name = scenario.stem environment = {**os.environ, "PYPY_GC_NURSERY": os.environ.get("PYPY_GC_NURSERY", "1M")} reference_command = [*NICE, python, str(ROOT / "scripts" / "reference_trace.py"), str(scenario)] cached = cache / f"{scenario_key(scenario)}.ref" if cache else None if cached is not None and cached.is_file(): reference_digest, reference_lines = cached.read_text().split() reference_lines = int(reference_lines) else: reference_digest, reference_lines, error = digest_of(reference_command, environment) if error: return name, False, "reference failed: " + error if cached is not None: cached.write_text(f"{reference_digest} {reference_lines}\n") digest, lines, error = digest_of([*NICE, str(rust), str(scenario)]) if error: return name, False, "rust failed: " + error if (digest, lines) == (reference_digest, reference_lines): return name, True, f"traces are identical ({lines:,} boundaries)" # Say where: both traces in full, then the reference's own comparison. TRACES.mkdir(parents=True, exist_ok=True) ref, ours = TRACES / f"{name}.ref.jsonl", TRACES / f"{name}.rust.jsonl" with ref.open("w") as handle: subprocess.run(reference_command, stdout=handle, env=environment, check=False) with ours.open("w") as handle: subprocess.run([*NICE, str(rust), str(scenario)], stdout=handle, check=False) compared = subprocess.run( [*NICE, python, str(ROOT / "scripts" / "compare_traces.py"), str(ref), str(ours)], capture_output=True, text=True, env=environment, ) # fmt: skip text = (compared.stdout.strip() or compared.stderr.strip())[:3000] return name, False, f"traces differ ({reference_lines:,} / {lines:,} boundaries):\n{text}" 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("--reference-cache", type=Path, help="keep the reference's digests here") args = parser.parse_args() if not args.python: raise SystemExit("no reference interpreter: set REFERENCE_PYTHON (scripts/env.sh does)") rust = args.rust if rust is None: build = subprocess.run([*NICE, "cargo", "build", "--release", "-q", "--bin", "trace", "--manifest-path", str(ROOT / "Cargo.toml")]) # fmt: skip if build.returncode: return 1 rust = ROOT / "target" / "release" / "trace" if args.reference_cache: args.reference_cache.mkdir(parents=True, exist_ok=True) failed = 0 # The longest first, so the pool does not end on one long case. todo = sorted(args.scenarios, key=lambda s: -json.loads(s.read_text()).get("steps", 0)) with ThreadPoolExecutor(min(args.jobs, 4)) as pool: # the machine is shared for name, ok, text in pool.map(lambda s: one(s, args.python, rust, args.reference_cache), todo): print(f"{name}: {text}", flush=True) failed += not ok print(f"{len(todo) - failed} of {len(todo)} scenarios identical") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())