#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The save-state rung: every case of ``scripts/cases.tsv`` run twice by ``md-trace``, once straight through and once interrupted, and the two traces compared line for line. The interrupted run saves a state a third of the way in, 1,777 68000 steps into the frame (part way down it), loads it into a freshly built system and goes on with that one (``--save-at``); saves again at the half, at the frame's start; and at two thirds takes a snapshot, runs three frames, and puts the snapshot back into the same system (``--rewind-at``, rewind's and run-ahead's path). Every line of the trace -- per frame the CPUs, memory CRCs, every VDP field, the picture, the FM's and the PSG's samples and the mixed sound -- must equal the uninterrupted run's. The uninterrupted run is the one rung 2 (``scripts/lockstep.py``) holds identical to megadrive-python, so identical here is the reference's run continued through a save state (the reference's own save states are proved the same way, by its ``scripts/state_roundtrip.py``). python3 scripts/state_rung.py [--only NAME ...] [--jobs N] [--frames N] [--rust PATH] python3 scripts/state_rung.py --faults [--frames 900] python3 scripts/state_rung.py --reference [--only NAME ...] ``--reference``: the interrupted run is megadrive-python's (``scripts/md_trace.py`` with the same options, through the reference's own save states), judged by the same uninterrupted ``md-trace``. The two tiers' formats are not shared (src/state.rs), so this is the cross-tier check: each tier's state continues as the other tier's run. ``--faults``: the rung's own seeded faults (:data:`FAULTS`, each one change to the save state code in a copy of ``src/``, built with fresh timestamps so cargo cannot reuse a stale build): each faulted ``md-trace`` runs every case interrupted, against the clean binary's uninterrupted trace, and is caught when any case differs or fails. Stdlib only; the cases' romsets come from the environment as in lockstep.py. """ from __future__ import annotations import argparse import os import re import shutil import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from lockstep import REPO, cases, first_difference, missing # noqa: E402 #: (name, file, the text, its replacement). Each text occurs exactly once. FAULTS = [ ("the HINT counter not saved", "src/vdp.rs", " pub hint_counter: i64,", " #[serde(skip)]\n pub hint_counter: i64,"), ("the FIFO not saved", "src/vdp.rs", " pub fifo: [FifoEntry; 4],", " #[serde(skip)]\n pub fifo: [FifoEntry; 4],"), ("the long and short H40 lines swapped", "src/state.rs", "3 => &t.h40_long,", "3 => &t.h40_short,"), ("the frame table always V28 NTSC", "src/state.rs", ".get(index)\n .copied()", ".get(0)\n .copied()"), ("the Z80's held instruction not restored", "src/state.rs", "md.z80_partial = self.z80_partial;", "md.z80_partial = None;"), ("the 68000's clock not restored", "src/state.rs", "clock: f.clock,", "clock: 0,"), ("the Z80's EI delay not restored", "src/state.rs", "ei_delay: f.ei_delay,", "ei_delay: 0,"), ("the stall credit not restored", "src/state.rs", "md.stall_credited = self.stall_credited;", "md.stall_credited = 0;"), ("the DSP's RAM not restored", "src/state.rs", "dsp.ram.copy_from_slice(&f.ram);", "let _ = &f.ram;"), ("the analogue filter not saved", "src/audio.rs", " filter: Vec<(f64, f64)>,", " #[serde(skip)]\n filter: Vec<(f64, f64)>,"), ("the 6-button pad's edges not saved", "src/io.rs", " pub edges: u8,", " #[serde(skip)]\n pub edges: u8,"), ("the Sega mapper's banks not saved", "src/cartridge.rs", " pub banks: [u8; 8],", " #[serde(skip)]\n pub banks: [u8; 8],"), ("the EEPROM's address not saved", "src/eeprom.rs", " pub address: usize,", " #[serde(skip)]\n pub address: usize,"), ("the sprite cache not saved", "src/render.rs", " #[serde(with = \"serde_big_array::BigArray\")]\n pub sprite_cache: [u8; 80 * 4],", " #[serde(skip, default = \"empty_cache\")]\n pub sprite_cache: [u8; 80 * 4],"), ] WORK = REPO / "external/state-faults" def slug(name: str) -> str: return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") def build(fault) -> tuple[Path, bool]: """The faulted ``md-trace``, and whether the faulted copy fails ``tests/state.rs``.""" name, path, old, new = fault work = WORK / "work" if work.exists(): shutil.rmtree(work) # our own scratch copy under external/ # shutil.copy, not copy2: fresh timestamps, so cargo rebuilds what changed back. shutil.copytree(REPO / "src", work / "src", copy_function=shutil.copy) shutil.copytree(REPO / "tests", work / "tests", copy_function=shutil.copy) manifest = (REPO / "Cargo.toml").read_text() (work / "Cargo.toml").write_text(manifest.replace('path = "../', f'path = "{REPO.parent}/')) shutil.copy(REPO / "Cargo.lock", work / "Cargo.lock") source = (work / path).read_text() if source.count(old) != 1: raise SystemExit(f"{name}: the text occurs {source.count(old)} times in {path}") source = source.replace(old, new) if "empty_cache" in new: source += "\nfn empty_cache() -> [u8; 80 * 4] {\n [0; 80 * 4]\n}\n" (work / path).write_text(source) env = dict(os.environ, CARGO_TARGET_DIR=str(WORK / "target")) subprocess.run(["nice", "rustup", "run", "stable", "cargo", "build", "--release", "-q", "--bin", "md-trace"], cwd=work, env=env, check=True) # fmt: skip binary = WORK / "bin" / slug(name) binary.parent.mkdir(parents=True, exist_ok=True) shutil.copy(WORK / "target/release/md-trace", binary) tests = subprocess.run(["nice", "rustup", "run", "stable", "cargo", "test", "--release", "-q", "--test", "state"], cwd=work, env=env, capture_output=True, text=True) # fmt: skip return binary, tests.returncode != 0 def interruptions(frames: int) -> list[str]: return [ "--save-at", f"{frames // 3}+1777", "--save-at", f"{frames // 2}", "--rewind-at", f"{2 * frames // 3}", ] # fmt: skip def run_case(case, rust: Path, out: Path, frames: int | None, clean: Path | None = None, python: Path | None = None): # fmt: skip """``clean``: the binary whose uninterrupted run is the judge (``--faults``); ``python``: the reference's interpreter, whose run is the interrupted one.""" name, count, cart, args = case count = min(count, frames) if frames else count why = missing(cart) if why: return name, count, "MISSING", why, 0.0 plain, saved = out / f"{name}.plain.trace", out / f"{name}.saved.trace" common = [str(rust), cart, "--frames", str(count), *args] started = time.perf_counter() judge = [str(clean), *common[1:]] if clean else common a = subprocess.run(["nice", *judge, "--out", str(plain)], capture_output=True, text=True) interrupted = [str(python), str(HERE / "md_trace.py"), *common[1:]] if python else common b = subprocess.run( ["nice", *interrupted, *interruptions(count), "--out", str(saved)], capture_output=True, text=True, ) # fmt: skip seconds = time.perf_counter() - started if a.returncode or b.returncode: return name, count, "ERROR", (a.stderr + b.stderr).strip()[-300:], seconds if plain.read_bytes() == saved.read_bytes(): lines = sum(1 for _ in plain.open()) lock = next((l for l in plain.open() if l.startswith("L ")), "") note = f"{lines} lines" + (f"; both stop: {lock.strip()}" if lock else "") return name, count, "identical", note, seconds return name, count, "DIFFERENT", first_difference(plain, saved), seconds def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", action="append", default=[]) parser.add_argument("--jobs", type=int, default=14) parser.add_argument("--frames", type=int, help="override every case's frame count") parser.add_argument("--rust", type=Path, default=REPO / "target/release/md-trace") parser.add_argument("--out", type=Path, default=REPO / "external/state-traces") parser.add_argument("--faults", action="store_true", help="run the seeded faults") parser.add_argument("--reference", action="store_true", help="the interrupted run is megadrive-python's") # fmt: skip parser.add_argument( "--python", type=Path, default=REPO / "external/megadrive-python/.venv/bin/python" ) args = parser.parse_args() if args.faults: return faults(args) args.out.mkdir(parents=True, exist_ok=True) selected = [c for c in cases() if not args.only or c[0] in args.only] failed = 0 with ThreadPoolExecutor(args.jobs) as pool: python = args.python if args.reference else None jobs = [pool.submit(run_case, c, args.rust, args.out, args.frames, None, python) for c in selected] # fmt: skip for job in jobs: name, count, verdict, note, seconds = job.result() failed += verdict != "identical" print(f"{name:22} {count:6} frames {verdict:9} {seconds:6.1f} s {note}", flush=True) print(f"{len(selected) - failed} of {len(selected)} identical through a save state") return 1 if failed else 0 def faults(args: argparse.Namespace) -> int: selected = [c for c in cases() if not missing(c[2])] # every case: --only names faults caught = 0 chosen = [f for f in FAULTS if not args.only or slug(f[0]) in args.only] for fault in chosen: binary, tests_failed = build(fault) out = WORK / "traces" / slug(fault[0]) out.mkdir(parents=True, exist_ok=True) with ThreadPoolExecutor(args.jobs) as pool: results = list(pool.map( lambda c: run_case(c, binary, out, args.frames or 900, args.rust), selected)) # fmt: skip found = [f"{name} ({note})" for name, _c, verdict, note, _s in results if verdict != "identical"] if tests_failed: found.insert(0, "cargo test --test state") caught += bool(found) verdict = f"caught by {len(found)} of {len(selected) + 1}, first {found[0][:90]}" if found else "MISSED" print(f"{fault[0]:42} {verdict}", flush=True) print(f"{caught} of {len(chosen)} caught") return 0 if caught == len(chosen) else 1 if __name__ == "__main__": sys.exit(main())