# SPDX-License-Identifier: MIT """The save-state check's machinery: run mcd-verificator, digest the whole console after every frame, save a state, and continue from it in this process or in a fresh one. A digest is of the state itself (``segacd_python.state.machine_state``: everything a state holds, the three CPUs' captures and the walked graph of the Mega Drive and the CD), so a field a load fails to restore shows as a difference at once, and state kept outside the saved objects that changes what the console does next shows on the first frame it matters. Each frame's digest is kept per component (``system.board.vdp``, ``system.board.port.cdc``, ``sub68k``, ...), so a failure names where it diverged. ``python tests/savestate_check.py STATE FIRST LAST OUT``: the fresh-process half (build the console, load STATE, which was saved after frame FIRST, run through frame LAST, write the digests to OUT as JSON). The drive holds ``SEGACD_DISC``'s disc, as in the half that saved it.""" from __future__ import annotations import hashlib import json import os import sys from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] #: KRIKzz's mcd-verificator, fetched by scripts/fetch_references.py; it stands in for the #: BIOS (its readme's option 1), so the check needs no Sega code. VERIFICATOR = ROOT / "reference/src/mcd-verificator/mcd-verificator/mcd-verificator.bin" #: A disc for the drive (a .cue, or a zip of a CUE and its BINs), by environment variable; #: without one the check runs with the drive empty. DISC_VARIABLE = "SEGACD_DISC" def _is_object(value: Any) -> bool: return isinstance(value, dict) and "fields" in value def _components(encoded: Any, path: str, depth: int, out: dict[str, str]) -> None: """Digest ``encoded`` per object, ``depth`` objects deep: each object's own values in one digest, and the objects it holds (directly or in a list) in their own, each label carrying its class, so a component reads as ``system.board.cartridge.pages[0].cdd`` wherever the walk first met it.""" if not _is_object(encoded) or depth == 0: text = json.dumps(encoded, sort_keys=True, separators=(",", ":")) out[path] = hashlib.blake2b(text.encode(), digest_size=8).hexdigest() return label = f"{path}<{encoded['object'].rsplit('.', 1)[-1]}>" own = {} for name, value in encoded["fields"].items(): if _is_object(value): _components(value, f"{label}.{name}", depth - 1, out) elif isinstance(value, list) and any(_is_object(item) for item in value): for i, item in enumerate(value): if _is_object(item): _components(item, f"{label}.{name}[{i}]", depth - 1, out) else: own[f"{name}[{i}]"] = item else: own[name] = value text = json.dumps(own, sort_keys=True, separators=(",", ":")) out[label] = hashlib.blake2b(text.encode(), digest_size=8).hexdigest() def digest(system: object, skipped: set[str] | None = None) -> dict[str, str]: """The console's digest per component, six objects into the graph.""" from segacd_python.state import machine_state body = machine_state(system, skipped) # type: ignore[arg-type] out: dict[str, str] = {} for cpu in ("m68k", "z80", "sub68k"): _components(body[cpu], cpu, 0, out) _components(body["system"], "system", 6, out) return out def disc_path() -> Path | None: value = os.environ.get(DISC_VARIABLE) return Path(value) if value else None def build_machine(disc: Path | None) -> tuple[object, object]: """mcd-verificator as the BIOS with a RAM cartridge in the slot, as the gate runs it (docs/status.md), and the drive holding ``disc`` or nothing.""" from segacd_python.console import build from segacd_python.disc import Disc from segacd_python.ramcart import RAMCartridge loaded = Disc.open(disc, ROOT / "runs/discs") if disc is not None else None return build("genesis", VERIFICATOR.read_bytes(), RAMCartridge(), disc=loaded) def run_frame(system: object, device: object) -> None: """One frame as ``python -m segacd_python`` runs it without ``--wav``: the frame, then the sample queues drained.""" system.run_frame() # type: ignore[attr-defined] system.board.fm.take_samples() # type: ignore[attr-defined] system.board.psg.take_samples() # type: ignore[attr-defined] for source in device.audio_sources: # type: ignore[attr-defined] source.take_samples(system.mclk) # type: ignore[attr-defined] def run_digests(system: object, device: object, first: int, last: int) -> list[dict[str, str]]: """Frames ``first``..``last`` (``system`` stands after frame ``first - 1``).""" digests = [] for _frame in range(first, last + 1): run_frame(system, device) digests.append(digest(system)) return digests def save(path: Path, system: object, frame: int, skipped: set[str] | None = None) -> None: """As ``python -m segacd_python --save-state`` writes it (``skipped``: attribute names left out of the state, for seeding faults).""" from segacd_python.state import save_state path.write_bytes(save_state(system, {"frame": frame}, skipped=skipped)) # type: ignore[arg-type] def load(path: Path, disc: Path | None) -> tuple[object, object, int]: """A freshly built console with the state at ``path`` loaded; and its frame.""" from segacd_python.state import load_state system, device = build_machine(disc) host = load_state(system, path.read_bytes()) # type: ignore[arg-type] return system, device, host["frame"] def first_divergence( straight: list[dict[str, str]], other: list[dict[str, str]], first: int ) -> str | None: """None when identical, else the first frame that differs and its components.""" for offset, (a, b) in enumerate(zip(straight, other, strict=True)): if a != b: parts = sorted(key for key in set(a) | set(b) if a.get(key) != b.get(key)) return f"frame {first + offset}: {', '.join(parts)}" return None def main(argv: list[str]) -> int: state, first, last, out = Path(argv[0]), int(argv[1]), int(argv[2]), Path(argv[3]) system, device, frame = load(state, disc_path()) assert frame == first, (frame, first) digests = [digest(system), *run_digests(system, device, first + 1, last)] out.write_text(json.dumps(digests)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))