current_evidence.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #!/usr/bin/env python3
  2. """Select current matrix / Formal evidence by explicit tip + run ID.
  3. Never use "last same basename", hardcoded R7/R8 paths, or directory-scan order.
  4. Historical receipts stay under receipts/historical/ or receipts/mse-rN-matrix/
  5. and are not current authority unless that run_id is the explicit selector.
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import json
  10. import os
  11. import re
  12. from pathlib import Path
  13. from typing import Any
  14. ROOT = Path(__file__).resolve().parents[1]
  15. REQUIRED_MATRIX_LANES = (
  16. "python",
  17. "board_viewer",
  18. "icarus",
  19. "verilator",
  20. "cocotb",
  21. "formal",
  22. )
  23. REQUIRED_FORMAL_TARGET_COUNT = 23
  24. DISPATCHER_TARGET = "door_rate_quantum_dispatcher"
  25. DISPATCHER_COVER_EXACT = 10
  26. CANONICAL_MATRIX_REL = "evidence/matrix/verification-matrix-final.json"
  27. CANONICAL_FORMAL_REL = "evidence/formal/formal-receipt.json"
  28. STALE_CURRENT_TOKENS = (
  29. "mse-r7-20260812T132652Z",
  30. "21ed755ad2ddb6689bca88a9a037b391372a060e",
  31. "3177c2f01070b32460dee826e41b685f482fea26",
  32. )
  33. FORBIDDEN_IDENTITY_TOKENS = ("PENDING", "pending_package", "hook_ready")
  34. class CurrentEvidenceError(RuntimeError):
  35. """Fail-closed current-evidence selection or validation error."""
  36. def _sha256_file(path: Path) -> str:
  37. digest = hashlib.sha256()
  38. with path.open("rb") as handle:
  39. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  40. digest.update(chunk)
  41. return digest.hexdigest()
  42. def commits_match(left: str | None, right: str | None) -> bool:
  43. a = str(left or "").strip().casefold()
  44. b = str(right or "").strip().casefold()
  45. if not a or not b:
  46. return False
  47. n = min(len(a), len(b))
  48. if n < 7:
  49. return False
  50. return a[:n] == b[:n]
  51. def matrix_family_dir(run_id: str) -> str:
  52. """mse-r10-20260813T010203Z → mse-r10-matrix (explicit, not a glob)."""
  53. text = str(run_id or "").strip()
  54. parts = text.split("-")
  55. if len(parts) < 3 or parts[0] != "mse" or not parts[1].startswith("r"):
  56. raise CurrentEvidenceError(f"bad_matrix_run_id:{run_id}")
  57. return f"{parts[0]}-{parts[1]}-matrix"
  58. def current_matrix_path(
  59. repo: Path,
  60. *,
  61. run_id: str,
  62. override: str | None = None,
  63. ) -> Path:
  64. explicit = (override or os.environ.get("PRODU2_CURRENT_MATRIX_PATH", "")).strip()
  65. if explicit:
  66. path = Path(explicit)
  67. if not path.is_absolute():
  68. path = repo / path
  69. return path
  70. family = matrix_family_dir(run_id)
  71. return repo / "receipts" / family / run_id / "unified-matrix-report.json"
  72. def current_formal_path(
  73. repo: Path,
  74. *,
  75. run_id: str,
  76. override: str | None = None,
  77. ) -> Path:
  78. explicit = (override or os.environ.get("PRODU2_CURRENT_FORMAL_PATH", "")).strip()
  79. if explicit:
  80. path = Path(explicit)
  81. if not path.is_absolute():
  82. path = repo / path
  83. return path
  84. family = matrix_family_dir(run_id)
  85. return repo / "receipts" / family / run_id / "lanes" / "formal-receipt.json"
  86. def select_current_matrix(
  87. repo: Path,
  88. *,
  89. verification_tip: str,
  90. run_id: str,
  91. ) -> Path:
  92. path = current_matrix_path(repo, run_id=run_id)
  93. if not path.is_file():
  94. raise CurrentEvidenceError(f"missing_current_matrix:{path}")
  95. doc = json.loads(path.read_text(encoding="utf-8"))
  96. failures = validate_matrix_report(
  97. doc, verification_tip=verification_tip, run_id=run_id
  98. )
  99. if failures:
  100. raise CurrentEvidenceError("current_matrix_invalid:" + ",".join(failures[:12]))
  101. return path
  102. def select_current_formal(
  103. repo: Path,
  104. *,
  105. verification_tip: str,
  106. run_id: str,
  107. ) -> Path:
  108. path = current_formal_path(repo, run_id=run_id)
  109. if not path.is_file():
  110. raise CurrentEvidenceError(f"missing_current_formal:{path}")
  111. doc = json.loads(path.read_text(encoding="utf-8"))
  112. failures = validate_formal_receipt(doc, verification_tip=verification_tip)
  113. if failures:
  114. raise CurrentEvidenceError("current_formal_invalid:" + ",".join(failures[:12]))
  115. return path
  116. def stage_current_evidence(
  117. *,
  118. repo: Path,
  119. staging_root: Path,
  120. verification_tip: str,
  121. run_id: str,
  122. ) -> dict[str, Path]:
  123. """Copy the explicitly selected current receipts onto canonical evidence/ paths."""
  124. matrix_src = select_current_matrix(
  125. repo, verification_tip=verification_tip, run_id=run_id
  126. )
  127. formal_src = select_current_formal(
  128. repo, verification_tip=verification_tip, run_id=run_id
  129. )
  130. matrix_dest = staging_root / Path(*CANONICAL_MATRIX_REL.split("/"))
  131. formal_dest = staging_root / Path(*CANONICAL_FORMAL_REL.split("/"))
  132. matrix_dest.parent.mkdir(parents=True, exist_ok=True)
  133. formal_dest.parent.mkdir(parents=True, exist_ok=True)
  134. matrix_dest.write_bytes(matrix_src.read_bytes())
  135. formal_dest.write_bytes(formal_src.read_bytes())
  136. return {"matrix": matrix_dest, "formal": formal_dest}
  137. def validate_matrix_report(
  138. doc: Any,
  139. *,
  140. verification_tip: str | None = None,
  141. run_id: str | None = None,
  142. ) -> list[str]:
  143. failures: list[str] = []
  144. if not isinstance(doc, dict) or not doc:
  145. return ["matrix_not_object_or_empty"]
  146. schema = str(doc.get("schema") or "")
  147. if "verification-matrix" not in schema.casefold():
  148. failures.append(f"matrix_schema_unexpected:{schema or 'empty'}")
  149. status = str(doc.get("status") or "").casefold()
  150. if status != "pass":
  151. failures.append(f"matrix_status_not_pass:{status or 'empty'}")
  152. failures_field = doc.get("failures")
  153. if failures_field is None:
  154. failures.append("matrix_failures_missing")
  155. elif failures_field not in ([], ()):
  156. failures.append("matrix_failures_not_empty")
  157. if verification_tip:
  158. commit = str(doc.get("commit_full") or doc.get("commit") or "")
  159. if not commits_match(commit, verification_tip):
  160. failures.append("matrix_tip_mismatch")
  161. lanes = doc.get("lanes")
  162. if not isinstance(lanes, dict):
  163. failures.append("matrix_lanes_missing")
  164. lanes = {}
  165. for name in REQUIRED_MATRIX_LANES:
  166. lane = lanes.get(name)
  167. if not isinstance(lane, dict):
  168. failures.append(f"matrix_lane_missing:{name}")
  169. continue
  170. lane_status = str(lane.get("status") or "").casefold()
  171. if lane_status != "pass":
  172. failures.append(f"matrix_lane_not_pass:{name}:{lane_status or 'empty'}")
  173. if verification_tip:
  174. lane_commit = str(lane.get("commit_full") or lane.get("commit") or "")
  175. if lane_commit and not commits_match(lane_commit, verification_tip):
  176. failures.append(f"matrix_lane_tip_mismatch:{name}")
  177. if name == "board_viewer":
  178. mode = str(lane.get("mode") or lane.get("selection", {}).get("mode") or "")
  179. if mode and mode != "detached_derived":
  180. failures.append(f"board_viewer_mode_not_detached_derived:{mode}")
  181. if run_id:
  182. # User-level run id lives in the receipts path; JSON may use a hex verification_run_id.
  183. json_run = str(doc.get("software_verification_run_id") or doc.get("run_id") or "")
  184. if json_run and json_run != run_id and run_id not in json_run:
  185. # Hex lane ids are expected; only fail when a conflicting mse-r* id is present.
  186. if re.match(r"^mse-r\d+-", json_run) and json_run != run_id:
  187. failures.append(f"matrix_run_id_mismatch:{json_run}")
  188. return failures
  189. def validate_formal_receipt(
  190. doc: Any,
  191. *,
  192. verification_tip: str | None = None,
  193. ) -> list[str]:
  194. failures: list[str] = []
  195. if not isinstance(doc, dict) or not doc:
  196. return ["formal_not_object_or_empty"]
  197. schema = str(doc.get("schema") or "")
  198. if schema != "prod2u-p4-normal-v3-formal-receipt-v1":
  199. failures.append(f"formal_schema_unexpected:{schema or 'empty'}")
  200. status = str(doc.get("status") or "").casefold()
  201. if status != "pass":
  202. failures.append(f"formal_status_not_pass:{status or 'empty'}")
  203. if verification_tip:
  204. commit = str(doc.get("commit_full") or doc.get("commit") or "")
  205. if commit and not commits_match(commit, verification_tip):
  206. failures.append("formal_tip_mismatch")
  207. targets = doc.get("targets")
  208. if not isinstance(targets, list):
  209. failures.append("formal_targets_missing")
  210. return failures
  211. if len(targets) != REQUIRED_FORMAL_TARGET_COUNT:
  212. failures.append(f"formal_target_count:{len(targets)}")
  213. names: list[str] = []
  214. dispatcher = None
  215. for target in targets:
  216. if not isinstance(target, dict):
  217. failures.append("formal_target_not_object")
  218. continue
  219. name = str(target.get("name") or "")
  220. names.append(name)
  221. t_status = str(target.get("status") or "").casefold()
  222. if t_status != "pass":
  223. failures.append(f"formal_target_not_pass:{name or '?'}:{t_status or 'empty'}")
  224. rc = target.get("returncode")
  225. if rc not in (0, "0"):
  226. failures.append(f"formal_target_rc:{name}:{rc}")
  227. tasks = target.get("task_results")
  228. if isinstance(tasks, list):
  229. if not tasks:
  230. failures.append(f"formal_target_tasks_empty:{name}")
  231. for task in tasks:
  232. if not isinstance(task, dict):
  233. failures.append(f"formal_task_not_object:{name}")
  234. continue
  235. raw = str(task.get("status") or "").casefold()
  236. if raw not in {"pass", "passed"}:
  237. failures.append(
  238. f"formal_task_not_pass:{name}:{task.get('name')}:{raw or 'empty'}"
  239. )
  240. task_rc = task.get("returncode")
  241. if task_rc not in (0, "0"):
  242. failures.append(
  243. f"formal_task_rc:{name}:{task.get('name')}:{task_rc}"
  244. )
  245. if name == DISPATCHER_TARGET:
  246. dispatcher = target
  247. if len(set(names)) != len(names):
  248. failures.append("formal_duplicate_target_names")
  249. if dispatcher is None:
  250. failures.append("formal_dispatcher_missing")
  251. else:
  252. hit = dispatcher.get("cover_hit_count")
  253. count = dispatcher.get("cover_count")
  254. ids = dispatcher.get("cover_hit_ids") or []
  255. if count != DISPATCHER_COVER_EXACT:
  256. failures.append(f"dispatcher_cover_count:{count}")
  257. if hit != DISPATCHER_COVER_EXACT:
  258. failures.append(f"dispatcher_cover_hit:{hit}")
  259. if isinstance(ids, list) and len(ids) not in (0, DISPATCHER_COVER_EXACT):
  260. # Some receipts list all 10 ids; empty list with hit_count=10 is still checked above.
  261. if len(ids) != DISPATCHER_COVER_EXACT:
  262. failures.append(f"dispatcher_cover_ids:{len(ids)}")
  263. if dispatcher.get("cover_required") is not True:
  264. failures.append("dispatcher_cover_not_required")
  265. manifest = doc.get("target_manifest")
  266. if isinstance(manifest, dict):
  267. expected = manifest.get("expected")
  268. if isinstance(expected, dict) and len(expected) != REQUIRED_FORMAL_TARGET_COUNT:
  269. failures.append(f"formal_manifest_expected_count:{len(expected)}")
  270. m_fail = manifest.get("failures")
  271. if m_fail not in (None, [], ()):
  272. failures.append("formal_manifest_failures_not_empty")
  273. return failures
  274. def validate_release_identity(
  275. identity: Any,
  276. *,
  277. zip_head: str | None = None,
  278. require_final: bool = True,
  279. ) -> list[str]:
  280. failures: list[str] = []
  281. if not isinstance(identity, dict) or not identity:
  282. return ["release_identity_not_object_or_empty"]
  283. schema = str(identity.get("schema") or "")
  284. if schema != "prod2u-release-set-identity-v1":
  285. failures.append(f"release_identity_schema:{schema or 'empty'}")
  286. if not str(identity.get("algorithm_version") or "").strip():
  287. failures.append("release_identity_missing_algorithm_version")
  288. stage = str(identity.get("package_stage") or "")
  289. if require_final and stage != "final-review":
  290. failures.append(f"release_identity_stage_not_final:{stage or 'empty'}")
  291. required = (
  292. "release_set_id",
  293. "base_dev_commit",
  294. "delivery_commit",
  295. "td_bound_commit",
  296. "artifact_source_commit",
  297. "bitstream_sha256",
  298. "td_artifact_run_id",
  299. "td_receipt_sha256",
  300. "production_binding",
  301. "hardware_validation",
  302. )
  303. for key in required:
  304. value = identity.get(key)
  305. if value is None or str(value).strip() in {"", "null", "None"}:
  306. failures.append(f"release_identity_missing:{key}")
  307. tip = str(
  308. identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
  309. ).strip()
  310. if require_final and not tip:
  311. failures.append("release_identity_missing_matrix_tip")
  312. run = str(
  313. identity.get("software_verification_run_id")
  314. or identity.get("verification_run_id")
  315. or ""
  316. ).strip()
  317. if require_final and not run:
  318. failures.append("release_identity_missing_matrix_run")
  319. if zip_head:
  320. delivery = str(identity.get("delivery_commit") or "")
  321. if delivery and zip_head and delivery != zip_head:
  322. failures.append("release_identity_delivery_ne_zip_head")
  323. lut = identity.get("lut")
  324. mslice = identity.get("mslice")
  325. if require_final:
  326. if mslice is None:
  327. failures.append("release_identity_mslice_missing")
  328. if lut is None:
  329. failures.append("release_identity_lut_missing")
  330. if lut is not None and mslice is not None and lut == mslice and lut not in (0, 0.0, "0"):
  331. failures.append("release_identity_mslice_equals_lut")
  332. blob = json.dumps(identity, sort_keys=True)
  333. for token in FORBIDDEN_IDENTITY_TOKENS:
  334. if token in blob:
  335. failures.append(f"release_identity_forbidden_token:{token}")
  336. hw = str(identity.get("hardware_validation") or "").casefold().replace(" ", "_")
  337. if hw not in {"not_run", "not-run"}:
  338. failures.append(f"hardware_validation_not_not_run:{identity.get('hardware_validation')}")
  339. return failures
  340. MSE_RUN_ID_RE = re.compile(r"mse-r\d{1,2}-20\d{6}T\d{6}Z", re.I)
  341. ROUND_AS_CURRENT_RE = re.compile(
  342. r"(?i)(?:当前|current|活动|基线).{0,80}Round-1[0-2]"
  343. r"|Round-1[0-2].{0,80}(?:当前|current|release closure|基线|dual package)"
  344. )
  345. PACKAGE_AUTHORITY_POINTERS = (
  346. "meta/release-set-identity.json",
  347. "meta/verification-to-delivery-closure.json",
  348. "evidence/matrix/verification-matrix-final.json",
  349. )
  350. STABLE_TD_MARKERS = (
  351. "c9e7e2b9",
  352. "f3242a47",
  353. "4320",
  354. "1089",
  355. "2178",
  356. )
  357. def stale_current_doc_failures(text: str) -> list[str]:
  358. """Fail when superseded matrix/run/round titles are presented as current."""
  359. failures: list[str] = []
  360. negate = re.compile(
  361. r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|"
  362. r"将被|取代|not\s+current|stale|不得|勿"
  363. )
  364. for token in STALE_CURRENT_TOKENS:
  365. for line in text.splitlines():
  366. if token not in line:
  367. continue
  368. if negate.search(line):
  369. continue
  370. failures.append(f"stale_current_doc:{token}")
  371. break
  372. for line in text.splitlines():
  373. if MSE_RUN_ID_RE.search(line) and not negate.search(line):
  374. failures.append("stale_current_doc:mse_run_id_as_current")
  375. break
  376. for line in text.splitlines():
  377. if ROUND_AS_CURRENT_RE.search(line) and not negate.search(line):
  378. failures.append("stale_current_doc:round_title_as_current")
  379. break
  380. return failures