#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 4's full compatibility sweep: every game's frames on the board against Mesen2's. The smoke list's method (scripts/smoke.py) over a whole folder, with every result classified: EMU_TOOLS_GPL=... PYPY_GC_NURSERY=1M nice .venv-pypy/bin/python -I \ scripts/sweep.py run --jobs 16 [--at 300 --at 900] python3 -I scripts/sweep.py summary tests/mame_traces/sweep/results--at.jsonl \ --failures tests/sweep-failures.txt ``run`` takes every ``.zip`` in ``$NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System`` (the main set only: the Private, Aftermarket, Satellaview and Sufami Turbo folders are not read), or the names in ``--list FILE`` (the smoke list's format). It runs under PyPy, a pool of long-lived workers (the JIT warms once per worker, not once per game); each game gets Mesen2's frames first through the system Python (``sweep.py mesen``: mesen2-runner, ``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes``, a GPL tool run by path, needs Pillow), then the board under a CPU-time limit (``--timeout``), so a stuck board is a result, not a stuck sweep, and a slow one on a busy machine is not called stuck. Per game and checkpoint (default 300 and 900 frames from power-on, no input), Mesen2's frame is taken once (``--region ntsc``: the board is an NTSC console, so a PAL game is compared on an NTSC console on both sides), and the board's frames ``--window`` either side of the checkpoint are compared with it at the vertical alignments smoke.py uses, nearest first: a reset-phase lag of up to W frames still shows as exact. Mesen2 b9fa69d is a closed box, so a difference is a lead, not a judgement (OBSERVED, via mesen2-runner 0.2.0). Its power-on RAM is the runner's default, zeros, and every frame is drawn (the old driver, until 2026-11-24, left frame skipping on; the cached frames under ``tests/mame_traces/sweep/`` from before that date came from it). Categories (``summary``), in this order: - ``unsupported``: MAME's software list (CC0; header_census.py) names a board other than plain LoROM/HiROM (a coprocessor, a special mapper), or, for an image the list lacks, the header's chipset byte names a coprocessor; counted as unsupported unless exact at every checkpoint; - ``crash``: the board raised an exception; - ``hang``: the board ran past the CPU-time limit, or the core executed STP, or the board's picture is one colour at every checkpoint while Mesen2's is not; - ``exact``: exact at every checkpoint; ``step``: the rest one 5-bit step off at every differing pixel (a brightness curve: docs/ppu-status.md U10); ``partial``: exact at some; ``picture``: at none; - ``no referee``: Mesen2 gave no frame. Everything is written under ``tests/mame_traces/sweep/`` (gitignored: pictures of commercial games are never committed); ``--failures`` writes the names that are not exact, by category, in the smoke list's format (the family's rule: a full sweep's failures become the next smoke list). """ from __future__ import annotations import argparse import collections import concurrent.futures import json import os import subprocess import sys import tempfile import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "tests" / "mame_traces" / "sweep" FOLDER = "Nintendo - Super Nintendo Entertainment System" PYPY = ROOT / ".venv-pypy" / "bin" / "python" sys.path.insert(0, str(ROOT / "scripts")) sys.path.insert(0, str(ROOT / "src")) # DOC: fullsnes / SNESdev wiki "ROM header" $FFD6 high nibble (low nibble 3-6: present). CHIPSET = {0x0: "dsp", 0x1: "superfx", 0x2: "obc1", 0x3: "sa1", 0x4: "sdd1", 0x5: "srtc", 0xE: "other", 0xF: "custom"} # fmt: skip def folder() -> Path: path = Path(os.environ.get("NO_INTRO_DIR", "")) / FOLDER if not path.is_dir(): raise SystemExit("set NO_INTRO_DIR") return path def names_from(list_file: Path | None) -> list[str]: if list_file is None: return sorted(p.name[:-4] for p in folder().glob("*.zip")) names = [] for line in list_file.read_text(encoding="utf-8").splitlines(): name = line.split("#", 1)[0].strip() if name: names.append(name) return names def image_of(name: str) -> bytes: with zipfile.ZipFile(folder() / f"{name}.zip") as z: inner = [n for n in z.namelist() if n.lower().endswith((".sfc", ".smc"))] if not inner: raise ValueError("no .sfc/.smc in the archive") return z.read(inner[0]) def slug(name: str) -> str: # Longer than smoke.py's 60 characters: the whole set has many shared prefixes. return "".join(c if c.isalnum() else "_" for c in name)[:120] def board_class(image: bytes, softlist: tuple | None) -> str: """The board: MAME's software-list slot (DOC, CC0) or, unlisted, the header's chipset.""" from header_census import lookup from snes_python.cartridge import find_header if len(image) % 1024 == 512: image = image[512:] if len(image) < 0x8000: # Super 8, Tri-Star: an adapter's own program, no SNES header return "adapter (under 32 KiB)" if softlist is not None: whole, first, sizes = softlist entry = lookup(image, whole, first, sizes) if entry is not None: return entry["slot"] or "unknown" try: header = find_header(image) except ValueError: return "no header" chipset = header.chipset if chipset in (0x00, 0x01, 0x02) or (chipset & 0x0F) not in (3, 4, 5, 6, 9, 10): return f"{header.kind} (unlisted)" return f"{header.kind}_{CHIPSET.get(chipset >> 4, 'unknown')} (unlisted, header)" PLAIN = {"lorom", "hirom", "lorom (unlisted)", "hirom (unlisted)", "exhirom (unlisted)"} # -- Mesen2 (system Python) --------------------------------------------------------------- def mesen_frames(name: str, checkpoints: list[int]) -> bool: from emu_tools import mesen2_frames # mesen2-runner, a GPL tool run by path (EMU_TOOLS_GPL) target = OUT / slug(name) target.mkdir(parents=True, exist_ok=True) missing = [at for at in checkpoints if not (target / f"mesen-{at:05d}.png").exists()] if not missing: return True from PIL import Image with tempfile.TemporaryDirectory() as tmp: rom = Path(tmp) / "game.sfc" rom.write_bytes(image_of(name)) got = mesen2_frames(rom, missing, Path(tmp) / "runs", region="ntsc", timeout=300) for at in missing: if got[at] is None: return False Image.open(got[at]).convert("RGB").save(target / f"mesen-{at:05d}.png") return True # -- the board (PyPy) --------------------------------------------------------------------- def blank(rgb: bytes | bytearray) -> bool: first = bytes(rgb[:3]) return bytes(rgb) == first * (len(rgb) // 3) def aligned_steps(picture: tuple, frame: tuple) -> tuple[int, int]: """(pixels whose 5-bit values differ, pixels off by two 5-bit steps or more), at the best of smoke.py's vertical alignments (fewest of the second kind first). A difference of one step everywhere is what a brightness-curve disagreement looks like (docs/ppu-status.md U10).""" from ppu_pictures import scale w, h, rgb = picture mw, mh, ref = frame fy = 2 if mh > 300 and h < 300 else 1 fx = mw // w if mw % w == 0 else 1 if fx != 1 or fy != 1: rgb = scale(w, h, rgb, w * fx, h * fy) or rgb w, h = w * fx, h * fy if w != mw: return (10**9, 10**9) unit = 2 if mh > 300 else 1 best = (10**9, 10**9) for top in (7 * unit, 0, unit, 8 * unit, 6 * unit): rows = min(h, mh - top) if rows <= 0: continue base = top * w * 3 strict = big = 0 for i in range(0, rows * w * 3, 3): worst = 0 for c in (i, i + 1, i + 2): d = (rgb[c] >> 3) - (ref[base + c] >> 3) if d < 0: d = -d worst = max(worst, d) if worst: strict += 1 if worst > 1: big += 1 if (big, strict) < (best[1], best[0]): best = (strict, big) if best[0] == 0: break return best class Overrun(BaseException): """The game's CPU-time limit ran out (a BaseException: the board's own errors are caught).""" def _overrun(signum: int, frame: object) -> None: raise Overrun def board_one(name: str, checkpoints: list[int], window: int, limit: int = 0) -> dict: """One game on the board; ``limit`` CPU seconds (ITIMER_PROF), 0 for none. The limit is CPU time, not wall time: on a shared machine a slow run is not a stuck one. """ import signal from mame_lockstep import ipl_rom from snes_python.board import SNES from snes_python.cartridge import Cartridge from snes_python.ppu_png import read_png, write_png target = OUT / slug(name) target.mkdir(parents=True, exist_ok=True) result: dict = {"name": name, "checkpoints": {}} began = time.monotonic() snes = None done = 0 if limit: signal.signal(signal.SIGPROF, _overrun) signal.setitimer(signal.ITIMER_PROF, limit) try: snes = SNES(Cartridge(image_of(name)), ipl=ipl_rom()) for at in checkpoints: ref_path = target / f"mesen-{at:05d}.png" mesen = read_png(ref_path) if ref_path.exists() else None pictures = {} for lag in range(window, -window - 1, -1): snes.run_frames(at - lag - done) done = at - lag pictures[lag] = snes.ppu.picture() write_png(target / f"board-{at:05d}.png", *pictures[0]) entry: dict = {"board_blank": all(blank(p[2]) for p in pictures.values())} if mesen is None: entry["verdict"] = "no referee" else: entry["mesen_blank"] = blank(mesen[2]) best = None for lag in sorted(pictures, key=lambda t: (abs(t), t)): strict, big = aligned_steps(pictures[lag], mesen) # Ranked by the pixels two steps or more off first: a fade one frame out # of phase is one step off nearly everywhere, which says less than a # few pixels of different content. if best is None or (big, strict) < (best[1], best[0]): best = (strict, big, lag) if strict == 0: break assert best is not None entry["lag"] = best[2] # Mesen2's frame minus the board's entry["pixels"] = best[0] entry["big"] = best[1] # pixels off by two 5-bit steps or more # "step": every differing pixel one 5-bit step off (a brightness curve, U10). entry["verdict"] = ( "exact" if best[0] == 0 else "step" if best[1] == 0 else "differs" ) result["checkpoints"][str(at)] = entry except Overrun: result["timeout"] = limit result["reached"] = snes.frame if snes is not None else 0 except Exception as error: # noqa: BLE001 - one game's failure is a result import traceback frames = traceback.extract_tb(error.__traceback__) result["error"] = f"{type(error).__name__}: {error}"[:300] result["where"] = f"{Path(frames[-1].filename).name}:{frames[-1].lineno}" if frames else "" finally: if limit: signal.setitimer(signal.ITIMER_PROF, 0) if snes is not None: result["stopped"] = bool(getattr(snes.cpu, "stopped", False)) result["frame"] = snes.frame result["seconds"] = round(time.monotonic() - began, 1) return result # -- the driver (PyPy: a pool of long-lived workers, so the JIT warms up once per worker) --- _SOFTLIST: tuple | None = None def _worker_init() -> None: global _SOFTLIST from header_census import SOFTLIST, load_softlist path = next((p for p in SOFTLIST if p.exists()), None) if path is not None: whole, first = load_softlist(path) _SOFTLIST = (whole, first, {size for size, _ in first}) def one_game(name: str, at: list[int], window: int, limit: int, mesen: bool) -> dict: began = time.monotonic() try: kind = board_class(image_of(name), _SOFTLIST) except Exception as error: # noqa: BLE001 # The DSP-n/ST01x "(Enhancement Chip)" zips hold a coprocessor's firmware, not a cartridge. return { "name": name, "board": "not a cartridge", "error": f"{type(error).__name__}: {error}", } have_ref = True if mesen: # Mesen2's frames first, by the system Python (mesen2-runner needs Pillow) command = [os.environ.get("SWEEP_PYTHON", "python3"), "-I", str(Path(__file__)), "mesen", "--only-name", name] + [x for a in at for x in ("--at", str(a))] # fmt: skip done = subprocess.run(command, capture_output=True, text=True, check=False, timeout=1800) have_ref = "ok" in done.stdout result = board_one(name, at, window, limit) result["board"] = kind result["referee"] = have_ref result["wall"] = round(time.monotonic() - began, 1) return result def run(args: argparse.Namespace) -> int: if sys.implementation.name != "pypy": raise SystemExit( "run the board side under PyPy: .venv-pypy/bin/python -I scripts/sweep.py run" ) if not args.no_mesen: import emu_tools emu_tools.require(emu_tools.MESEN2_RUN) # exit 3, naming EMU_TOOLS_GPL, without it names = names_from(args.list) if args.only: names = [n for n in names if args.only.lower() in n.lower()] OUT.mkdir(parents=True, exist_ok=True) commit = subprocess.run( ["git", "-C", str(ROOT), "rev-parse", "--short", "HEAD"], capture_output=True, text=True, check=False, ).stdout.strip() # fmt: skip dirty = subprocess.run( ["git", "-C", str(ROOT), "status", "--porcelain", "--untracked-files=no", "src"], capture_output=True, text=True, check=False, ).stdout.strip() # fmt: skip at = "-".join(str(a) for a in args.at) results = args.out or OUT / f"results-{commit}{'-dirty' if dirty else ''}-at{at}.jsonl" seen = set() if results.exists() and not args.rerun: # resume for line in results.read_text(encoding="utf-8").splitlines(): done = json.loads(line) if "timeout" not in done: # cut-off runs run again; the last result counts seen.add(done["name"]) todo = [n for n in names if n not in seen] if args.shuffle: # a fixed order that samples the whole set early import random random.Random(0).shuffle(todo) print(f"{len(names)} games, {len(todo)} to run -> {results}", flush=True) # Workers live for the whole pool: max_tasks_per_child deadlocked the first full sweep # after 1,280 games (2026-11-24: the parent asleep, no workers left; the stdlib's worker # replacement races). A pool that breaks (a worker killed) or goes silent for longer than # any game may take is torn down and the games it did not finish run in a new one. done_count = 0 with results.open("a", encoding="utf-8") as sink: for attempt in range(4): if not todo: break unfinished: list[str] = [] pool = concurrent.futures.ProcessPoolExecutor(args.jobs, initializer=_worker_init) futures = { pool.submit(one_game, n, args.at, args.window, args.timeout, not args.no_mesen): n for n in todo } pending = set(futures) while pending: finished, pending = concurrent.futures.wait( pending, timeout=args.timeout * 4, return_when="FIRST_COMPLETED" ) if not finished: unfinished += [futures[f] for f in pending] print(f"pool silent for {args.timeout * 4} s: restarting", flush=True) break for future in finished: name = futures[future] try: result = future.result() except concurrent.futures.process.BrokenProcessPool: unfinished.append(name) continue except Exception as error: # noqa: BLE001 - one game's failure is a result result = {"name": name, "error": f"worker: {error}"} sink.write(json.dumps(result) + "\n") sink.flush() done_count += 1 print(f"[{done_count}] {category(result)[0]:<12} {name}", flush=True) for process in list(getattr(pool, "_processes", {}).values()): process.kill() pool.shutdown(wait=False, cancel_futures=True) if unfinished and attempt == 3: for name in unfinished: sink.write(json.dumps({"name": name, "error": "worker died 4 times"}) + "\n") todo = unfinished return 0 def mesen(args: argparse.Namespace) -> int: import emu_tools emu_tools.require(emu_tools.MESEN2_RUN) # exit 3, naming EMU_TOOLS_GPL, without it names = [args.only_name] if args.only_name else names_from(args.list) with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool: for name, ok in zip(names, pool.map(lambda n: mesen_frames(n, args.at), names)): print(f"{'ok' if ok else 'no frame'}\t{name}", flush=True) return 0 def category(result: dict) -> tuple[str, str]: """(category, detail) for one result (the module docstring's order).""" points = result.get("checkpoints", {}) verdicts = [p.get("verdict") for p in points.values()] exact = bool(verdicts) and all(v == "exact" for v in verdicts) and "error" not in result board = result.get("board", "") if "image too small" in result.get("error", ""): # results from before board_class knew board = "adapter (under 32 KiB)" if board == "unreadable": board = "not a cartridge" if board not in PLAIN and not exact: return "unsupported", board if "timeout" in result: return "hang", f"over {result['timeout']} CPU s, at frame {result.get('reached', '?')}" if "error" in result: return "crash", f"{result['error']} ({result.get('where', '')})" if any(v == "no referee" for v in verdicts): return "no referee", "" if exact: # a stopped core that matches Mesen2 is a game's own stop (a region lockout) return "exact", "STP" if result.get("stopped") else "" if result.get("stopped"): return "hang", "STP" if points and all(p.get("board_blank") and not p.get("mesen_blank") for p in points.values()): return "hang", "blank picture" detail = ", ".join( f"{at}: {p['verdict']}" + (f" {p['pixels']} px" if p["verdict"] != "exact" else "") for at, p in points.items() ) if all(v in ("exact", "step") for v in verdicts): return "step", detail # every difference one 5-bit step: the brightness curve (U10) if any(v == "exact" for v in verdicts): return "partial", detail return "picture", detail def summary(args: argparse.Namespace) -> int: results = {} for line in args.results.read_text(encoding="utf-8").splitlines(): r = json.loads(line) results[r["name"]] = r by: dict[str, list] = collections.defaultdict(list) for name in sorted(results): cat, detail = category(results[name]) by[cat].append((name, detail)) order = ["exact", "step", "partial", "picture", "hang", "crash", "unsupported", "no referee"] print(f"{len(results)} games ({args.results.name})") for cat in order + sorted(set(by) - set(order)): if by.get(cat): print(f" {cat:<12} {len(by[cat])}") if by.get("unsupported"): boards = collections.Counter(d for _, d in by["unsupported"]) print(" unsupported boards: " + ", ".join(f"{b} {n}" for b, n in boards.most_common())) plain = [n for n, r in results.items() if r.get("board") in PLAIN] plain_exact = [n for n in plain if category(results[n])[0] == "exact"] blank = [ n for n in plain_exact if all(p.get("mesen_blank") for p in results[n]["checkpoints"].values()) ] # fmt: skip print( f" plain boards: {len(plain_exact)} of {len(plain)} exact ({len(blank)} of them blank on both sides at every checkpoint)" ) # The handoff brief's acceptance set: licensed (header_census.py's rule), plain boards. from header_census import UNLICENSED licensed = collections.Counter( category(results[n])[0] for n in plain if not UNLICENSED.search(n + ".zip") ) print( f" licensed plain boards: {sum(licensed.values())}: " + ", ".join(f"{c} {licensed[c]}" for c in order if licensed[c]) ) for cat in args.show or []: for name, detail in by.get(cat, []): print(f"{cat}\t{name}\t{detail}") if args.failures: lines = [ '# The full sweep\'s failures (scripts/sweep.py; docs/status.md "The full sweep"),', f"# from {args.results.name}: every game not exact at every checkpoint, by category.", "# Names in $NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System, without", '# ".zip"; run them with: sweep.py run --list tests/sweep-failures.txt', ] for cat in order[1:] + sorted(set(by) - set(order)): if not by.get(cat): continue lines += ["", f"# {cat} ({len(by[cat])})"] width = max(len(n) for n, _ in by[cat]) lines += [f"{n:<{width}} # {d}".rstrip(" #") for n, d in by[cat]] args.failures.write_text("\n".join(lines) + "\n", encoding="utf-8") return 0 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("run") p.add_argument("--list", type=Path, help="names in the smoke list's format (default: all)") p.add_argument("--only") p.add_argument("--at", type=int, action="append") p.add_argument("--window", type=int, default=30) p.add_argument("--jobs", type=int, default=8) p.add_argument("--timeout", type=int, default=1800, help="board CPU seconds per game") p.add_argument("--out", type=Path, help="results file (default: results-.jsonl)") p.add_argument("--no-mesen", action="store_true", help="use only cached Mesen2 frames") p.add_argument("--shuffle", action="store_true", help="run in a fixed shuffled order") p.add_argument( "--rerun", action="store_true", help="run every listed game even if the results file has it (the last result counts)", ) p = sub.add_parser("mesen", help="Mesen2's frames only (system Python, Pillow)") p.add_argument("--list", type=Path) p.add_argument("--only-name") p.add_argument("--at", type=int, action="append") p.add_argument("--jobs", type=int, default=1) p = sub.add_parser("summary") p.add_argument("results", type=Path) p.add_argument("--failures", type=Path) p.add_argument("--show", action="append", help="list one category's games") args = parser.parse_args() if getattr(args, "at", None) is not None or args.command != "summary": args.at = sorted(args.at or [300, 900]) if args.command == "mesen": return mesen(args) if args.command == "run": return run(args) return summary(args) if __name__ == "__main__": sys.exit(main())