#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Seeded faults: build the board with one single-line mutation at a time and check that the lockstep gate catches each (a fault is caught when any case's trace differs from the reference's). python3 scripts/seeded_faults.py [--cases FILE ...] [--only NAME] [--jobs N] The mutations are applied to a copy of the tree (a git worktree at external/faults-tree, built into external/faults-target), never to this checkout; every mutated file is written fresh, so cargo cannot reuse a stale build (methodology, 2026-11-13). The reference's traces come from --reference-cache external/refcache (run scripts/ladder.sh first). Every fault is also judged on cases-midframe.tsv (mid-frame save states). A fault marked "half" (save-state faults) is judged with --save-at-half and --save-mid-half cycle-12345 on the tables and on cases-midframe.tsv; one marked "audio" with --extra=--audio on the tables and cases-midframe.tsv (the Acid5200 table's audio traces are made by the first such run: the ladder runs audio on cases.tsv only). The first two are the reference's own seeded faults (a5200-python board.faults), switched on in the source instead of at run time. Stdlib only. """ from __future__ import annotations import argparse import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TREE = ROOT / "external" / "faults-tree" TARGET = ROOT / "external" / "faults-target" # (name, file, old text, new text, mode): each old text must occur exactly once. FAULTS = [ # the reference's seeded faults (a5200-python board.py, docs/status.md) ("reference: drop_dummy_read", "src/board.rs", " faults: HashSet::new(),", ' faults: HashSet::from(["drop_dummy_read"]),', "plain"), ("reference: steal_one_short", "src/board.rs", " faults: HashSet::new(),", ' faults: HashSet::from(["steal_one_short"]),', "plain"), # ANTIC ("antic: refresh slots end", "src/antic.rs", "(25..58).contains(&c)", "(25..54).contains(&c)", "plain"), ("antic: VCOUNT from cycle 111", "src/antic.rs", "if self.hcount >= 111 {", "if self.hcount >= 112 {", "plain"), ("antic: VBI NMI cycle", "src/antic.rs", "self._nmi_armed = if self.nmien & 0x40 != 0 { 8 } else { 99 };", "self._nmi_armed = if self.nmien & 0x40 != 0 { 9 } else { 99 };", "plain"), ("antic: line buffer period", "src/antic.rs", "self.lb_index = (self.lb_index + 1) % 63;", "self.lb_index = (self.lb_index + 1) % 64;", "plain"), ("antic: character display delay", "src/antic.rs", "const CHAR_DELAY: i32 = 3;", "const CHAR_DELAY: i32 = 4;", "plain"), ("antic: wide playfield stop", "src/antic.rs", "if c == 105 + shift {", "if c == 106 + shift {", "plain"), # GTIA ("gtia: colour write delay", "src/gtia.rs", "3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1,", "3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 1,", "plain"), ("gtia: luma bit 0", "src/gtia.rs", "= value & 0xFE; // DOC: luma bit 0", "= value & 0xFF; // DOC: luma bit 0", "plain"), ("gtia: player-player collisions", "src/gtia.rs", "self.ppl[n] |= players & !bit;", "self.ppl[n] |= players;", "plain"), ("gtia: priority multicolour", "src/gtia.rs", "let sp1 = p1 & n(pf01 & pri23) & n(pri2 & pf23) & (n(p0) | multi);", "let sp1 = p1 & n(pf01 & pri23) & n(pri2 & pf23) & n(p0);", "plain"), ("gtia: hires luminance", "src/gtia.rs", "let lum = colour[5] & 0x0E;", "let lum = colour[6] & 0x0E;", "plain"), # the board ("board: RDY two cycles after WSYNC", "src/board.rs", "self.cycles as i64 >= self.antic.wsync_at + 2", "self.cycles as i64 >= self.antic.wsync_at + 1", "plain"), ("board: refresh leaves the bus", "src/board.rs", " let value = if address == REFRESH {\n self.data_bus", " let value = if address == REFRESH {\n 0xFF", "plain"), ("board: NMI lost on the P push", "src/board.rs", "if self.nmi_lost_on_p_push && self._stack_writes == 3 {", "if self.nmi_lost_on_p_push && self._stack_writes == 2 {", "plain"), ("board: frame row bookkeeping", "src/board.rs", "if self.antic.hcount < 100 {", "if self.antic.hcount < 50 {", "plain"), ("board: F000 mirror", "src/board.rs", " } else if a >= 0xF000 && self.machine.f000_mirror {\n value = self.bios[a & 0x7FF];", " } else if a >= 0xF000 && self.machine.f000_mirror {\n value = self.data_bus;", "plain"), # cartridges ("cart: 16K two-chip layout", "src/cartridge/mappings.rs", "[low, low, high, high]", "[low, high, low, high]", "plain"), ("cart: Bounty Bob first window", "src/cartridge/mappings.rs", "self.bank[0] = (low - 0xFF6) as usize;", "self.bank[0] = (low - 0xFF6) as usize & 1;", "plain"), # controllers ("controllers: pot scan step", "src/controllers.rs", "pub const SCAN_STEP: f64 = 114.0;", "pub const SCAN_STEP: f64 = 113.0;", "plain"), ("controllers: keypad code 2", "src/controllers.rs", '"2" => 0xE,', '"2" => 0xD,', "plain"), ("controllers: trak-ball lag", "src/controllers.rs", "pub const LAG: f64 = 0.5;", "pub const LAG: f64 = 0.6;", "plain"), ("controllers: 2-port port select", "src/controllers.rs", " port &= 1;", " port &= 3;", "plain"), # save states (judged by the round trips: --save-at-half, --save-mid-half and # cases-midframe.tsv) ("state: /IRQ level for the next cycle", "src/state.rs", " board._irq_next = b._irq_next;\n", "", "half"), ("state: the /IRQ line", "src/state.rs", " board._irq_line = b._irq_line;\n", "", "half"), ("state: the trak-ball lag not restored", "src/state.rs", " ball.out = *out;\n", "", "half"), ("state: the trak-ball pins not restored", "src/state.rs", " controllers._trak_pins.set(trak_pins);\n", "", "half"), ("state: the pot targets not restored", "src/state.rs", " rc.target.clone_from(&state.pot_rc.target);\n", "", "half"), ("state: restore by apply() (the old restore)", "src/state.rs", " controllers.wire_pots(&mut console.cpu.bus);\n", " controllers.wire_pots(&mut console.cpu.bus);\n controllers.apply(&mut console.cpu.bus);\n", "half"), ("state: the stack-write count", "src/state.rs", " board._stack_writes = b._stack_writes;\n", "", "half"), ("state: pot capacitor charge", "src/state.rs", " rc.charge.copy_from_slice(&state.pot_rc.charge);\n", "", "half"), ("state: the last-read address", "src/state.rs", " board._last_read = b._last_read;\n", "", "half"), ("state: the floating-bus latch", "src/state.rs", " board.data_bus = b.data_bus;\n", "", "half"), ("state: GTIA's CONSOL pin", "src/gtia.rs", " pin.set(state.consol_out.get());\n", "", "half"), # audio (judged with --audio) ("media: speaker weight", "src/media.rs", "level += 0.2;", "level += 0.25;", "audio"), ("media: sample step", "src/media.rs", "self._since += self.step as f64;", "self._since += self.step as f64 + 0.001;", "audio"), ] def run(cmd, **kw) -> subprocess.CompletedProcess: return subprocess.run(cmd, capture_output=True, text=True, **kw) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--cases", action="append", type=Path) parser.add_argument("--only") parser.add_argument("--jobs", type=int, default=3) args = parser.parse_args() tables = args.cases or [ROOT / "scripts" / "cases.tsv", ROOT / "scripts" / "cases-acid.tsv"] if not TREE.exists(): run(["git", "-C", str(ROOT), "worktree", "add", "--detach", str(TREE), "HEAD"], check=True) head = run(["git", "-C", str(ROOT), "rev-parse", "HEAD"]).stdout.strip() run(["git", "-C", str(TREE), "checkout", "--detach", head], check=True) caught = 0 tried = 0 for name, file, old, new, mode in FAULTS: if args.only and args.only not in name: continue path = TREE / file run(["git", "-C", str(TREE), "checkout", "--", "."], check=True) text = path.read_text() if text.count(old) != 1: print(f"{name}: SKIPPED (the old text occurs {text.count(old)} times)") continue path.write_text(text.replace(old, new)) build = run(["nice", "-n", "19", "cargo", "build", "--release", "-q", "--bin", "a5200-trace", "--manifest-path", str(TREE / "Cargo.toml"), "--target-dir", str(TARGET)], timeout=1800) if build.returncode: print(f"{name}: BUILD FAILED {build.stderr[-300:]}") continue tried += 1 found = [] mid = ROOT / "scripts" / "cases-midframe.tsv" runs = { "plain": [(t, []) for t in tables] + [(mid, [])], "half": [(t, ["--save-at-half"]) for t in tables] + [(t, ["--save-mid-half", "cycle-12345"]) for t in tables] + [(mid, [])], "audio": [(t, ["--extra=--audio"]) for t in tables] + [(mid, ["--extra=--audio"])], }[mode] for table, extra in runs: gate = run([sys.executable, str(ROOT / "scripts" / "lockstep.py"), "--cases", str(table), "--rust", str(TARGET / "release" / "a5200-trace"), "--jobs", str(args.jobs), "--reference-cache", str(ROOT / "external" / "refcache"), "--traces", str(ROOT / "external" / "faults-traces"), *extra], timeout=7200) found += [line.split(":")[0] for line in gate.stdout.splitlines() if ": " in line and ": identical" not in line and not line.startswith(" ")] caught += bool(found) shown = ": " + ", ".join(found[:3]) if found else "" print(f"{name} [{mode}]: {'CAUGHT' if found else 'MISSED'} ({len(found)} cases{shown})", flush=True) run(["git", "-C", str(TREE), "checkout", "--", "."]) print(f"{caught} of {tried} faults caught") return 0 if caught == tried else 1 if __name__ == "__main__": raise SystemExit(main())