| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- #!/usr/bin/env python3
- """L12 bounded fault seeding in disposable clones of the clean source tree."""
- from __future__ import annotations
- from dataclasses import dataclass
- from datetime import datetime, timezone
- import hashlib
- import json
- import os
- from pathlib import Path
- import re
- import subprocess
- import sys
- import tempfile
- import time
- ROOT = Path(__file__).resolve().parents[1]
- @dataclass(frozen=True)
- class Mutation:
- name: str
- path: str
- old: str
- new: str
- gate: str
- GATES = {
- # The retired host_protocol/control cocotb profile names are deliberately
- # not part of the active V1.1 contract. Use the maintained aggregate
- # simulation entrypoint, which covers both host transport and control
- # benches, plus the current BMC and PWM gates.
- "host": [sys.executable, "tools/run_6400_v1.py", "sim"],
- "control": [sys.executable, "-B", "-m", "pytest", "-q", "tests/unit/test_6400_contract.py"],
- # The active deterministic BMC parser bench is already part of `sim`;
- # the optional cocotb BMC lane requires a libpython shared library that
- # is not present in every verification image.
- "bmc": [sys.executable, "tools/run_6400_v1.py", "sim"],
- "pwm": [sys.executable, "tools/run_6400_v1.py", "pwm"],
- }
- MUTATIONS = (
- Mutation(
- "crc_decision_inverted",
- "src/common/frame_rx.v",
- "if ({byte_data, received_crc_low} == crc_value) begin",
- "if ({byte_data, received_crc_low} != crc_value) begin",
- "host",
- ),
- Mutation(
- "hard_safety_comparator_changed",
- "src/control/thermal_control_core.v",
- "wire scan_over77 = bmc_rd_valid && (bmc_celsius >= 16'd77);",
- "wire scan_over77 = bmc_rd_valid && (bmc_celsius > 16'd77);",
- "control",
- ),
- Mutation(
- "bank_pointer_flip_suppressed",
- "src/acquisition/bmc_ascii_snapshot.v",
- "active_bank <= ~active_bank;",
- "active_bank <= active_bank;",
- "bmc",
- ),
- Mutation(
- "pwm_deadline_shortened",
- "src/actuator/pwm_bitmap_engine.v",
- "parameter integer PTC_PHASE_CLKS = 12500,",
- "parameter integer PTC_PHASE_CLKS = 32,",
- "pwm",
- ),
- Mutation(
- "stale_threshold_off_by_one",
- "src/acquisition/bmc_ascii_snapshot.v",
- "assign stale = (age_seconds >= STALE_SECONDS[15:0]);",
- "assign stale = (age_seconds > STALE_SECONDS[15:0]);",
- "control",
- ),
- Mutation(
- "invalid_mask_bit_shifted",
- "src/acquisition/bmc_ascii_snapshot.v",
- "valid1[byte_count[5:1]] <= 1'b0;",
- "valid1[byte_count[5:1] ^ 5'd1] <= 1'b0;",
- # The parser fuzz gate checks exact raw/valid pairing across both
- # alternating banks; the full control gate happens to exercise this
- # mutation site only while the other bank is active.
- "bmc",
- ),
- )
- def sha256(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def git(*args: str, cwd: Path = ROOT) -> str:
- return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
- def run(command: list[str], cwd: Path, log: Path, timeout: int = 600) -> dict[str, object]:
- started = time.monotonic()
- env = os.environ.copy()
- env["PYTHONDONTWRITEBYTECODE"] = "1"
- # Keep the runner portable: Windows may intentionally lack HDL tools,
- # while the authorized Linux verification host keeps them on persistent
- # volumes outside the base PATH.
- tool_bins = [
- Path("/data/prod2u/toolchain/iverilog/usr/bin"),
- Path("/data/prod2u/oss-cad-suite/latest/bin"),
- ]
- available = [str(path) for path in tool_bins if path.is_dir()]
- if available:
- env["PATH"] = os.pathsep.join([*available, env.get("PATH", "")])
- with log.open("wb") as stream:
- completed = subprocess.run(
- command,
- cwd=cwd,
- env=env,
- stdout=stream,
- stderr=subprocess.STDOUT,
- timeout=timeout,
- check=False,
- )
- text = log.read_text(encoding="utf-8", errors="replace")
- return {
- "command": command,
- "exit_code": completed.returncode,
- "duration_seconds": round(time.monotonic() - started, 3),
- "log": str(log),
- "log_sha256": sha256(log),
- "failure_signature": bool(re.search(r"(FAIL|AssertionError|FATAL|failed|error)", text, re.IGNORECASE)),
- "tail": "\n".join(text.splitlines()[-40:]),
- }
- def clone_at(commit: str, destination: Path) -> None:
- subprocess.run(["git", "clone", "--quiet", "--shared", "--no-checkout", str(ROOT), str(destination)], check=True)
- subprocess.run(["git", "checkout", "--quiet", "--detach", commit], cwd=destination, check=True)
- def apply_mutation(root: Path, mutation: Mutation) -> dict[str, str]:
- path = root / mutation.path
- before = path.read_text(encoding="utf-8")
- count = before.count(mutation.old)
- if count != 1:
- raise RuntimeError(f"{mutation.name}: expected one mutation site, found {count}")
- after = before.replace(mutation.old, mutation.new, 1)
- path.write_text(after, encoding="utf-8")
- return {
- "before_sha256": hashlib.sha256(before.encode()).hexdigest(),
- "after_sha256": hashlib.sha256(after.encode()).hexdigest(),
- "diff": git("diff", "--", mutation.path, cwd=root),
- }
- def main() -> int:
- dirty = git("status", "--porcelain")
- if dirty:
- raise SystemExit(f"mutation gate requires a clean source worktree:\n{dirty}")
- commit = git("rev-parse", "HEAD")
- tree = git("rev-parse", "HEAD^{tree}")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- run_id = f"6400-mutation-{stamp}-{commit[:8]}"
- run_root = Path(os.environ.get("PROD2U_MUTATION_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
- run_root.mkdir(parents=True, exist_ok=False)
- records: dict[str, object] = {}
- status = "PASS"
- # Establish that every detector passes on the unmodified commit before
- # interpreting a mutant failure as useful evidence.
- with tempfile.TemporaryDirectory(prefix="prod2u-6400-mutation-baseline-") as directory:
- baseline_root = Path(directory) / "source"
- clone_at(commit, baseline_root)
- baselines: dict[str, object] = {}
- for gate, command in GATES.items():
- record = run(command, baseline_root, run_root / f"baseline-{gate}.log")
- baselines[gate] = record
- print(f"baseline {gate}: exit={record['exit_code']} duration_s={record['duration_seconds']}", flush=True)
- if record["exit_code"] != 0:
- status = "FAIL"
- records["baselines"] = baselines
- mutation_records: list[dict[str, object]] = []
- if status == "PASS":
- for mutation in MUTATIONS:
- with tempfile.TemporaryDirectory(prefix=f"prod2u-6400-{mutation.name}-") as directory:
- clone = Path(directory) / "source"
- clone_at(commit, clone)
- patch = apply_mutation(clone, mutation)
- record = run(GATES[mutation.gate], clone, run_root / f"mutation-{mutation.name}.log")
- detected = bool(record["exit_code"] != 0 and record["failure_signature"])
- item = {
- "name": mutation.name,
- "path": mutation.path,
- "gate": mutation.gate,
- "detected": detected,
- "production_tree_unchanged": not bool(git("status", "--porcelain")),
- "patch": patch,
- "run": record,
- }
- mutation_records.append(item)
- print(
- f"mutation {mutation.name}: detected={detected} "
- f"exit={record['exit_code']} duration_s={record['duration_seconds']}",
- flush=True,
- )
- if not detected:
- status = "FAIL"
- records["mutations"] = mutation_records
- if git("status", "--porcelain"):
- status = "FAIL"
- receipt = {
- "schema": "prod2u-6400-mutation-receipt-v1",
- "run_id": run_id,
- "status": status,
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "commit": commit,
- "tree": tree,
- "clean_before": not bool(dirty),
- "clean_after": not bool(git("status", "--porcelain")),
- "command": f"{sys.executable} tools/run_6400_mutation.py",
- "required_mutations": len(MUTATIONS),
- "detected_mutations": sum(bool(item["detected"]) for item in mutation_records),
- "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
- "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
- "hardware": "NOT RUN",
- **records,
- }
- receipt_path = run_root / "mutation-receipt.json"
- receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- print(receipt_path)
- if status == "PASS":
- print(f"L12_MUTATION_PASS detected={len(MUTATIONS)}/{len(MUTATIONS)}")
- return 0
- print(f"L12_MUTATION_FAIL detected={receipt['detected_mutations']}/{len(MUTATIONS)}")
- return 1
- if __name__ == "__main__":
- raise SystemExit(main())
|