run_6400_soak.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #!/usr/bin/env python3
  2. """Run L11 deterministic randomized soak and emit a source-bound receipt."""
  3. from __future__ import annotations
  4. from datetime import datetime, timezone
  5. import hashlib
  6. import json
  7. import os
  8. from pathlib import Path
  9. import subprocess
  10. import tempfile
  11. import time
  12. import xml.etree.ElementTree as ET
  13. try:
  14. from cocotb_tools.runner import get_runner
  15. except ModuleNotFoundError:
  16. from cocotb.runner import get_runner
  17. ROOT = Path(__file__).resolve().parents[1]
  18. TEST_DIR = ROOT / "tests/cocotb"
  19. CLOSURE = ROOT / "products/6400-front-rear/source-closure.json"
  20. WRAPPER = TEST_DIR / "prod2u_6400_v1_cocotb_top.v"
  21. def sha256(path: Path) -> str:
  22. return hashlib.sha256(path.read_bytes()).hexdigest()
  23. def git(*args: str) -> str:
  24. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  25. def main() -> int:
  26. dirty = git("status", "--porcelain")
  27. if dirty:
  28. raise SystemExit(f"soak requires a clean source worktree:\n{dirty}")
  29. commit = git("rev-parse", "HEAD")
  30. tree = git("rev-parse", "HEAD^{tree}")
  31. closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
  32. sources = [ROOT / item for item in closure["sources"] if item.endswith(".v")]
  33. input_paths = [CLOSURE, WRAPPER, TEST_DIR / "thermal_6400_uart.py", TEST_DIR / "test_6400_v1_soak.py", *sources]
  34. inputs = {str(path.relative_to(ROOT)): sha256(path) for path in input_paths}
  35. source_hash = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
  36. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  37. run_id = f"6400-soak-{stamp}-{commit[:8]}"
  38. run_root = Path(os.environ.get("PROD2U_SOAK_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  39. run_root.mkdir(parents=True, exist_ok=False)
  40. result_json = run_root / "soak-result.json"
  41. results_xml = run_root / "results.xml"
  42. seed = int(os.environ.get("PROD2U_SOAK_SEED", "1677779166"))
  43. iterations = int(os.environ.get("PROD2U_SOAK_ITERATIONS", "96"))
  44. runner = get_runner("icarus")
  45. started = time.monotonic()
  46. status = "FAIL"
  47. failure = None
  48. try:
  49. runner.build(
  50. sources=[*sources, WRAPPER],
  51. hdl_toplevel="prod2u_6400_v1_cocotb_top",
  52. build_dir=run_root / "build",
  53. build_args=["-g2012", "-I", str(ROOT)],
  54. parameters={"ENABLE_STIMULUS": 1, "BMC_INITIAL_EPOCH": 0xFFFA},
  55. always=True,
  56. )
  57. result_path = Path(runner.test(
  58. hdl_toplevel="prod2u_6400_v1_cocotb_top",
  59. test_module="test_6400_v1_soak",
  60. test_dir=TEST_DIR,
  61. build_dir=run_root / "build",
  62. results_xml=str(results_xml),
  63. extra_env={
  64. "PROD2U_SOAK_RESULT": str(result_json),
  65. "PROD2U_SOAK_SEED": str(seed),
  66. "PROD2U_SOAK_ITERATIONS": str(iterations),
  67. "PYTHONPATH": str(TEST_DIR),
  68. },
  69. ))
  70. xml = ET.parse(result_path).getroot()
  71. cases = xml.findall(".//testcase")
  72. failures = xml.findall(".//failure") + xml.findall(".//error")
  73. skipped = xml.findall(".//skipped")
  74. if len(cases) != 1 or failures or skipped or not result_json.is_file():
  75. raise RuntimeError(f"incomplete soak cases={len(cases)} failures={len(failures)} skipped={len(skipped)}")
  76. status = "PASS"
  77. except Exception as exc: # receipt must survive a failed test
  78. failure = f"{type(exc).__name__}: {exc}"
  79. duration = round(time.monotonic() - started, 3)
  80. payload = json.loads(result_json.read_text(encoding="utf-8")) if result_json.is_file() else None
  81. receipt = {
  82. "schema": "prod2u-6400-soak-receipt-v1",
  83. "run_id": run_id,
  84. "status": status,
  85. "generated_at": datetime.now(timezone.utc).isoformat(),
  86. "commit": commit,
  87. "tree": tree,
  88. "clean": not bool(dirty),
  89. "command": "python3 tools/run_6400_soak.py",
  90. "seed": seed,
  91. "iterations": iterations,
  92. "duration_seconds": duration,
  93. "source_manifest_sha256": source_hash,
  94. "inputs": inputs,
  95. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  96. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  97. "result": payload,
  98. "results_xml": str(results_xml) if results_xml.is_file() else None,
  99. "results_xml_sha256": sha256(results_xml) if results_xml.is_file() else None,
  100. "failure": failure,
  101. "hardware": "NOT RUN",
  102. }
  103. receipt_path = run_root / "soak-receipt.json"
  104. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  105. print(receipt_path)
  106. if status == "PASS":
  107. print(f"L11_SOAK_PASS iterations={iterations} seed={seed} duration_s={duration}")
  108. return 0
  109. print(f"L11_SOAK_FAIL {failure}")
  110. return 1
  111. if __name__ == "__main__":
  112. raise SystemExit(main())