#!/usr/bin/env python3 """Smoke-test the board on a curated set of commercial ROMs, in parallel, against baselines. A regression detector, not a judge (docs/validation.md "Smoke set"): the baselines are the board's own output at a recorded commit, so a change means "look", never "wrong". Each entry of ``tests/smoke_set.txt`` runs in its own PyPy process (a crash or hang costs one entry, not the run) and at each checkpoint frame records three digests: - picture: ``screen_hash``, as ``tests/frames_pass.txt`` records it; - state: the CPU's registers and CPSR, EWRAM and IWRAM, which move on a timing change frames before the picture does; - sound: every sample the mixer has put out so far (the Game Boy channels and the two DMA sound FIFOs through SOUNDCNT and SOUNDBIAS, at 32,768 Hz). Entries start at 8000000 with the BIOS's register setup (``skip_bios``, NanoBoyAdvance's SkipBootScreen) unless their start column says ``bios``: the boot animation is 273 frames, a minute a ROM on a loaded machine, and the same for every cartridge. The RTC starts at a fixed date so RTC games repeat. python scripts/smoke.py --quick # the q checkpoints: eleven ROMs, short python scripts/smoke.py # the whole set python scripts/smoke.py --record [--quick] # write the baselines from this board python scripts/smoke.py --nba # also diff each picture with NBA 1.8.3 python scripts/smoke.py --only Metroid --dump DIR --every 60 # PNGs to look at """ from __future__ import annotations import argparse import hashlib import json import os import subprocess import sys import tempfile import time import zipfile from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from datetime import datetime from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SET = ROOT / "tests" / "smoke_set.txt" BASELINE = ROOT / "tests" / "smoke_baseline.txt" NBA = ROOT / "reference" / "build" / "nba" / "nba_driver" PYPY = ROOT / ".venv-pypy" / "bin" / "python" RTC_START = datetime(2005, 6, 15, 12, 0, 0) @dataclass class Entry: rom: str # nointro:NAME.zip, nointro:SET/NAME.zip, or a repository path checkpoints: list[int] quick: list[int] # the checkpoints marked q: what --quick runs keys: list[str] start: str # skip or bios category: str reason: str line: int = 0 @property def frames(self) -> int: return self.checkpoints[-1] @dataclass class Result: entry: Entry status: str = "ok" # ok, crash, hang seconds: float = 0.0 points: list[dict] = field(default_factory=list) info: dict = field(default_factory=dict) error: str = "" # ----- the manifest ------------------------------------------------------------------------- def load_set(path: Path | None = None) -> list[Entry]: """``ROM | checkpoints | keys | start | category | reason``, ``#`` comments.""" path = path or SET entries = [] for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): line = raw.strip() if not line or line.startswith("#"): continue columns = [c.strip() for c in line.split("|")] if len(columns) != 6: raise SystemExit(f"{path.name}:{number}: expected 6 columns, got {len(columns)}") rom, points, keys, start, category, reason = columns marks = [p.strip() for p in points.split(",")] entries.append( Entry( rom=rom, checkpoints=sorted(int(p.rstrip("q")) for p in marks), quick=sorted(int(p.rstrip("q")) for p in marks if p.endswith("q")), keys=expand_keys(keys), start=start, category=category, reason=reason, line=number, ) ) return entries def expand_keys(column: str) -> list[str]: """``FRAME:MASK`` tokens, and ``MASK@FIRST-LAST/EVERY``: press MASK for 4 frames every EVERY frames from FIRST to LAST (to get past logos and title screens).""" keys: list[str] = [] for token in [] if column == "-" else column.split(): if "@" in token: mask, span = token.split("@") frames, every = span.split("/") first, last = (int(f) for f in frames.split("-")) for frame in range(first, last + 1, int(every)): keys += [f"{frame}:{mask}", f"{frame + 4}:0"] else: keys.append(token) return keys def rom_path(rom: str) -> Path: if rom.startswith("nointro:"): sys.path.insert(0, str(ROOT / "src")) from gba_python.bios import nointro_dir name = rom.removeprefix("nointro:") if "/" in name: return nointro_dir() / name return nointro_dir() / "Nintendo - Game Boy Advance" / name return ROOT / rom def short(rom: str) -> str: name = rom.removeprefix("nointro:").rsplit("/", 1)[-1] return name.removesuffix(".zip").removesuffix(".gba") # ----- one entry, in its own process -------------------------------------------------------- def run_one(spec: dict) -> dict: """Run one entry on the board; return its digests (called in the worker process).""" sys.path.insert(0, str(ROOT / "src")) from gba_python import bios as bios_module from gba_python.board import GBA from gba_python.testrom import read_rom, screen_hash, screen_png gba = GBA( bios_module.find(None), read_rom(spec["path"]), skip_bios=spec["start"] == "skip", rtc_start=RTC_START, ) sound = hashlib.sha256() silent = True gba.apu.start_capture() keys = {int(f): int(m, 0) for f, m in (k.split(":") for k in spec["keys"])} checkpoints = set(spec["checkpoints"]) dump = Path(spec["dump"]) if spec.get("dump") else None every = spec.get("every") or 0 points = [] for frame in range(1, spec["checkpoints"][-1] + 1): if frame - 1 in keys: gba.keypad.set_pressed(keys[frame - 1]) gba.run_frame() if dump and every and frame % every == 0: (dump / f"{spec['stem']}-{frame:05d}.png").write_bytes(screen_png(gba)) samples = gba.apu.take_samples() silent = silent and not any(samples) sound.update(samples.tobytes()) if frame in checkpoints: cpu = gba.cpu state = hashlib.sha256() state.update(json.dumps([list(cpu.r), cpu.cpsr]).encode()) state.update(gba.ewram) state.update(gba.iwram) points.append( { "frame": frame, "picture": screen_hash(gba), "state": state.hexdigest()[:16], "sound": "0" * 16 if silent else sound.hexdigest()[:16], "mode": gba.ppu.registers[0] & 7, } ) if dump: (dump / f"{spec['stem']}-{frame:05d}-check.png").write_bytes(screen_png(gba)) cart = gba.cartridge info = {"save": cart.save_type or "none", "rtc": cart.gpio is not None} return {"points": points, "info": info} def launch(entry: Entry, args: argparse.Namespace) -> Result: spec = { "path": str(rom_path(entry.rom)), "start": entry.start, "keys": entry.keys, "checkpoints": entry.checkpoints, "dump": str(args.dump) if args.dump else None, "every": args.every, "stem": short(entry.rom).split(" (")[0].replace(" ", "_"), } python = str(PYPY if PYPY.exists() else Path(sys.executable)) began = time.monotonic() result = Result(entry) try: done = subprocess.run( [python, str(Path(__file__)), "--one", json.dumps(spec)], capture_output=True, text=True, timeout=args.timeout, cwd=ROOT, ) except subprocess.TimeoutExpired: result.status = "hang" result.error = f"no result in {args.timeout} s" else: if done.returncode: result.status = "crash" tail = done.stderr.strip().splitlines() result.error = tail[-1] if tail else f"exit {done.returncode}" else: out = json.loads(done.stdout.strip().splitlines()[-1]) result.points, result.info = out["points"], out["info"] result.seconds = time.monotonic() - began if args.nba and result.status == "ok": for point in result.points: shots = (args.dump, spec["stem"]) if args.dump else None point["nba"], point["nba_match"] = nba_picture(entry, point["frame"], shots) return result # ----- NanoBoyAdvance 1.8.3, a detector ---------------------------------------------------- def nba_picture( entry: Entry, frames: int, shots: tuple[Path, str] | None = None ) -> tuple[str, float | None]: """NBA's ``screen_hash`` after ``frames`` (its driver: no GPIO, so no RTC). With ``shots`` (the dump folder and the entry's stem) its PNG is kept beside the board's, and the share of pixels the two pictures have in common is returned too.""" sys.path.insert(0, str(ROOT / "scripts")) from frame_diff import decode_png from referee_run import bios_args from gba_python import bios as bios_module path = rom_path(entry.rom) with tempfile.TemporaryDirectory() as scratch: rom = path if path.suffix == ".zip": with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if n.lower().endswith(".gba")) rom = Path(scratch) / "rom.gba" rom.write_bytes(archive.read(name)) command = [ str(NBA), str(rom), *bios_args(str(bios_module.find(None).source), Path(scratch)), ] command += ["--frames", str(frames), "--png", str(Path(scratch) / "nba.png")] if entry.start == "skip": command.append("--skip-bios") for key in entry.keys: command += ["--keys", key] subprocess.run(command, capture_output=True, check=False, timeout=900) png = Path(scratch) / "nba.png" if not png.exists(): return "none", None pixels = decode_png(png.read_bytes()) rgb = bytes(c for pixel in pixels for c in pixel) match = None if shots: folder, stem = shots (folder / f"{stem}-{frames:05d}-nba.png").write_bytes(png.read_bytes()) ours = folder / f"{stem}-{frames:05d}-check.png" if ours.exists(): same = sum( a == b for a, b in zip(decode_png(ours.read_bytes()), pixels, strict=True) ) match = same / len(pixels) return hashlib.sha256(rgb).hexdigest()[:16], match # ----- baselines ---------------------------------------------------------------------------- def load_baseline() -> dict[tuple[str, int], dict]: table = {} if not BASELINE.exists(): return table for raw in BASELINE.read_text(encoding="utf-8").splitlines(): if not raw or raw.startswith("#"): continue rom, frame, picture, state, sound, nba = raw.split("\t") table[(rom, int(frame))] = {"picture": picture, "state": state, "sound": sound, "nba": nba} return table def write_baseline(results: list[Result], old: dict[tuple[str, int], dict], commit: str) -> None: table = dict(old) for result in results: for point in result.points: key = (result.entry.rom, point["frame"]) keep = old.get(key, {}).get("nba", "-") table[key] = { "picture": point["picture"], "state": point["state"], "sound": point["sound"], "nba": point.get("nba", keep) if "nba" in point else keep, } order = {e.rom: i for i, e in enumerate(load_set())} rows = sorted( ((rom, frame, v) for (rom, frame), v in table.items() if rom in order), key=lambda r: (order[r[0]], r[1]), ) lines = [ f"# {SET.stem} baselines from gba-python {commit}: rom, frame, picture, state, sound, nba", "# nba: NanoBoyAdvance 1.8.3's picture hash at that frame (- = not run), a detector", ] lines += [ f"{rom}\t{frame}\t{v['picture']}\t{v['state']}\t{v['sound']}\t{v['nba']}" for rom, frame, v in rows ] BASELINE.write_text("\n".join(lines) + "\n", encoding="utf-8") def commit() -> str: done = subprocess.run( ["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True, cwd=ROOT ) dirty = subprocess.run( ["git", "status", "--porcelain", "--", "src"], capture_output=True, text=True, cwd=ROOT ) return done.stdout.strip() + ("+dirty" if dirty.stdout.strip() else "") # ----- report ------------------------------------------------------------------------------- def judge(result: Result, baseline: dict[tuple[str, int], dict]) -> tuple[str, list[str]]: """``pass``, ``changed``, ``new``, ``crash`` or ``hang``, with what moved.""" if result.status != "ok": return result.status, [result.error] notes, verdict = [], "pass" for point in result.points: old = baseline.get((result.entry.rom, point["frame"])) if old is None: verdict = "new" if verdict == "pass" else verdict continue moved = [k for k in ("picture", "state", "sound") if point[k] != old[k]] if moved: verdict = "changed" notes.append(f"@{point['frame']}: {', '.join(moved)}") nba = point.get("nba") if nba and nba != "none": match = point.get("nba_match") if nba == point["picture"]: notes.append(f"@{point['frame']}: = NBA") elif match is not None: notes.append(f"@{point['frame']}: {match:.0%} of NBA's pixels") elif old.get("nba") == old["picture"]: verdict = "changed" notes.append(f"@{point['frame']}: no longer = NBA") else: notes.append(f"@{point['frame']}: != NBA (flag)") return verdict, notes def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--one", help=argparse.SUPPRESS) parser.add_argument("--quick", action="store_true", help="only the checkpoints marked q") parser.add_argument( "--set", type=Path, help="another list in the same form (tests/games_set.txt); its baselines are " "NAME_baseline.txt beside it", ) parser.add_argument("--only", action="append", default=[], help="entries whose ROM has TEXT") parser.add_argument( "-j", "--jobs", type=int, default=min(16, max(1, (os.cpu_count() or 2) // 2)) ) parser.add_argument("--timeout", type=int, default=1800, help="seconds per entry") parser.add_argument("--record", action="store_true", help="write tests/smoke_baseline.txt") parser.add_argument("--nba", action="store_true", help="diff pictures with NBA 1.8.3") parser.add_argument("--dump", type=Path, help="write checkpoint PNGs (and --every) here") parser.add_argument("--every", type=int, default=0, help="with --dump: a PNG every N frames") parser.add_argument("--json", type=Path, help="write every result as JSON") parser.add_argument("--frames", type=int, help="override: one checkpoint at N (exploring)") args = parser.parse_args() if args.one: print(json.dumps(run_one(json.loads(args.one)))) return 0 if args.set: global SET, BASELINE SET = args.set.resolve() BASELINE = SET.with_name(SET.name.replace("_set", "_baseline")) entries = load_set() if args.quick: entries = [e for e in entries if e.quick] for entry in entries: entry.checkpoints = entry.quick if args.only: entries = [e for e in entries if any(t.lower() in e.rom.lower() for t in args.only)] missing = [e for e in entries if not rom_path(e.rom).exists()] for entry in missing: print(f"skip {short(entry.rom)}: not in the local set") entries = [e for e in entries if e not in missing] if args.frames: for entry in entries: entry.checkpoints = [args.frames] if args.dump: args.dump.mkdir(parents=True, exist_ok=True) # longest first, so the pool's tail is short entries.sort(key=lambda e: -e.frames) baseline = load_baseline() began = time.monotonic() results: list[Result] = [] counts: dict[str, int] = {} with ThreadPoolExecutor(args.jobs) as pool: futures = [pool.submit(launch, entry, args) for entry in entries] for future in futures: result = future.result() results.append(result) verdict, notes = judge(result, baseline) counts[verdict] = counts.get(verdict, 0) + 1 modes = "/".join(str(p["mode"]) for p in result.points) print( f"{verdict:7} {short(result.entry.rom)[:60]:60} {result.seconds:6.0f} s" f" mode {modes or '-'} {'; '.join(notes)}", flush=True, ) wall = time.monotonic() - began summary = ", ".join(f"{n} {k}" for k, n in sorted(counts.items())) print(f"{len(results)} entries in {wall / 60:.1f} min wall (-j {args.jobs}): {summary}") if args.json: args.json.write_text( json.dumps( [ { "rom": r.entry.rom, "status": r.status, "seconds": round(r.seconds, 1), "points": r.points, "info": r.info, "error": r.error, } for r in results ], indent=1, ) ) if args.record: write_baseline([r for r in results if r.status == "ok"], baseline, commit()) print(f"recorded {BASELINE}") return 0 return 0 if set(counts) <= {"pass"} else 1 if __name__ == "__main__": sys.exit(main())