l0_contract_check.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python3
  2. """L0: contract SHA snapshot, gen_profile drift, gofmt, optional buf lint."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import subprocess
  9. import sys
  10. import tempfile
  11. from pathlib import Path
  12. HOST = Path(__file__).resolve().parents[1]
  13. REPO = HOST.parent
  14. SKIP_GO_PREFIXES = ("internal/gen/",)
  15. TOOLCHAIN_PATH_PREFIX = (
  16. "/data/prod2u/bin",
  17. "/data/prod2u/opt/go1.25.13/bin",
  18. "/opt/python-3.12/bin",
  19. "/usr/bin",
  20. "/bin",
  21. )
  22. def _ensure_toolchain_path() -> None:
  23. cur = os.environ.get("PATH", "")
  24. parts = [p for p in TOOLCHAIN_PATH_PREFIX if p]
  25. for p in cur.split(os.pathsep):
  26. if p and p not in parts:
  27. parts.append(p)
  28. os.environ["PATH"] = os.pathsep.join(parts)
  29. def sha256(path: Path) -> str:
  30. return hashlib.sha256(path.read_bytes()).hexdigest()
  31. def check_gofmt() -> list[str]:
  32. files: list[str] = []
  33. for path in HOST.rglob("*.go"):
  34. rel = path.relative_to(HOST).as_posix()
  35. if rel.startswith(SKIP_GO_PREFIXES) or "/gen/" in rel:
  36. continue
  37. files.append(str(path))
  38. if not files:
  39. return []
  40. out = subprocess.check_output(["gofmt", "-l", *files], text=True)
  41. return [line for line in out.splitlines() if line.strip()]
  42. def check_profile_drift() -> str | None:
  43. gen = HOST / "tools" / "gen_profile.py"
  44. committed = HOST / "profiles" / "prod2u-door-temp" / "profile.json"
  45. with tempfile.TemporaryDirectory() as tmp:
  46. out = Path(tmp) / "profile.json"
  47. subprocess.check_call([sys.executable, str(gen), "--repo-root", str(REPO), "--out", str(out)])
  48. got = json.loads(out.read_text(encoding="utf-8"))
  49. want = json.loads(committed.read_text(encoding="utf-8"))
  50. if got != want:
  51. return "gen_profile.py output differs from host/profiles/prod2u-door-temp/profile.json"
  52. return None
  53. def evidence() -> dict[str, str]:
  54. legacy = HOST / "contracts" / "evidence"
  55. old_generated = REPO / "src" / "generated"
  56. contract = old_generated / "host-contract.json"
  57. golden = old_generated / "golden-vectors.json"
  58. if not contract.is_file():
  59. contract = legacy / "host-contract.json"
  60. if not golden.is_file():
  61. golden = legacy / "golden-vectors.json"
  62. paths = {
  63. "host-contract.json": contract,
  64. "golden-vectors.json": golden,
  65. "legacy-RTL_REF.txt": legacy / "RTL_REF.txt",
  66. "legacy-SHA256SUMS": legacy / "SHA256SUMS",
  67. "6400-host-contract.json": HOST / "contracts" / "6400" / "host-contract.json",
  68. "6400-SHA256SUMS": HOST / "contracts" / "6400" / "SHA256SUMS",
  69. "profile.json": HOST / "profiles" / "prod2u-door-temp" / "profile.json",
  70. "hth.proto": HOST / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  71. }
  72. out: dict[str, str] = {}
  73. for name, path in paths.items():
  74. if path.is_file():
  75. out[name] = sha256(path)
  76. else:
  77. out[name] = "MISSING"
  78. return out
  79. def maybe_buf() -> str:
  80. try:
  81. buf = subprocess.run(["buf", "--version"], capture_output=True, text=True)
  82. except FileNotFoundError:
  83. return "buf: NOT RUN (binary missing)"
  84. if buf.returncode != 0:
  85. return "buf: NOT RUN (binary missing)"
  86. lint = subprocess.run(["buf", "lint"], cwd=HOST, capture_output=True, text=True)
  87. if lint.returncode != 0:
  88. return f"buf lint FAIL\n{lint.stdout}\n{lint.stderr}"
  89. desc = HOST / "api" / "proto" / "hth.api.v1.desc.prev"
  90. if desc.is_file():
  91. against = f"{desc}#format=binpb"
  92. brk = subprocess.run(
  93. ["buf", "breaking", "--against", against],
  94. cwd=HOST,
  95. capture_output=True,
  96. text=True,
  97. )
  98. if brk.returncode != 0:
  99. return f"buf breaking FAIL\n{brk.stdout}\n{brk.stderr}"
  100. return f"buf lint PASS; buf breaking PASS against {desc.name}"
  101. return "buf lint PASS; buf breaking NOT RUN (no previous descriptor)"
  102. def main() -> int:
  103. _ensure_toolchain_path()
  104. ap = argparse.ArgumentParser()
  105. ap.add_argument("--repo-root", type=Path, default=None)
  106. ap.add_argument("--evidence-root", type=Path, default=None)
  107. ap.add_argument(
  108. "--mode",
  109. choices=("offline", "release"),
  110. default="offline",
  111. help="offline: buf missing is PARTIAL; release: buf lint+breaking required",
  112. )
  113. args = ap.parse_args()
  114. global HOST, REPO
  115. if args.repo_root is not None:
  116. REPO = args.repo_root.resolve()
  117. if (REPO / "host" / "go.mod").is_file():
  118. HOST = REPO / "host"
  119. elif (REPO / "go.mod").is_file():
  120. HOST = REPO
  121. ev_root = args.evidence_root.resolve() if args.evidence_root else None
  122. ev = evidence()
  123. if ev_root is not None:
  124. for name in list(ev):
  125. alt = ev_root / name
  126. if alt.is_file():
  127. ev[name] = sha256(alt)
  128. print("L0_EVIDENCE_SHA256")
  129. for k, v in ev.items():
  130. print(f"{v} {k}")
  131. if v == "MISSING":
  132. print("L0_FAIL missing evidence file", k, file=sys.stderr)
  133. return 1
  134. dirty = check_gofmt()
  135. if dirty:
  136. print("L0_FAIL gofmt", file=sys.stderr)
  137. print("\n".join(dirty), file=sys.stderr)
  138. return 1
  139. print("gofmt: clean")
  140. drift = check_profile_drift()
  141. if drift:
  142. print("L0_FAIL", drift, file=sys.stderr)
  143. return 1
  144. print("gen_profile: no drift")
  145. oracle = HOST / "tools" / "protocol_oracle.py"
  146. golden = REPO / "src" / "generated" / "golden-vectors.json"
  147. if ev_root is not None and (ev_root / "golden-vectors.json").is_file():
  148. golden = ev_root / "golden-vectors.json"
  149. elif not golden.is_file() and (HOST / "contracts" / "evidence" / "golden-vectors.json").is_file():
  150. golden = HOST / "contracts" / "evidence" / "golden-vectors.json"
  151. o = subprocess.run(
  152. [
  153. sys.executable,
  154. str(oracle),
  155. "--golden",
  156. str(golden),
  157. "--min-positive",
  158. "8",
  159. "--min-negative",
  160. "2",
  161. "--min-frames",
  162. "6",
  163. ],
  164. capture_output=True,
  165. text=True,
  166. )
  167. print(o.stdout.strip())
  168. if o.returncode != 0:
  169. print("L0_FAIL oracle", file=sys.stderr)
  170. print(o.stderr, file=sys.stderr)
  171. return 1
  172. buf_line = maybe_buf()
  173. print(buf_line)
  174. buf_missing = "NOT RUN" in buf_line
  175. buf_fail = "FAIL" in buf_line
  176. if args.mode == "release":
  177. if buf_missing or buf_fail:
  178. print("L0_RELEASE_GATE_FAIL buf required", file=sys.stderr)
  179. print(buf_line, file=sys.stderr)
  180. return 1
  181. print("L0_RELEASE_CONTRACT_GATE_PASS")
  182. print("L0_CONTRACT_CHECK_PASS")
  183. return 0
  184. if buf_fail:
  185. print("L0_FAIL buf", file=sys.stderr)
  186. return 1
  187. if buf_missing:
  188. print("L0_OFFLINE_EVIDENCE_CHECK_PARTIAL")
  189. print("buf NOT RUN")
  190. return 0
  191. print("L0_OFFLINE_EVIDENCE_CHECK_PASS")
  192. print("L0_CONTRACT_CHECK_PASS")
  193. return 0
  194. if __name__ == "__main__":
  195. raise SystemExit(main())