run_6400_mutation.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. "host": [sys.executable, "tests/cocotb/run_6400_v1_integration.py", "host_protocol"],
  25. "control": [sys.executable, "tests/cocotb/run_6400_v1_integration.py", "control"],
  26. "bmc": [sys.executable, "tests/cocotb/run_6400_bmc_fuzz.py"],
  27. "pwm": [sys.executable, "tools/run_6400_v1.py", "pwm"],
  28. }
  29. MUTATIONS = (
  30. Mutation(
  31. "crc_decision_inverted",
  32. "src/common/frame_rx.v",
  33. "if ({byte_data, received_crc_low} == crc_value) begin",
  34. "if ({byte_data, received_crc_low} != crc_value) begin",
  35. "host",
  36. ),
  37. Mutation(
  38. "hard_safety_comparator_changed",
  39. "src/control/thermal_control_core.v",
  40. "wire channel_over_77 = bmc_rd_valid && bmc_temperature >= HARD_LIMIT;",
  41. "wire channel_over_77 = bmc_rd_valid && bmc_temperature > HARD_LIMIT;",
  42. "control",
  43. ),
  44. Mutation(
  45. "bank_pointer_flip_suppressed",
  46. "src/acquisition/bmc_ascii_snapshot.v",
  47. "active_bank <= ~active_bank;",
  48. "active_bank <= active_bank;",
  49. "bmc",
  50. ),
  51. Mutation(
  52. "pwm_deadline_shortened",
  53. "src/actuator/pwm_bitmap_engine.v",
  54. "parameter integer PTC_PHASE_CLKS = 500,",
  55. "parameter integer PTC_PHASE_CLKS = 32,",
  56. "pwm",
  57. ),
  58. Mutation(
  59. "stale_threshold_off_by_one",
  60. "src/acquisition/bmc_ascii_snapshot.v",
  61. "assign stale = (age_seconds >= STALE_SECONDS[15:0]);",
  62. "assign stale = (age_seconds > STALE_SECONDS[15:0]);",
  63. "control",
  64. ),
  65. Mutation(
  66. "invalid_mask_bit_shifted",
  67. "src/acquisition/bmc_ascii_snapshot.v",
  68. "valid1[byte_count[5:1]] <= 1'b0;",
  69. "valid1[byte_count[5:1] ^ 5'd1] <= 1'b0;",
  70. # The parser fuzz gate checks exact raw/valid pairing across both
  71. # alternating banks; the full control gate happens to exercise this
  72. # mutation site only while the other bank is active.
  73. "bmc",
  74. ),
  75. )
  76. def sha256(path: Path) -> str:
  77. return hashlib.sha256(path.read_bytes()).hexdigest()
  78. def git(*args: str, cwd: Path = ROOT) -> str:
  79. return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
  80. def run(command: list[str], cwd: Path, log: Path, timeout: int = 600) -> dict[str, object]:
  81. started = time.monotonic()
  82. env = os.environ.copy()
  83. env["PYTHONDONTWRITEBYTECODE"] = "1"
  84. with log.open("wb") as stream:
  85. completed = subprocess.run(
  86. command,
  87. cwd=cwd,
  88. env=env,
  89. stdout=stream,
  90. stderr=subprocess.STDOUT,
  91. timeout=timeout,
  92. check=False,
  93. )
  94. text = log.read_text(encoding="utf-8", errors="replace")
  95. return {
  96. "command": command,
  97. "exit_code": completed.returncode,
  98. "duration_seconds": round(time.monotonic() - started, 3),
  99. "log": str(log),
  100. "log_sha256": sha256(log),
  101. "failure_signature": bool(re.search(r"(FAIL|AssertionError|FATAL|failed|error)", text, re.IGNORECASE)),
  102. "tail": "\n".join(text.splitlines()[-40:]),
  103. }
  104. def clone_at(commit: str, destination: Path) -> None:
  105. subprocess.run(["git", "clone", "--quiet", "--shared", "--no-checkout", str(ROOT), str(destination)], check=True)
  106. subprocess.run(["git", "checkout", "--quiet", "--detach", commit], cwd=destination, check=True)
  107. def apply_mutation(root: Path, mutation: Mutation) -> dict[str, str]:
  108. path = root / mutation.path
  109. before = path.read_text(encoding="utf-8")
  110. count = before.count(mutation.old)
  111. if count != 1:
  112. raise RuntimeError(f"{mutation.name}: expected one mutation site, found {count}")
  113. after = before.replace(mutation.old, mutation.new, 1)
  114. path.write_text(after, encoding="utf-8")
  115. return {
  116. "before_sha256": hashlib.sha256(before.encode()).hexdigest(),
  117. "after_sha256": hashlib.sha256(after.encode()).hexdigest(),
  118. "diff": git("diff", "--", mutation.path, cwd=root),
  119. }
  120. def main() -> int:
  121. dirty = git("status", "--porcelain")
  122. if dirty:
  123. raise SystemExit(f"mutation gate requires a clean source worktree:\n{dirty}")
  124. commit = git("rev-parse", "HEAD")
  125. tree = git("rev-parse", "HEAD^{tree}")
  126. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  127. run_id = f"6400-mutation-{stamp}-{commit[:8]}"
  128. run_root = Path(os.environ.get("PROD2U_MUTATION_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  129. run_root.mkdir(parents=True, exist_ok=False)
  130. records: dict[str, object] = {}
  131. status = "PASS"
  132. # Establish that every detector passes on the unmodified commit before
  133. # interpreting a mutant failure as useful evidence.
  134. with tempfile.TemporaryDirectory(prefix="prod2u-6400-mutation-baseline-") as directory:
  135. baseline_root = Path(directory) / "source"
  136. clone_at(commit, baseline_root)
  137. baselines: dict[str, object] = {}
  138. for gate, command in GATES.items():
  139. record = run(command, baseline_root, run_root / f"baseline-{gate}.log")
  140. baselines[gate] = record
  141. print(f"baseline {gate}: exit={record['exit_code']} duration_s={record['duration_seconds']}", flush=True)
  142. if record["exit_code"] != 0:
  143. status = "FAIL"
  144. records["baselines"] = baselines
  145. mutation_records: list[dict[str, object]] = []
  146. if status == "PASS":
  147. for mutation in MUTATIONS:
  148. with tempfile.TemporaryDirectory(prefix=f"prod2u-6400-{mutation.name}-") as directory:
  149. clone = Path(directory) / "source"
  150. clone_at(commit, clone)
  151. patch = apply_mutation(clone, mutation)
  152. record = run(GATES[mutation.gate], clone, run_root / f"mutation-{mutation.name}.log")
  153. detected = bool(record["exit_code"] != 0 and record["failure_signature"])
  154. item = {
  155. "name": mutation.name,
  156. "path": mutation.path,
  157. "gate": mutation.gate,
  158. "detected": detected,
  159. "production_tree_unchanged": not bool(git("status", "--porcelain")),
  160. "patch": patch,
  161. "run": record,
  162. }
  163. mutation_records.append(item)
  164. print(
  165. f"mutation {mutation.name}: detected={detected} "
  166. f"exit={record['exit_code']} duration_s={record['duration_seconds']}",
  167. flush=True,
  168. )
  169. if not detected:
  170. status = "FAIL"
  171. records["mutations"] = mutation_records
  172. if git("status", "--porcelain"):
  173. status = "FAIL"
  174. receipt = {
  175. "schema": "prod2u-6400-mutation-receipt-v1",
  176. "run_id": run_id,
  177. "status": status,
  178. "generated_at": datetime.now(timezone.utc).isoformat(),
  179. "commit": commit,
  180. "tree": tree,
  181. "clean_before": not bool(dirty),
  182. "clean_after": not bool(git("status", "--porcelain")),
  183. "command": f"{sys.executable} tools/run_6400_mutation.py",
  184. "required_mutations": len(MUTATIONS),
  185. "detected_mutations": sum(bool(item["detected"]) for item in mutation_records),
  186. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  187. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  188. "hardware": "NOT RUN",
  189. **records,
  190. }
  191. receipt_path = run_root / "mutation-receipt.json"
  192. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  193. print(receipt_path)
  194. if status == "PASS":
  195. print(f"L12_MUTATION_PASS detected={len(MUTATIONS)}/{len(MUTATIONS)}")
  196. return 0
  197. print(f"L12_MUTATION_FAIL detected={receipt['detected_mutations']}/{len(MUTATIONS)}")
  198. return 1
  199. if __name__ == "__main__":
  200. raise SystemExit(main())