#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """A gate that cannot fail proves nothing: break this core one rule at a time and check that the ladder catches every break (rung 4). python3 scripts/seeded_faults.py [--jobs 4] [NAME ...] The faults are ym2612-python's 28 (its ``validation/faults.py`` at a6e8e5d), each the same rule broken the same way in this crate's source, in the same order. Each is applied to a copy of the crate under ``external/faults/NN/`` (the working tree is never touched) and judged by every rung: - rung 1: ``cargo test`` of the five transcribed test files (the files that fail are listed); - rung 2: the lockstep scripts against the reference traces ``scripts/rung2.sh`` wrote with its defaults; - rung 3: the closed_box.py streams against the reference traces ``scripts/rung3.sh`` wrote. The unbroken copy is judged first and must pass every rung. A fault is caught when any rung fails; the summary counts the faults each rung catches. """ from __future__ import annotations import argparse import os import queue import shutil import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent.parent TEST_FILES = ("contract", "measured", "manuals", "community", "provisional") #: (ym2612-python's name for it, file under src/, the exact text, its replacement, every #: occurrence?) FAULTS = [ ("no 17-bit wrap after detune", "operator.rs", "& 0x1FFFF", "& 0xFFFFFF", True), ("high F-number byte applied at once", "chip.rs", " self.fnum_latch[latch] = value & 0x3F;\n", " self.fnum_latch[latch] = value & 0x3F;\n self.channels[channel].block = (value >> 3) & 7;\n", False), ("timers at the YM2612 manual's rate (72 clocks)", "chip.rs", " self.timer_a_counter += 1;\n", " self.timer_a_counter += 2;\n", False), ("CSM acts in mode 01", "chip.rs", " if self.channel3_mode == 2 {", " if self.channel3_mode == 1 {", False), ("SSG-EG factor 6", "operator.rs", "attenuation += 4 * increment", "attenuation += 6 * increment", False), ("SSG-EG inversion by exclusive-or with $1FF", "operator.rs", "level = (SSG_THRESHOLD - level) & 0x3FF;", "level = (level ^ 0x1FF) & 0x3FF;", False), ("decay cut back to the sustain level", "operator.rs", " self.envelope_phase = SUSTAIN;\n phase = SUSTAIN;\n", " self.envelope_phase = SUSTAIN;\n phase = SUSTAIN;\n self.attenuation = level << 5;\n attenuation = level << 5;\n", False), ("carriers summed before the cut to 9 bits", "chip.rs", " let mut value = out4 >> 5;\n if wiring[6] != 0 {\n value += out1 >> 5;\n }\n if wiring[7] != 0 {\n value += out2 >> 5;\n }\n if wiring[8] != 0 {\n value += out3 >> 5;\n }\n", " let mut value = (out4 + out1 * wiring[6] + out2 * wiring[7] + out3 * wiring[8]) >> 5;\n", False), ("accumulator wraps", "chip.rs", " if value > high_limit {\n value = high_limit;\n", " if value > high_limit {\n value -= 512;\n", False), ("one detune entry moved", "tables.rs", "[2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12,", "[2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 12, 12,", False), ("envelope step patterns shifted by one", "tables.rs", " rows[rate] = slow[rate & 3];", " rows[rate] = { let s = slow[rate & 3]; [s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[0]] };", False), ("linear attack", "operator.rs", "attenuation + ((!attenuation * increment) >> 4)", "0.max(attenuation - 16 * increment)", False), ("exponent table scaled as the OPL's", "operator.rs", "(EXPONENT[(total & 0xFF) as usize] << 2) >> (total >> 8)", "(EXPONENT[(total & 0xFF) as usize] << 1) >> (total >> 8)", False), ("modulation not shifted", "chip.rs", "(out1 * wiring[0]) >> 1", "(out1 * wiring[0])", True), ("key-on resets the attenuation", "operator.rs", " self.envelope_phase = ATTACK;\n self.phase = 0;\n", " self.envelope_phase = ATTACK;\n self.attenuation = 0x3FF;\n self.phase = 0;\n", False), ("key-on leaves the phase alone", "operator.rs", " self.envelope_phase = ATTACK;\n self.phase = 0;\n", " self.envelope_phase = ATTACK;\n", False), ("BUSY lasts a sample", "chip.rs", "BUSY_CLOCKS: u64 = 192", "BUSY_CLOCKS: u64 = 144", False), ("envelope advances every sample", "chip.rs", "self.envelope_divider == 3", "self.envelope_divider == 1", False), ("feedback from one store", "chip.rs", "(older + newer) >> (10 - feedback)", "(newer + newer) >> (10 - feedback)", False), ("no delayed modulation paths", "chip.rs", "DELAYED_MODULATION: bool = true", "DELAYED_MODULATION: bool = false", False), ("DAC scaled by four", "chip.rs", "(self.dac_data - 0x80) << 1", "(self.dac_data - 0x80) << 2", False), ("register operator order 1, 2, 3, 4", "chip.rs", "REGISTER_SLOT_TO_OPERATOR: [usize; 4] = [0, 2, 1, 3]", "REGISTER_SLOT_TO_OPERATOR: [usize; 4] = [0, 1, 2, 3]", False), ("block shifts left only", "operator.rs", "let mut increment = (f_number << self.block) >> 1;", "let mut increment = f_number << self.block;", False), ("attack does not stall at rate 62", "operator.rs", " if rate < 62 {\n", " if rate < 64 {\n", False), ("total level added before the inversion", "operator.rs", " let mut level = self.attenuation;\n if self.ssg & SSG_ENABLE != 0 && self.inverted() {", " let mut level = self.attenuation + (self.total_level << 3);\n if self.ssg & SSG_ENABLE != 0 && self.inverted() {", False), ("tremolo triangle not doubled", "chip.rs", " triangle <<= 1;\n", "", False), ("timer flag set without the enable bit", "chip.rs", " if self.timer_enable & 1 != 0 {\n self.status_flags |= 1;\n }\n", " self.status_flags |= 1;\n", False), ("the YM3438 given the ladder", "variant.rs", " ladder: false,\n ladder_positive: 0,\n ladder_negative: 0,\n ladder_idle: 0,\n", " ladder: true,\n ladder_positive: 4,\n ladder_negative: -3,\n ladder_idle: 4,\n", False), ] # fmt: skip def run(cmd: list[str], cwd: Path, env: dict | None = None) -> subprocess.CompletedProcess: return subprocess.run( ["nice", *cmd], cwd=cwd, env=dict(os.environ, **(env or {})), capture_output=True, text=True ) def make_copy(index: int, file: str = "", find: str = "", replacement: str = "", every: bool = False) -> Path: copy = ROOT / "external" / "faults" / f"{index:02d}" copy.mkdir(parents=True, exist_ok=True) for item in ("Cargo.toml", "Cargo.lock", "src", "tests", "examples"): source = ROOT / item if source.is_dir(): shutil.copytree(source, copy / item, dirs_exist_ok=True) else: shutil.copy2(source, copy / item) if file: text = (ROOT / "src" / file).read_text() count = text.count(find) if count == 0 or (count > 1 and not every): sys.exit(f"fault {index}: the text occurs {count} times in src/{file}") (copy / "src" / file).write_text(text.replace(find, replacement)) return copy def judge(index: int, fault: tuple, targets: queue.Queue) -> tuple[int, list[str], list[str], str]: copy = make_copy(index, *fault[1:]) if fault else make_copy(index) target = targets.get() try: # The target directories are shared between copies and cargo judges freshness by # modification time, while copytree keeps the sources' old times: stamp every file # now, so the build is of this copy and not a binary left by another one. now = time.time() for path in copy.rglob("*"): if path.is_file(): os.utime(path, (now, now)) env = {"CARGO_TARGET_DIR": str(target)} build = run(["cargo", "build", "--release", "-q", "--example", "ym2612-trace"], copy, env) if build.returncode: return index, [], [], "does not build: " + build.stderr.strip().splitlines()[-1] caught, files = [], [] for name in TEST_FILES: if run(["cargo", "test", "--release", "-q", "--test", name], copy, env).returncode: files.append(name) if files: caught.append("1") details = [] for rung, script in (("2", "rung2.sh"), ("3", "rung3.sh")): result = run( [str(ROOT / "scripts" / script)], ROOT, { "BIN": str(target / "release" / "examples" / "ym2612-trace"), "REUSE": "1", "OURS": str(copy / f"traces-rung{rung}"), "JOBS": "2", }, ) if result.returncode == 2: return index, caught, files, f"rung {rung} could not run: " + result.stderr.strip() if result.returncode: caught.append(rung) line = next((ln for ln in result.stdout.splitlines() if " scripts identical" in ln), "") details.append(line.split(": ", 1)[-1].split(" (")[0]) return index, caught, files, "; ".join(f"rung {r}: {d}" for r, d in zip("23", details)) finally: targets.put(target) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=4) parser.add_argument("names", nargs="*", help="only faults whose name contains one of these") args = parser.parse_args() chosen = [ (index, fault) for index, fault in enumerate(FAULTS, start=1) if not args.names or any(n in fault[0] for n in args.names) ] targets: queue.Queue = queue.Queue() for i in range(args.jobs): targets.put(ROOT / "external" / "faults-target" / str(i)) _, caught, files, detail = judge(0, (), targets) if caught: print(f"the unbroken copy fails: rungs {caught} {files} ({detail})") return 1 print(f"unbroken copy: every rung passes ({detail})\n") per_rung = {"1": 0, "2": 0, "3": 0} per_file = dict.fromkeys(TEST_FILES, 0) missed = [] with ThreadPoolExecutor(args.jobs) as pool: futures = [pool.submit(judge, index, fault, targets) for index, fault in chosen] for (index, fault), future in zip(chosen, futures): _, caught, files, detail = future.result() for rung in caught: per_rung[rung] += 1 for name in files: per_file[name] += 1 rungs = "+".join(caught) if caught else "NOBODY" print(f"{index:2d}. {fault[0]}: rungs {rungs} (rung 1 files: {', '.join(files) or '-'}; {detail})", flush=True) if not caught: missed.append(fault[0]) print() for rung, count in per_rung.items(): print(f"rung {rung}: catches {count} of {len(chosen)}") for name, count in per_file.items(): print(f" rung 1, tests/{name}.rs: {count}") print(f"{len(chosen) - len(missed)} of {len(chosen)} caught; missed: {missed if missed else 'none'}") return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())