# SPDX-License-Identifier: MIT """Seeded one-line faults: every judge must catch each one (charter: a gate that cannot fail proves nothing). Each fault replaces one exact line fragment in src/pokey_python/chip.py. The source tree is copied to a scratch directory (fresh timestamps, so no stale bytecode is reused), the fault applied there, and the judges run against the copy: the unit tests (the hardware numbers, the register table, AcidSAP's ten tests when the harness's dependencies are present), and with ``--streams N`` also N closed-box rung 2, rung 3 and rung 4 streams (needs the box built). python -I scripts/seeded_faults.py python -I scripts/seeded_faults.py --streams 4 A fault that changes nothing observable is an equivalent mutant: noted, not counted. A real fault no judge catches is a recorded blind spot. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CHIP = Path("src/pokey_python/chip.py") #: (name, exact fragment, replacement). Each fragment must occur exactly once. FAULTS: list[tuple[str, str, str]] = [ ("STIMER reload a tick late", "self.stimer_q |= 0b100", "self.stimer_q |= 0b1000"), ("borrow pipeline 2 instead of 3", "pend[ch] = 3", "pend[ch] = 2"), ("17-bit tap moved", "fb = (r ^ (r >> 5) ^ 1) & 1", "fb = (r ^ (r >> 4) ^ 1) & 1"), ("9-bit tap moved", "fb = ((r >> 8) ^ (r >> 13) ^ 1) & 1", "fb = ((r >> 8) ^ (r >> 12) ^ 1) & 1"), ("RANDOM not inverted", "return ~(self.poly17 >> 9) & 0xFF", "return (self.poly17 >> 9) & 0xFF"), ("RANDOM one stage off", "return ~(self.poly17 >> 9) & 0xFF", "return ~(self.poly17 >> 8) & 0xFF"), ("15 kHz special state", "p15 = c == 0b1001001", "p15 = c == 0b1001000"), ("64 kHz feedback tap", "bit = 1 if p64 else ((c >> 4) ^ (c >> 2)) & 1", "bit = 1 if p64 else ((c >> 4) ^ (c >> 1)) & 1"), # C64_RESET is only the power-on value: init mode shifts the reset in (B2.1a), so changing # it is an equivalent mutant (noted, not counted); its special state is tested instead. ("64 kHz special state", "p64 = c == 0b00010", "p64 = c == 0b00100"), ("joined pair: low not reloaded by high", "count[ch - 1] = audf[ch - 1]", "pass"), ("joined pair: low reloads itself", "if not low:", "if True:"), ("timer 4 IRQ bit", "(fired[3] and 0x04)", "(fired[3] and 0x08)"), ("unmapped read", "return 0xFF # B1.2", "return 0x00 # B1.2"), ("IRQST bit 3 latched", "return ~(self.latched | 0x08) & 0xFF", "return ~self.latched & 0xFF"), ("SKRES misses kb overrun", "self.frame_error = self.kb_overrun = self.ser_overrun = 0", "self.frame_error = self.ser_overrun = 0"), ("init mode feeds 1s into the long counter", " fb = 0\n elif self.audctl & 0x80", " fb = 1\n elif self.audctl & 0x80"), ("base clock select bit", "self._timers(p15 if self.audctl & 0x01 else p64)", "self._timers(p15 if self.audctl & 0x02 else p64)"), ("channel 3 fast-clock bit", "clocked = base if not audctl & 0x20 else True", "clocked = base if not audctl & 0x40 else True"), ("poly4 tap", "fb = 0 if init else ((r >> 5) ^ (r >> 6) ^ 1) & 1", "fb = 0 if init else ((r >> 5) ^ (r >> 7) ^ 1) & 1"), ("poly5 tap", "fb = 0 if init else ((r >> 5) ^ (r >> 7) ^ 1) & 1", "fb = 0 if init else ((r >> 5) ^ (r >> 6) ^ 1) & 1"), ("IRQEN disable keeps latch", "self.latched &= value # B1.4", "pass # B1.4"), ("SKSTAT SID inverted", "value |= 0x10 if self.sid else 0", "value |= 0 if self.sid else 0x10"), ("STIMER does not cancel pending", " pend[ch] = 0\n", " pass\n"), ("init clock reset shifts 0 into 64 kHz", "self.c64 = ((self.c64 << 1) & 0x1F) | 1", "self.c64 = (self.c64 << 1) & 0x1F"), ("square does not toggle", "ff[ch] ^= 1 # B3.5", "ff[ch] = 1 # B3.5"), ("high-pass off holds 0", " hp[0] = 1\n", " hp[0] = 0\n"), ("STIMER sets flip-flops to 0", "ff[0] = ff[1] = ff[2] = ff[3] = 1", "ff[0] = ff[1] = ff[2] = ff[3] = 0"), ("volume-only ignored on channel 3", "o3 = 1 if c & 0x10 else ff[2]", "o3 = ff[2]"), ("noise inverted in init", "ff[ch] = (p17 >> (self.TAP17 - ch)) & 1", "ff[ch] = ~(p17 >> (self.TAP17 - ch)) & 1"), # rung 3: the 5-bit gate (B3.2) and the STIMER hold (B3.7) ("gate not loaded at a fire", "gate[ch] = self._gate(ch) # B3.2: and", "pass # B3.2: and"), ("gate not held open while ungated", "gate[ch] = 1 # B3.2: held open", "pass # B3.2: held open"), ("gate one stage off", "return (self.poly5 >> (self.TAP5 - ch)) & 1", "return (self.poly5 >> (self.TAP5 - ch + 1)) & 1"), ("gate load misses this cycle's write", "control = self.w_val if self.w_reg == 2 * ch + 1 else self.audc[ch]", "control = self.audc[ch]"), ("gate shut in init mode", "if not init and not passed[ch]:", "if not passed[ch]:"), ("STIMER holds the flip-flops one tick", "self.stimer_set = 2", "self.stimer_set = 1"), ("STIMER does not load the gates", " gate[ch] = self._gate(ch)\n if skctl & 0x08:", " pass\n if skctl & 0x08:"), ("4-bit noise one stage off", "ff[ch] = (p4 >> (self.TAP4 - ch)) & 1", "ff[ch] = (p4 >> (self.TAP4 - ch + 1)) & 1"), ("high-pass copies the new flip-flop", "hp[0] = old0 if self.HP_OLD else ff[0]", "hp[0] = ff[0]"), # rung 4: interrupts (B4.x) and the clocks' init lag (B2.1b) ("clocks see init mode at once", "clocks_init = self.clocks_init\n", "clocks_init = init\n"), ("timer latched though disabled", "self.latched |= irq & self.irqen", "self.latched |= irq"), ("IRQ line not settled each tick", "self._update_irq() # B4.2", "pass # B4.2"), ("timer 2 IRQ bit", "(fired[1] and 0x02)", "(fired[1] and 0x01)"), ("bit-3 pin ignores IRQEN", "level = bool(self.latched) or bool(self.irqen & 0x08)", "level = bool(self.latched)"), ("IRQEN write leaves the enable", "self.irqen = value # B4.1", "pass # B4.1"), # rung 5: the pot scan (B5.x) ("pot scan ends at 227", "ending = self.pot_count == 228", "ending = self.pot_count == 227"), ("live pot read not transitional", "return value & (0 if step == 2 else self.pot_count + 1)", "return value"), ("POTGO does not clear the counter", "self.pot_count = 0\n self.pot_scan = True", "self.pot_scan = True"), ("slow scan never steps", "self.pot_step = 1 if p15 else 0", "self.pot_step = 0"), ("ALLPOT not forced at the end", "allpot = 0 # B5.4", "pass # B5.4"), ("dump ignores fast scan", "dump = not self.skctl & 0x04 and not self.pot_scan", "dump = not self.pot_scan"), ("live pot does not follow the counter", "pot[n] = count", "pass"), # rung 6: the keyboard scan (B6.x) ("keyboard counter steps down", "code = (self.scan_code + 1) & 0x3F", "code = (self.scan_code - 1) & 0x3F"), ("debounce ignored", "match = code == self.kb_compare or not self.skctl & 0x01", "match = True"), ("no keyboard overrun", "self.kb_overrun = 1 # B6.5", "pass # B6.5"), ("Break repeats while held", "if kr2 and not self.break_prev and self.irqen & 0x80:", "if kr2 and self.irqen & 0x80:"), ("KBCODE without Shift", "self.kbcode = code | self.shift_latch << 6 | self.ctrl_latch << 7", "self.kbcode = code | self.ctrl_latch << 7"), ("scan not reset when disabled", "self.kb_state = 0 # B6.2", "pass # B6.2"), ("release never debounced", "self.key_held = 0\n self.kb_state = 0", "self.kb_state = 0"), ("Shift read at the wrong code", "SHIFT_CODE = 0x10", "SHIFT_CODE = 0x11"), # rung 7: the serial port's audio-affecting parts (B7.x) ("two-tone resync a tick early", "self.resync_q |= 0b10", "self.resync_q |= 0b1"), ("async receive does not hold", "held = skctl & 0x10", "held = 0"), ("force break ignored by two-tone", "bit = self.sod_bit and not skctl & 0x80", "bit = self.sod_bit"), ("timer 2 does not resync", "if (fired[0] and bit) or fired[1]:", "if fired[0] and bit:"), ("output clock from channel 3", "if (fired[3] and 2 <= mode <= 5)", "if (fired[2] and 2 <= mode <= 5)"), ] def run_judges(tree: Path, streams: int) -> list[str]: env = dict( os.environ, PYTHONPATH=str(tree / "src"), PYTHONDONTWRITEBYTECODE="1", POKEY_REFERENCE=str(ROOT / "reference"), ) # fmt: skip caught = [] tests = subprocess.run( [sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", str(tree / "tests")], cwd=tree, env=env, capture_output=True, text=True, timeout=600, ) # fmt: skip if tests.returncode: caught.append("tests") kit = subprocess.run( [sys.executable, str(ROOT / "scripts" / "conformance.py")], cwd=ROOT, env=dict(env, POKEY_SRC=str(tree / "src")), capture_output=True, text=True, timeout=900, ) # fmt: skip if "cases identical" not in kit.stdout: raise RuntimeError("the conformance kit did not run:\n" + kit.stderr[-2000:]) if kit.returncode: caught.append("kit") for rung in ("rung2", "rung3", "rung4") if streams else (): # the repository's own referee (it needs reference/), the faulty core via POKEY_SRC extra = ["--no-init-toggles"] if rung == "rung2" else [] judge = subprocess.run( [sys.executable, str(ROOT / "scripts" / "streams.py"), rung, "--streams", str(streams), "--cycles", "20000", *extra], cwd=ROOT, env=dict(env, POKEY_SRC=str(tree / "src")), capture_output=True, text=True, timeout=1800, ) # fmt: skip if "streams_with_differences" not in judge.stdout: raise RuntimeError("the stream judge did not run:\n" + judge.stderr[-2000:]) if judge.returncode: caught.append(rung) return caught def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--streams", type=int, default=0) parser.add_argument("--only", help="run only the faults whose name contains this text") args = parser.parse_args() source = (ROOT / CHIP).read_text(encoding="utf-8") missed = [] faults = [f for f in FAULTS if not args.only or args.only in f[0]] with tempfile.TemporaryDirectory(prefix="pokey-faults-") as scratch: for name, old, new in faults: if source.count(old) != 1: print(f"STALE fault (fragment not found once): {name}") missed.append(name) continue tree = Path(scratch) / f"t{len(missed)}-{abs(hash(name))}" shutil.copytree(ROOT, tree, ignore=shutil.ignore_patterns( ".git", ".venv*", "reference", "__pycache__", "*.pyc", ".pytest_cache")) (tree / CHIP).write_text(source.replace(old, new), encoding="utf-8") caught = run_judges(tree, args.streams) print(f"{'caught' if caught else 'MISSED'}: {name} {caught}") if not caught: missed.append(name) print(f"{len(faults) - len(missed)}/{len(faults)} caught") return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())