run_6400_mutation.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env python3
  2. """L12 bounded fault seeding in disposable clones of the clean source tree."""
  3. from __future__ import annotations
  4. from dataclasses import dataclass
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import json
  8. import os
  9. from pathlib import Path
  10. import re
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import time
  15. ROOT = Path(__file__).resolve().parents[1]
  16. @dataclass(frozen=True)
  17. class Mutation:
  18. name: str
  19. path: str
  20. old: str
  21. new: str
  22. gate: str
  23. GATES = {
  24. # The retired host_protocol/control cocotb profile names are deliberately
  25. # not part of the active V1.1 contract. Use the maintained aggregate
  26. # simulation entrypoint, which covers both host transport and control
  27. # benches, plus the current BMC and PWM gates.
  28. "host": [sys.executable, "tools/run_6400_v1.py", "sim"],
  29. "control": [sys.executable, "-B", "-m", "pytest", "-q", "tests/unit/test_6400_contract.py"],
  30. # The active deterministic BMC parser bench is already part of `sim`;
  31. # the optional cocotb BMC lane requires a libpython shared library that
  32. # is not present in every verification image.
  33. "bmc": [sys.executable, "tools/run_6400_v1.py", "sim"],
  34. "pwm": [sys.executable, "tools/run_6400_v1.py", "pwm"],
  35. }
  36. MUTATIONS = (
  37. Mutation(
  38. "crc_decision_inverted",
  39. "src/common/frame_rx.v",
  40. "if ({byte_data, received_crc_low} == crc_value) begin",
  41. "if ({byte_data, received_crc_low} != crc_value) begin",
  42. "host",
  43. ),
  44. Mutation(
  45. "hard_safety_comparator_changed",
  46. "src/control/thermal_control_core.v",
  47. "wire scan_over77 = bmc_rd_valid && (bmc_celsius >= 16'd77);",
  48. "wire scan_over77 = bmc_rd_valid && (bmc_celsius > 16'd77);",
  49. "control",
  50. ),
  51. Mutation(
  52. "bank_pointer_flip_suppressed",
  53. "src/acquisition/bmc_ascii_snapshot.v",
  54. "active_bank <= ~active_bank;",
  55. "active_bank <= active_bank;",
  56. "bmc",
  57. ),
  58. Mutation(
  59. "pwm_deadline_shortened",
  60. "src/actuator/pwm_bitmap_engine.v",
  61. "parameter integer PTC_PHASE_CLKS = 500,",
  62. "parameter integer PTC_PHASE_CLKS = 32,",
  63. "pwm",
  64. ),
  65. Mutation(
  66. "stale_threshold_off_by_one",
  67. "src/acquisition/bmc_ascii_snapshot.v",
  68. "assign stale = (age_seconds >= STALE_SECONDS[15:0]);",
  69. "assign stale = (age_seconds > STALE_SECONDS[15:0]);",
  70. "control",
  71. ),
  72. Mutation(
  73. "invalid_mask_bit_shifted",
  74. "src/acquisition/bmc_ascii_snapshot.v",
  75. "valid1[byte_count[5:1]] <= 1'b0;",
  76. "valid1[byte_count[5:1] ^ 5'd1] <= 1'b0;",
  77. # The parser fuzz gate checks exact raw/valid pairing across both
  78. # alternating banks; the full control gate happens to exercise this
  79. # mutation site only while the other bank is active.
  80. "bmc",
  81. ),
  82. )
  83. def sha256(path: Path) -> str:
  84. return hashlib.sha256(path.read_bytes()).hexdigest()
  85. def git(*args: str, cwd: Path = ROOT) -> str:
  86. return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
  87. def run(command: list[str], cwd: Path, log: Path, timeout: int = 600) -> dict[str, object]:
  88. started = time.monotonic()
  89. env = os.environ.copy()
  90. env["PYTHONDONTWRITEBYTECODE"] = "1"
  91. # Keep the runner portable: Windows may intentionally lack HDL tools,
  92. # while the authorized Linux verification host keeps them on persistent
  93. # volumes outside the base PATH.
  94. tool_bins = [
  95. Path("/data/prod2u/toolchain/iverilog/usr/bin"),
  96. Path("/data/prod2u/oss-cad-suite/latest/bin"),
  97. ]
  98. available = [str(path) for path in tool_bins if path.is_dir()]
  99. if available:
  100. env["PATH"] = os.pathsep.join([*available, env.get("PATH", "")])
  101. with log.open("wb") as stream:
  102. completed = subprocess.run(
  103. command,
  104. cwd=cwd,
  105. env=env,
  106. stdout=stream,
  107. stderr=subprocess.STDOUT,
  108. timeout=timeout,
  109. check=False,
  110. )
  111. text = log.read_text(encoding="utf-8", errors="replace")
  112. return {
  113. "command": command,
  114. "exit_code": completed.returncode,
  115. "duration_seconds": round(time.monotonic() - started, 3),
  116. "log": str(log),
  117. "log_sha256": sha256(log),
  118. "failure_signature": bool(re.search(r"(FAIL|AssertionError|FATAL|failed|error)", text, re.IGNORECASE)),
  119. "tail": "\n".join(text.splitlines()[-40:]),
  120. }
  121. def clone_at(commit: str, destination: Path) -> None:
  122. subprocess.run(["git", "clone", "--quiet", "--shared", "--no-checkout", str(ROOT), str(destination)], check=True)
  123. subprocess.run(["git", "checkout", "--quiet", "--detach", commit], cwd=destination, check=True)
  124. def apply_mutation(root: Path, mutation: Mutation) -> dict[str, str]:
  125. path = root / mutation.path
  126. before = path.read_text(encoding="utf-8")
  127. count = before.count(mutation.old)
  128. if count != 1:
  129. raise RuntimeError(f"{mutation.name}: expected one mutation site, found {count}")
  130. after = before.replace(mutation.old, mutation.new, 1)
  131. path.write_text(after, encoding="utf-8")
  132. return {
  133. "before_sha256": hashlib.sha256(before.encode()).hexdigest(),
  134. "after_sha256": hashlib.sha256(after.encode()).hexdigest(),
  135. "diff": git("diff", "--", mutation.path, cwd=root),
  136. }
  137. def main() -> int:
  138. dirty = git("status", "--porcelain")
  139. if dirty:
  140. raise SystemExit(f"mutation gate requires a clean source worktree:\n{dirty}")
  141. commit = git("rev-parse", "HEAD")
  142. tree = git("rev-parse", "HEAD^{tree}")
  143. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  144. run_id = f"6400-mutation-{stamp}-{commit[:8]}"
  145. run_root = Path(os.environ.get("PROD2U_MUTATION_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  146. run_root.mkdir(parents=True, exist_ok=False)
  147. records: dict[str, object] = {}
  148. status = "PASS"
  149. # Establish that every detector passes on the unmodified commit before
  150. # interpreting a mutant failure as useful evidence.
  151. with tempfile.TemporaryDirectory(prefix="prod2u-6400-mutation-baseline-") as directory:
  152. baseline_root = Path(directory) / "source"
  153. clone_at(commit, baseline_root)
  154. baselines: dict[str, object] = {}
  155. for gate, command in GATES.items():
  156. record = run(command, baseline_root, run_root / f"baseline-{gate}.log")
  157. baselines[gate] = record
  158. print(f"baseline {gate}: exit={record['exit_code']} duration_s={record['duration_seconds']}", flush=True)
  159. if record["exit_code"] != 0:
  160. status = "FAIL"
  161. records["baselines"] = baselines
  162. mutation_records: list[dict[str, object]] = []
  163. if status == "PASS":
  164. for mutation in MUTATIONS:
  165. with tempfile.TemporaryDirectory(prefix=f"prod2u-6400-{mutation.name}-") as directory:
  166. clone = Path(directory) / "source"
  167. clone_at(commit, clone)
  168. patch = apply_mutation(clone, mutation)
  169. record = run(GATES[mutation.gate], clone, run_root / f"mutation-{mutation.name}.log")
  170. detected = bool(record["exit_code"] != 0 and record["failure_signature"])
  171. item = {
  172. "name": mutation.name,
  173. "path": mutation.path,
  174. "gate": mutation.gate,
  175. "detected": detected,
  176. "production_tree_unchanged": not bool(git("status", "--porcelain")),
  177. "patch": patch,
  178. "run": record,
  179. }
  180. mutation_records.append(item)
  181. print(
  182. f"mutation {mutation.name}: detected={detected} "
  183. f"exit={record['exit_code']} duration_s={record['duration_seconds']}",
  184. flush=True,
  185. )
  186. if not detected:
  187. status = "FAIL"
  188. records["mutations"] = mutation_records
  189. if git("status", "--porcelain"):
  190. status = "FAIL"
  191. receipt = {
  192. "schema": "prod2u-6400-mutation-receipt-v1",
  193. "run_id": run_id,
  194. "status": status,
  195. "generated_at": datetime.now(timezone.utc).isoformat(),
  196. "commit": commit,
  197. "tree": tree,
  198. "clean_before": not bool(dirty),
  199. "clean_after": not bool(git("status", "--porcelain")),
  200. "command": f"{sys.executable} tools/run_6400_mutation.py",
  201. "required_mutations": len(MUTATIONS),
  202. "detected_mutations": sum(bool(item["detected"]) for item in mutation_records),
  203. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  204. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  205. "hardware": "NOT RUN",
  206. **records,
  207. }
  208. receipt_path = run_root / "mutation-receipt.json"
  209. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  210. print(receipt_path)
  211. if status == "PASS":
  212. print(f"L12_MUTATION_PASS detected={len(MUTATIONS)}/{len(MUTATIONS)}")
  213. return 0
  214. print(f"L12_MUTATION_FAIL detected={receipt['detected_mutations']}/{len(MUTATIONS)}")
  215. return 1
  216. if __name__ == "__main__":
  217. raise SystemExit(main())