l0_contract_check.py 6.2 KB

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