run_6400_mutation.py 8.1 KB

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