#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 5: can each rung fail? The 61 seeded faults of ay8910-python's scripts/mutation.py, the same rules broken in this crate's source, one textual change each, and six of this crate's own (the port queue that stands for Python's callables, and the save state). python3 scripts/seeded_faults.py [--jobs 4] [--only N,N,...] Each fault is applied to a copy of the crate under the git-ignored external/faults/NN/; the copy is judged by rung 1 (cargo test, by test file), rung 2 (the lockstep scripts against the reference traces scripts/rung2.sh wrote), rung 3 (the reference's streams, from scripts/rung3.sh) and rung 4 (rung 2's scripts with save-state round trips). The unbroken copy (00) is judged first and must pass all four. Exit status 1 if it fails or any fault goes unnoticed by every rung. """ from __future__ import annotations import argparse import os import re import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] WORK = ROOT / "external" / "faults" STABLE = Path.home() / ".rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin" # Rung 1's test files, named as the reference's. RUNG1 = { "chip": "rung 1 chip (test_chip.py)", "variants": "rung 1 variants (test_variants.py)", "conformance": "rung 1 conformance (test_conformance.py, the 19 examples)", "save_state": "rung 1 save_state", } RUNGS = [*RUNG1.values(), "rung 2", "rung 3", "rung 4"] SKIP = '#[cfg_attr(feature = "serde", serde(skip))]\n ' # (what is broken: ay8910-python's name for it, file, text to find, replacement, every?) # The first 61 are scripts/mutation.py's, in its order. FAULTS: tuple[tuple[str, str, str, str, bool], ...] = ( ("strobe a clock early", "chip.rs", "pub const STROBE_PHASE: u8 = 2;", "pub const STROBE_PHASE: u8 = 1;", False), ("count four clocks after the strobe", "chip.rs", "pub const COUNT_PHASE: u8 = 3;", "pub const COUNT_PHASE: u8 = 6;", False), ("tones low out of reset", "chip.rs", "self.tone_output = [1, 1, 1];", "self.tone_output = [0, 0, 0];", False), ("counters free out of reset", "chip.rs", "self.tone_held = [true, true, true];", "self.tone_held = [false, false, false];", False), ("tone expires above its period", "chip.rs", "self.tone_count[channel] >= self.tone_period[channel]", "self.tone_count[channel] > self.tone_period[channel]", False), ("tone period 0 is 4096", "chip.rs", "self.tone_period[channel] = ((coarse & 0x0F) as u32) << 8 | fine as u32;", "self.tone_period[channel] = match ((coarse & 0x0F) as u32) << 8 | fine as u32 { 0 => 4096, p => p };", False), ("coarse tone period eight bits wide", "chip.rs", "self.tone_period[channel] = ((coarse & 0x0F) as u32) << 8 | fine as u32;", "self.tone_period[channel] = (coarse as u32) << 8 | fine as u32;", False), ("a held tone counter is compared", "chip.rs", "if !self.tone_held[channel] && self.tone_count[channel] >= self.tone_period[channel] {", "if self.tone_count[channel] >= self.tone_period[channel] {", False), ("a period write restarts its tone", "chip.rs", "self.tone_period[channel] = ((coarse & 0x0F) as u32) << 8 | fine as u32;", "self.tone_period[channel] = ((coarse & 0x0F) as u32) << 8 | fine as u32;\n self.tone_count[channel] = 0;", False), ("the strobe shuts with its clock", "chip.rs", "self.phase == (STROBE_PHASE + 1) & 7", "false", False), ("noise steps on every expiry", "chip.rs", " self.noise_half ^= 1;\n if self.noise_half == 0 {\n self.shift_noise();\n }", " self.shift_noise();", False), ("noise steps on the other expiry", "chip.rs", "if self.noise_half == 0 {", "if self.noise_half != 0 {", False), ("noise taps 16 and 14", "chip.rs", "((noise >> 16) ^ (noise >> 13)) & 1", "((noise >> 16) ^ (noise >> 14)) & 1", False), ("noise taps 16 and 2 (the 15-bit pair moved up)", "chip.rs", "((noise >> 16) ^ (noise >> 13)) & 1", "((noise >> 16) ^ (noise >> 2)) & 1", False), ("noise register sixteen bits", "chip.rs", "| (noise == 0) as u32) & 0x1FFFF", "| (noise == 0) as u32) & 0xFFFF", False), ("an empty noise register stays empty", "chip.rs", "| feedback | (noise == 0) as u32) & 0x1FFFF", "| feedback) & 0x1FFFF", False), ("noise heard uninverted", "chip.rs", "((!self.noise_register >> 16) & 1) as u8", "((self.noise_register >> 16) & 1) as u8", False), ("noise heard at bit 0", "chip.rs", "((!self.noise_register >> 16) & 1) as u8", "(!self.noise_register & 1) as u8", False), ("noise period six bits wide", "chip.rs", "(registers[NOISE_PERIOD as usize] & 0x1F) as u32", "(registers[NOISE_PERIOD as usize] & 0x3F) as u32", False), ("an AY envelope steps on every expiry", "chip.rs", "if self.envelope_top == 15 {", "if false {", False), ("a Yamaha envelope steps on every second expiry", "chip.rs", "if self.envelope_top == 15 {", "if true {", False), ("envelope period 0 is twice as fast (MAME's AY)", "chip.rs", "if !self.envelope_held && self.envelope_count >= self.envelope_period {", "if (!self.envelope_held || self.envelope_period == 0) && self.envelope_count >= self.envelope_period {", False), ("a late restart clears the whole counter", "chip.rs", "self.envelope_count &= 1;", "self.envelope_count = 0;", False), ("a late restart holds the counter", "chip.rs", "self.envelope_count &= 1;\n self.envelope_held = false;", "self.envelope_count &= 1;\n self.envelope_held = true;", False), ("an early restart does not hold the counter", "chip.rs", " self.envelope_count = 0;\n self.envelope_held = true;\n }\n self.envelope_half = 0;", " self.envelope_count = 0;\n self.envelope_held = false;\n }\n self.envelope_half = 0;", False), ("the second half starts a clock late", "chip.rs", "self.phase > COUNT_PHASE", "self.phase > COUNT_PHASE + 1", False), ("a restart keeps the halving flip-flop", "chip.rs", " self.envelope_half = 0;\n self.envelope_step = 0;\n self.envelope_holding = false;\n", " self.envelope_step = 0;\n self.envelope_holding = false;\n", False), ("a restart keeps the step", "chip.rs", " self.envelope_step = 0;\n self.envelope_holding = false;\n", " self.envelope_holding = false;\n", False), ("a restart leaves the period counter running", "chip.rs", " if self.counters_counted() {\n self.envelope_count &= 1;\n self.envelope_held = false;\n } else {\n self.envelope_count = 0;\n self.envelope_held = true;\n }\n", "", False), ("a restart does not release a held level", "chip.rs", " self.envelope_holding = false;\n self.envelope_rising = self", " self.envelope_rising = self", False), ("attack read from the alternate bit", "chip.rs", "& ATTACK != 0;", "& ALTERNATE != 0;", False), ("a ramp one step short", "chip.rs", "if self.envelope_step <= self.envelope_top {", "if self.envelope_step < self.envelope_top {", False), ("without CONTINUE the level holds where it ended", "chip.rs", " self.envelope_holding = true;\n self.envelope_level = 0;\n", " self.envelope_holding = true;\n", False), ("HOLD ignores ALTERNATE", "chip.rs", "let ends_high = self.envelope_rising ^ (shape & ALTERNATE != 0);", "let ends_high = self.envelope_rising;", False), # Python replaces the line with `pass`. ("ALTERNATE does not turn the ramp", "chip.rs", "self.envelope_rising = !self.envelope_rising;", "", False), ("HOLD does not hold", "chip.rs", "} else if shape & HOLD != 0 {\n self.envelope_holding = true;", "} else if shape & HOLD != 0 {\n self.envelope_holding = false;", False), ("mixer bits enable instead of disable", "chip.rs", "let tone_gate = self.tone_output[channel] | (mixer >> channel);", "let tone_gate = self.tone_output[channel] | !(mixer >> channel);", False), ("tone and noise are ORed", "chip.rs", "if tone_gate & noise_gate & 1 == 0 {", "if (tone_gate | noise_gate) & 1 == 0 {", False), ("noise gates from the tone bits", "chip.rs", "let noise_gate = noise | (mixer >> (channel + 3));", "let noise_gate = noise | (mixer >> channel);", False), ("a Yamaha volume drives 2v", "chip.rs", "(volume & 0x0F) * 2 + 1", "(volume & 0x0F) * 2", False), ("the envelope bit is bit 5", "chip.rs", "if volume & 0x10 != 0 {", "if volume & 0x20 != 0 {", False), ("the volume acts at the next strobe", "chip.rs", " self.compare();\n }\n self.levels_now = self.mix_levels();\n", " self.compare();\n }\n", False), ("any address byte selects", "chip.rs", "self.selected = (value & 0xF0) == 0;", "self.selected = true;", False), ("a deselecting byte moves the latch", "chip.rs", " if self.selected {\n self.address = value & 0x0F;\n }", " self.address = value & 0x0F;", False), ("an address byte leaves the bus charged", "chip.rs", " self.address = value & 0x0F;\n }\n self.bus = 0;", " self.address = value & 0x0F;\n }", False), ("a data write leaves the bus as it was", "chip.rs", " self.bus = value;\n self.write_selected(self.address, self.bus);", " self.write_selected(self.address, value);", False), ("an output port reads its latch alone", "chip.rs", "levels &= self.registers[register as usize];", "levels = self.registers[register as usize];", False), ("an input port reads its latch", "chip.rs", " if self.port_is_output(register) {\n levels &= self.registers[register as usize];\n }", " levels &= self.registers[register as usize];", False), ("port directions swapped", "chip.rs", "(if register == PORT_A { 0x40 } else { 0x80 })", "(if register == PORT_A { 0x80 } else { 0x40 })", False), ("an unbonded port reads the outside", "chip.rs", " if self.port_bonded(register) {\n levels = outside;\n }", " levels = outside;", False), ("the divider ignores the halving", "chip.rs", "if self.divider_count >= self.clock_divider {", "if self.divider_count >= 1 {", False), ("reset keeps the registers", "chip.rs", " self.registers = [0; 16];\n", "", False), ("reset keeps the divider's phase", "chip.rs", " self.phase = 0;\n", "", False), ("the AY keeps eight bits of every register", "variants.rs", "register_masks: REGISTER_WIDTH_MASKS,", "register_masks: ALL_BITS,", True), ("the YM2149 has a 16-step envelope", "variants.rs", 'name: Cow::Borrowed("YM2149"),\n envelope_steps: 32,', 'name: Cow::Borrowed("YM2149"),\n envelope_steps: 16,', False), ("the 5B runs at the full clock", "variants.rs", "clock_divider: 2,", "clock_divider: 1,", False), ("the AY-3-8912 has port B", "variants.rs", 'ports: Cow::Borrowed("A"),', 'ports: Cow::Borrowed("AB"),', False), # The tables are written out (variants.rs's header), so the formula's fault is the numbers # it would have given: code 1 at 2 ** (-30 / 4); the top four codes 3 dB apart. ("the 5B's code 1 sounds", "variants.rs", " 0.0, 0.0, 0.0065695032441696445, 0.0078125,", " 0.0, 0.005524271728019903, 0.0065695032441696445, 0.0078125,", False), ("the Yamaha ladder at 3 dB a step", "variants.rs", " 0.5946035575013605, 0.7071067811865476, 0.8408964152537145, 1.0,", " 0.3535533905932738, 0.5, 0.7071067811865476, 1.0,", False), ("the strobe stays open all the turn", "chip.rs", "self.phase == (STROBE_PHASE + 1) & 7", "true", False), ("the count that lets a counter go does not count it", "chip.rs", " self.tone_count[channel] += 1;\n", " self.tone_count[channel] += (!self.tone_held[channel]) as u32;\n", False), # This crate's own: the port queue that stands for Python's port_*_out callables. ("(Rust) a change is told on an unbonded port", "chip.rs", "if out && self.port_bonded(register) {", "if out {", False), ("(Rust) a port is told when nothing changed", "chip.rs", "if value != self.driven[port] {", "if value != self.driven[port] || out_always() {", False), ("(Rust) the outside's levels are not read", "chip.rs", " return self.port_pins(PORT_A, self.port_a_in);", " return self.port_pins(PORT_A, None);", False), # And the save state (the serde feature): a field left out of it. ("(Rust) a save state forgets the envelope's halving flip-flop", "chip.rs", "pub envelope_half: u8,", SKIP + "pub envelope_half: u8,", False), ("(Rust) a save state forgets the queued outputs", "chip.rs", "pub outputs: Vec,", SKIP + "pub outputs: Vec,", False), ("(Rust) a save state forgets the address latch", "chip.rs", "pub address: u8,", SKIP + "pub address: u8,", False), ) # fmt: skip # Fault 63's helper: always true, out of the optimiser's sight. HELPER = "\n#[inline(never)]\nfn out_always() -> bool {\n std::hint::black_box(true)\n}\n" def environment() -> dict[str, str]: env = dict(os.environ) if (STABLE / "cargo").exists(): env["PATH"] = f"{STABLE}:{env['PATH']}" return env def make_copy(index: int, file: str = "", find: str = "", replacement: str = "", every=False) -> Path: copy = WORK / f"{index:02d}" for part in ("src", "tests", "examples"): target = copy / part if target.exists(): # the previous run's copy is set aside, never deleted (the working rules); the # build directory stays, so a rerun only recompiles this crate aside = ROOT / "trash" / "faults" / str(os.getpid()) / f"{index:02d}" aside.mkdir(parents=True, exist_ok=True) shutil.move(str(target), str(aside / part)) shutil.copytree(ROOT / part, target) for name in ("Cargo.toml", "Cargo.lock"): shutil.copy2(ROOT / name, copy / name) if file: source = copy / "src" / file text = source.read_text() count = text.count(find) if count == 0 or (count > 1 and not every): sys.exit(f"fault {index}: {find!r} occurs {count} times in {file}") text = text.replace(find, replacement) if "out_always()" in replacement: text += HELPER source.write_text(text) return copy def judge(copy: Path) -> tuple[bool, set[str]]: """(built, the rungs that fail).""" env = environment() env["CARGO_TARGET_DIR"] = str(copy / "target") # copytree keeps the sources' old modification times, and cargo judges freshness by them: # stamp every file now, so a reused build directory cannot serve a binary of other text for part in ("src", "tests", "examples"): for path in (copy / part).rglob("*"): if path.is_file(): os.utime(path) for name in ("Cargo.toml", "Cargo.lock"): os.utime(copy / name) caught: set[str] = set() build = subprocess.run( ["nice", "cargo", "build", "--release", "-q", "--features", "serde", "--example", "ay8910-trace"], cwd=copy, env=env, capture_output=True, text=True, check=False, ) # fmt: skip if build.returncode: return False, set(RUNGS) # stderr (cargo's "Running tests/x.rs") merged into stdout in order, so each result line # follows the header of its file tests = subprocess.run( ["timeout", "900", "nice", "cargo", "test", "--release", "--features", "serde", "--no-fail-fast", "--tests"], cwd=copy, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) # fmt: skip current = None for line in tests.stdout.splitlines(): running = re.match(r"\s*Running tests/(\w+)\.rs", line) if running: current = running.group(1) elif current in RUNG1 and re.match(r"test result: FAILED", line): caught.add(RUNG1[current]) if tests.returncode and not caught: caught |= set(RUNG1.values()) # a test target did not build binary = copy / "target" / "release" / "examples" / "ay8910-trace" for rung, script, extra in ( ("rung 2", "rung2.sh", {}), ("rung 3", "rung3.sh", {}), ("rung 4", "rung2.sh", {"ROUNDTRIP": "1"}), ): out = copy / f"out-{rung[-1]}" out.mkdir(exist_ok=True) result = subprocess.run( [str(ROOT / "scripts" / script)], env=dict(env, BIN=str(binary), OURS=str(out), REUSE="1", JOBS="2", **extra), capture_output=True, text=True, check=False, ) # fmt: skip if result.returncode: caught.add(rung) return True, caught def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--only", default="") args = parser.parse_args() only = {int(n) for n in args.only.split(",") if n} built, caught = judge(make_copy(0)) if not built or caught: print(f"the unbroken copy fails: {sorted(caught)}") return 1 print("unbroken copy: rungs 1, 2, 3 and 4 pass\n") chosen = [(i, f) for i, f in enumerate(FAULTS, start=1) if not only or i in only] copies = [make_copy(i, *fault[1:]) for i, fault in chosen] with ThreadPoolExecutor(args.jobs) as pool: results = list(pool.map(judge, copies)) counts = dict.fromkeys(RUNGS, 0) unnoticed = [] for (index, (what, *_)), (built, found) in zip(chosen, results, strict=True): for rung in found: counts[rung] += 1 seen = ", ".join(rung for rung in RUNGS if rung in found) or "NOBODY" if not built: seen = "does not build (" + seen + ")" if not found: unnoticed.append(what) print(f"{index:2d}. {what}: {seen}") print() any_rung1 = sum(1 for _, (_, found) in zip(chosen, results, strict=True) if found & set(RUNG1.values())) print(f"rung 1 (any test file): notices {any_rung1} of {len(chosen)} faults") for rung in RUNGS: print(f"{rung}: notices {counts[rung]} of {len(chosen)} faults") print(f"caught by some rung: {len(chosen) - len(unnoticed)} of {len(chosen)}") print(f"unnoticed by every rung: {len(unnoticed)} {unnoticed if unnoticed else ''}") return 1 if unnoticed else 0 if __name__ == "__main__": sys.exit(main())