#!/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. python3 scripts/seeded_faults.py [--jobs 4] [NAME ...] The faults are sn76489-python's 22 (its ``validation/faults.py`` at f8157f4), each the same rule broken the same way in ``src/``. Each is applied to a copy of the repository under ``external/faults//`` (the working tree is never touched) and judged by every rung: - rung 1: ``cargo test`` of the five transcribed test files (each file's verdict is kept, as the reference's faults.py keeps its test files'); - rung 2: the lockstep scripts against the reference's traces already written by ``scripts/rung2.sh`` with its defaults (run it first; the reference must be fetched); - rung 3: the closed-box streams against the reference's traces already written by ``scripts/rung3.sh``, and ``cargo test --test closed_box`` (the committed hashes). A fault is caught when any rung fails; the table says which ones did, and the totals say how many each rung and each rung 1 file caught. The unbroken copy is judged first and must pass. """ from __future__ import annotations import argparse import os import queue import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent.parent RUNG1 = ("contract", "capture", "manuals", "community", "provisional") VOLUME_TABLE = """ 1.0, 0.7943282347242815, 0.6309573444801932, 0.5011872336272722, 0.3981071705534972, 0.31622776601683794, 0.25118864315095796, 0.19952623149688792, 0.15848931924611134, 0.12589254117941673, 0.1, 0.07943282347242814, 0.0630957344480193, 0.05011872336272722, 0.03981071705534971, 0.0, """ #: The table faults.py's `10 ** (-0.1 * (step + 1))` makes: each step one lower, 15 still off. VOLUME_TABLE_SHIFTED = ( "\n".join(VOLUME_TABLE.splitlines()[1:15]) + "\n 0.03162277660168379,\n 0.0,\n" ) TONE_DATA = " self.tone[channel] = (self.tone[channel] & 0x00F) | ((value & 0x3F) << 4);\n" #: (the reference's description, file under src/, exact text, replacement, every occurrence?) FAULTS = [ ("discrete chip: noise taps moved", "variants.rs", '"SN76489AN", 15, 0x0003)', '"SN76489AN", 15, 0x0005)', False), ("discrete chip: 16 stages", "variants.rs", '"SN76489AN", 15, 0x0003)', '"SN76489AN", 16, 0x0003)', False), ("Sega parts: the discrete chip's taps", "variants.rs", "16, 0x0009)", "16, 0x0003)", True), ("Sega parts: 15 stages", "variants.rs", "16, 0x0009)", "15, 0x0009)", True), ("volume table shifted one step", "variants.rs", VOLUME_TABLE, VOLUME_TABLE_SHIFTED, False), ("data bytes to attenuation and noise ignored", "variants.rs", "data_byte_reaches_all_registers: true,", "data_byte_reaches_all_registers: false,", False), ("Sega parts loud at power-on", "variants.rs", "power_on_attenuation: 15,", "power_on_attenuation: 0,", False), ("discrete chip: tone value 0 as on Sega's", "variants.rs", "tone_zero_period: 1024,", "tone_zero_period: 1,", False), ("register 3 latched at power-on", "variants.rs", "power_on_latch: 0,", "power_on_latch: 3,", False), ("no reset of the shift register on a noise write", "chip.rs", " self.lfsr = 1 << (self.variant.lfsr_bits - 1);\n", "", False), ("divide by 8 instead of 16", "chip.rs", "pub const CLOCKS_PER_SAMPLE: u64 = 16;", "pub const CLOCKS_PER_SAMPLE: u64 = 8;", False), ("tone period one tick long", "chip.rs", "counter0 = period0;\n", "counter0 = period0 + 1;\n", False), ("fixed noise rates halved", "chip.rs", "let noise_period = 0x10 << rate;", "let noise_period = 0x20 << rate;", False), ("noise at rate 3 shifts on both edges", "chip.rs", "shift = follows_tone && output2 == shift_level;", "shift = follows_tone;", False), ("periodic noise fed back like white", "chip.rs", " } else {\n 0x0001\n", " } else {\n 0x0003\n", False), ("noise bit taken one stage early", "chip.rs", "let noise_bit = lfsr & 1;", "let noise_bit = (lfsr >> 1) & 1;", False), ("stereo: left reads the right-hand bits", "chip.rs", "let [left0, left1, left2, left3] = side(0x10);", "let [left0, left1, left2, left3] = side(0x01);", False), ("tone data byte lands in the low bits", "chip.rs", "((value & 0x3F) << 4)", "(value & 0x3F)", False), ("latch byte does not write the tone", "chip.rs", "(self.tone[channel] & 0x3F0) | (value & 0x0F)", "self.tone[channel]", False), ("a new tone value restarts the count", "chip.rs", TONE_DATA, TONE_DATA + " self.counters[channel] = 0;\n", False), ("test override ignored", "chip.rs", "let overridden = self.test & 1;", "let overridden = 0;", False), ("noise divider not kept between runs", "chip.rs", " self.noise_counter = noise_counter;\n", "", False), ] # fmt: skip def slug(name: str) -> str: return "".join(c if c.isalnum() else "-" for c in name.lower()).strip("-").replace("--", "-") 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 judge(fault: tuple | None, targets: queue.Queue) -> tuple[str, list[str], list[str], str]: name = fault[0] if fault else "unbroken" copy = ROOT / "external" / "faults" / slug(name) 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 fault: _, file, old, new, every = fault text = (ROOT / "src" / file).read_text() count = text.count(old) if count == 0 or (count > 1 and not every): return name, [], [], f"fault text found {count} times in {file}" (copy / "src" / file).write_text(text.replace(old, new)) target = targets.get() try: # The copies share a few target directories, and cargo names this crate's artifacts # the same whatever directory it sits in; it decides freshness by modification times. # A copy's files keep their old times (and the fault's may predate another copy's # build), so cargo could reuse an artifact built from another copy. Every source file # is therefore stamped now, while this copy holds the target directory alone. for path in copy.rglob("*"): if path.is_file() and "traces" not in path.parts[len(copy.parts)]: os.utime(path) env = { "CARGO_TARGET_DIR": str(target), "SN76489_REFERENCE": os.environ.get( "SN76489_REFERENCE", str(ROOT.parent / "sn76489-python" / "reference") ), } build = run(["cargo", "build", "--release", "-q", "--tests", "--examples"], copy, env) if build.returncode: return name, [], [], "does not build: " + build.stderr.strip().splitlines()[-1] caught, files = [], [] for test in RUNG1: if run(["cargo", "test", "--release", "-q", "--test", test], copy, env).returncode: files.append(test) if files: caught.append("1") trace_bin = str(target / "release" / "examples" / "sn76489-trace") rung2 = run( [str(ROOT / "scripts" / "rung2.sh")], ROOT, {"BIN": trace_bin, "REUSE": "1", "OURS": str(copy / "traces2"), "JOBS": "2"}, ) if rung2.returncode == 2: return name, caught, files, "rung 2 could not run: " + rung2.stderr.strip() if rung2.returncode: caught.append("2") rung3 = run( [str(ROOT / "scripts" / "rung3.sh")], ROOT, {"BIN": trace_bin, "REUSE": "1", "OURS": str(copy / "traces3"), "JOBS": "2", "SKIP_CARGO_TEST": "1"}, ) # fmt: skip hashes = run(["cargo", "test", "--release", "-q", "--test", "closed_box"], copy, env) if rung3.returncode or hashes.returncode: caught.append("3") detail = next((ln for ln in rung2.stdout.splitlines() if " traces identical" in ln), "") return name, caught, files, "lockstep " + detail.removeprefix("rung 2: ").split(" (")[0] 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() faults = [f for f in FAULTS if not args.names or any(n in f[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)) name, caught, files, detail = judge(None, targets) if caught: print(f"the unbroken copy fails rungs {'+'.join(caught)} {files} ({detail})") return 1 print(f"unbroken copy: every rung passes ({detail})\n") missed = [] per_rung = dict.fromkeys("123", 0) per_file = dict.fromkeys(RUNG1, 0) with ThreadPoolExecutor(args.jobs) as pool: futures = [pool.submit(judge, fault, targets) for fault in faults] for index, future in enumerate(futures, start=1): name, caught, files, detail = future.result() for rung in caught: per_rung[rung] += 1 for file in files: per_file[file] += 1 rungs = "+".join(caught) if caught else "-" print(f"{index:2d}. {'caught' if caught else 'MISSED'} rungs {rungs:6} {name} " f"(rung 1 files: {', '.join(files) or 'none'}; {detail})", flush=True) # fmt: skip if not caught: missed.append(name) print() for rung, count in per_rung.items(): print(f"rung {rung}: catches {count} of {len(faults)}") for file, count in per_file.items(): print(f" rung 1, tests/{file}.rs: {count} of {len(faults)}") print(f"{len(faults) - len(missed)} of {len(faults)} caught") return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())