#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Seeded faults: a gate that cannot fail proves nothing (methodology, "Gates"). Two kinds, each run through the gate and each required to be **caught** (the gate fails): 1. **The reference's own faults, applied to this board** (no rebuild): its named board faults (``board.faults``: ``fast-tia``, ``ignore-lock``, ``end-test-zero``, ``last-line-cost-dropped``, ``dli-early``; and the two detector settings ``dli-clear-on-nmi``, ``c23-mame``, which must also part from the board) through ``a7800-trace --fault`` on the lockstep cases that exercise them; its window faults (``keys``, ``pixels``, ``composite``) through ``a7800-play --judge --fault``. 2. **One-line source faults** (the reference's script-level faults ported, and faults in what Rust added: the DMA state machine, the port, the hand-off, save states, the sound tap): the tree is copied to ``external/faults-tree`` (files written fresh, so their timestamps are new and cargo cannot reuse a stale build: the 2026-11-13 lesson), one line is changed, the trace binary is built into ``external/faults-target``, and the named cases are run against the cached reference traces. The original line is written back after each. A fault that changes nothing observable on its cases is reported as such (an equivalent mutant or a blind spot), not counted as caught. python3 scripts/seeded_faults.py [--only REGEX] """ from __future__ import annotations import argparse import os import re import shutil import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TREE = ROOT / "external" / "faults-tree" TARGET = ROOT / "external" / "faults-target" CACHE = ROOT / "external" / "refcache" EMU = ROOT.parent # (name, cases regex) for the reference's named faults NAMED = [ ("fast-tia", r"^m2/asteroids$"), # after the lock a 7800 title's own TIA writes (sound) must not reach the latch; in # 2600 mode the 7800 board no longer runs after the hand-off, so a 7800 case judges it ("ignore-lock", r"^m2/asteroids$"), # the titles that end lists with a non-zero byte 1 (C5: Ninja Golf, Crossbow) ("end-test-zero", r"^(scheme/supergame-bank6-behaviour-ninjagolf|gun/crossbow)$"), ("last-line-cost-dropped", r"^m2/asteroids$"), ("dli-early", r"^(m2/joust|c23/dliprobe-ntsc)$"), ("dli-clear-on-nmi", r"^c23/dliprobe-ntsc$"), ("c23-mame", r"^c23/dliprobe-(ntsc|pal)$"), ] WINDOW = ["keys", "pixels", "composite"] # (name, file, old line fragment, new fragment, cases regex) SOURCE = [ # the reference's script-level faults, ported ("gun-blind (controller_faults.py)", "src/controllers.rs", "(maria.pixels[clock as usize] & 0x0F) >= Self::BRIGHT", "false", r"^gun/"), ("two-button-always (controller_faults.py)", "src/controllers.rs", "riot.ddr_b & bit != 0 && riot.out_b & bit == 0", "true", r"^twobutton/"), ("maria-sees-sally (m7_banksets.py)", "src/cartridge/schemes.rs", "self.maria.access(address, data, true, halt, t)", "self.sally.access(address, data, true, halt, t)", r"^scheme/bankset"), ("data bus not carried over (gates_2600 smoke)", "src/mode2600.rs", "board.data_bus = old.data_bus;", "board.data_bus = 0;", r"^m2600/"), # Rust-specific: what the transcription added or had to restructure ("DMA engine: CWIDTH's second byte from address + 2", "src/maria.rs", "((self.address + 1) & 0xFFFF)", "((self.address + 2) & 0xFFFF)", r"^(m2|scheme)/"), ("DMA engine: the VBE fetch's tail 4 clocks, not 2", "src/maria.rs", "return Some(VBE_COST - 6);", "return Some(VBE_COST - 4);", r"^m2/asteroids$"), ("DMA engine: a header's cut-off test one clock late", "src/maria.rs", " if m.clock_in_line + 4 > LRC {\n self.label = Label::AfterLoop; // cut off", " if m.clock_in_line + 3 > LRC {\n self.label = Label::AfterLoop; // cut off", r"^(m2|scheme)/"), ("picture: the border always black", "src/maria.rs", "let border = if self.ctrl & 0x08 != 0 { background } else { 0 };", "let border = 0;", r"^(m2|scheme|pal)/"), ("Kangaroo bit ignored (first cell)", "src/maria.rs", " if colour != 0 || kangaroo {\n", " if colour != 0 {\n", r"^(m2|scheme|pal)/"), ("port: the cartridge not ticked (POKEY stops)", "src/board.rs", " self.cartridge.tick(self.data_bus);\n", "", r"^scheme/(supergame-pokey|linear-pokey)"), ("sound tap: POKEY weight 0.5", "src/sound.rs", "pub const POKEY_WEIGHT: f64 = 1.0;", "pub const POKEY_WEIGHT: f64 = 0.5;", r"^scheme/supergame-pokey"), ("Activision bank select two bits", "src/cartridge/schemes.rs", "self.bank = address_u & 7;", "self.bank = address_u & 3;", r"^scheme/activision"), ("two-button line of port 2 on SWCHB D3", "src/controllers.rs", "{ 0x04 } else { 0x10 }", "{ 0x04 } else { 0x08 }", r"^twobutton/"), ("save state: the cartridge not restored", "src/state.rs", " board.cartridge.restore(&whole.cartridge)?;\n", "", r"^scheme/(supergame|activision|absolute)", ), ] # Faults the case table cannot see, each with why (methodology: an equivalent mutant is # noted, not counted; a real fault the gate misses is a recorded blind spot). The script # passes while these stay uncaught and everything else is caught; a newly caught one is # simply counted. KNOWN_UNCAUGHT = { "data bus not carried over (gates_2600 smoke)": "equivalent on these cases: the first cycle after the hand-off refills the latch", "Kangaroo bit ignored (first cell)": "blind spot: no case draws in Kangaroo mode", } def run(cmd, **kw): return subprocess.run(["nice", "-n", "19", *cmd], capture_output=True, text=True, **kw) def lockstep(rust: Path, only: str, extra: list[str], save: bool = False) -> tuple[bool, str]: cmd = [sys.executable, str(ROOT / "scripts/lockstep.py"), "--rust", str(rust), "--reference-cache", str(CACHE), "--only", only, "--traces", str(ROOT / "external/faults-traces"), "--jobs", "3", *extra] if save: cmd.append("--save-at-half") out = run(cmd, timeout=14400) last = out.stdout.strip().splitlines()[-1] if out.stdout.strip() else out.stderr.strip()[-300:] return out.returncode != 0, last def copy_tree() -> None: for sub in ("src", "tests"): for path in (ROOT / sub).rglob("*"): if path.is_file(): target = TREE / path.relative_to(ROOT) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, target) # fresh timestamps manifest = (ROOT / "Cargo.toml").read_text() for dep in ("a2600-rust", "6502-rust", "pokey-rust"): manifest = manifest.replace(f'path = "../{dep}"', f'path = "{EMU / dep}"') (TREE / "Cargo.toml").write_text(manifest) shutil.copyfile(ROOT / "Cargo.lock", TREE / "Cargo.lock") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", help="a regular expression on the fault name") args = parser.parse_args() keep = lambda name: not args.only or re.search(args.only, name) # noqa: E731 caught = total = 0 rust = ROOT / "target/release/a7800-trace" for name, cases in NAMED: if not keep(name): continue hit, last = lockstep(rust, cases, [f"--rust-extra=--fault {name}"]) total += 1 caught += hit print(f"{'caught' if hit else 'MISSED'}: board fault {name} ({cases}): {last}", flush=True) play = ROOT / "target/release/a7800-play" for name in WINDOW: if not keep(name): continue out = run([str(play), "--judge", "--fault", name], env={**os.environ, "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy"}, timeout=1800) hit = out.returncode != 0 total += 1 caught += hit print(f"{'caught' if hit else 'MISSED'}: window fault {name}: {out.stdout.strip().splitlines()[-1:]}", flush=True) copy_tree() uncaught: list[str] = [] for name, file, old, new, cases in SOURCE: if not keep(name): continue path = TREE / file original = path.read_text() if original.count(old) < 1: print(f"BROKEN: {name}: the line is not in {file}") total += 1 continue path.write_text(original.replace(old, new, 1)) build = run(["cargo", "build", "--release", "-q", "-j", "3", "--bin", "a7800-trace", "--manifest-path", str(TREE / "Cargo.toml"), "--target-dir", str(TARGET)], timeout=3600) path.write_text(original) total += 1 if build.returncode: print(f"BROKEN: {name}: it does not build: {build.stderr.strip()[-300:]}") continue save = file == "src/state.rs" hit, last = lockstep(TARGET / "release/a7800-trace", cases, [], save=save) caught += hit known = KNOWN_UNCAUGHT.get(name) if not hit and known: uncaught.append(name) print(f"not caught (recorded: {known}): {name} ({cases}): {last}", flush=True) continue print(f"{'caught' if hit else 'MISSED'}: {name} ({cases}): {last}", flush=True) print(f"seeded faults: {caught} of {total} caught ({len(uncaught)} recorded as not caught: " f"{', '.join(uncaught) or 'none'})") return 0 if caught + len(uncaught) == total else 1 if __name__ == "__main__": sys.exit(main())