|
|
@@ -0,0 +1,387 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Select current matrix / Formal evidence by explicit tip + run ID.
|
|
|
+
|
|
|
+Never use "last same basename", hardcoded R7/R8 paths, or directory-scan order.
|
|
|
+Historical receipts stay under receipts/historical/ or receipts/mse-rN-matrix/
|
|
|
+and are not current authority unless that run_id is the explicit selector.
|
|
|
+"""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import hashlib
|
|
|
+import json
|
|
|
+import os
|
|
|
+import re
|
|
|
+from pathlib import Path
|
|
|
+from typing import Any
|
|
|
+
|
|
|
+
|
|
|
+ROOT = Path(__file__).resolve().parents[1]
|
|
|
+
|
|
|
+REQUIRED_MATRIX_LANES = (
|
|
|
+ "python",
|
|
|
+ "board_viewer",
|
|
|
+ "icarus",
|
|
|
+ "verilator",
|
|
|
+ "cocotb",
|
|
|
+ "formal",
|
|
|
+)
|
|
|
+REQUIRED_FORMAL_TARGET_COUNT = 23
|
|
|
+DISPATCHER_TARGET = "door_rate_quantum_dispatcher"
|
|
|
+DISPATCHER_COVER_EXACT = 10
|
|
|
+CANONICAL_MATRIX_REL = "evidence/matrix/verification-matrix-final.json"
|
|
|
+CANONICAL_FORMAL_REL = "evidence/formal/formal-receipt.json"
|
|
|
+STALE_CURRENT_TOKENS = (
|
|
|
+ "mse-r7-20260812T132652Z",
|
|
|
+ "21ed755ad2ddb6689bca88a9a037b391372a060e",
|
|
|
+ "3177c2f01070b32460dee826e41b685f482fea26",
|
|
|
+)
|
|
|
+FORBIDDEN_IDENTITY_TOKENS = ("PENDING", "pending_package", "hook_ready")
|
|
|
+
|
|
|
+
|
|
|
+class CurrentEvidenceError(RuntimeError):
|
|
|
+ """Fail-closed current-evidence selection or validation error."""
|
|
|
+
|
|
|
+
|
|
|
+def _sha256_file(path: Path) -> str:
|
|
|
+ digest = hashlib.sha256()
|
|
|
+ with path.open("rb") as handle:
|
|
|
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
|
+ digest.update(chunk)
|
|
|
+ return digest.hexdigest()
|
|
|
+
|
|
|
+
|
|
|
+def commits_match(left: str | None, right: str | None) -> bool:
|
|
|
+ a = str(left or "").strip().casefold()
|
|
|
+ b = str(right or "").strip().casefold()
|
|
|
+ if not a or not b:
|
|
|
+ return False
|
|
|
+ n = min(len(a), len(b))
|
|
|
+ if n < 7:
|
|
|
+ return False
|
|
|
+ return a[:n] == b[:n]
|
|
|
+
|
|
|
+
|
|
|
+def matrix_family_dir(run_id: str) -> str:
|
|
|
+ """mse-r10-20260813T010203Z → mse-r10-matrix (explicit, not a glob)."""
|
|
|
+ text = str(run_id or "").strip()
|
|
|
+ parts = text.split("-")
|
|
|
+ if len(parts) < 3 or parts[0] != "mse" or not parts[1].startswith("r"):
|
|
|
+ raise CurrentEvidenceError(f"bad_matrix_run_id:{run_id}")
|
|
|
+ return f"{parts[0]}-{parts[1]}-matrix"
|
|
|
+
|
|
|
+
|
|
|
+def current_matrix_path(
|
|
|
+ repo: Path,
|
|
|
+ *,
|
|
|
+ run_id: str,
|
|
|
+ override: str | None = None,
|
|
|
+) -> Path:
|
|
|
+ explicit = (override or os.environ.get("PRODU2_CURRENT_MATRIX_PATH", "")).strip()
|
|
|
+ if explicit:
|
|
|
+ path = Path(explicit)
|
|
|
+ if not path.is_absolute():
|
|
|
+ path = repo / path
|
|
|
+ return path
|
|
|
+ family = matrix_family_dir(run_id)
|
|
|
+ return repo / "receipts" / family / run_id / "unified-matrix-report.json"
|
|
|
+
|
|
|
+
|
|
|
+def current_formal_path(
|
|
|
+ repo: Path,
|
|
|
+ *,
|
|
|
+ run_id: str,
|
|
|
+ override: str | None = None,
|
|
|
+) -> Path:
|
|
|
+ explicit = (override or os.environ.get("PRODU2_CURRENT_FORMAL_PATH", "")).strip()
|
|
|
+ if explicit:
|
|
|
+ path = Path(explicit)
|
|
|
+ if not path.is_absolute():
|
|
|
+ path = repo / path
|
|
|
+ return path
|
|
|
+ family = matrix_family_dir(run_id)
|
|
|
+ return repo / "receipts" / family / run_id / "lanes" / "formal-receipt.json"
|
|
|
+
|
|
|
+
|
|
|
+def select_current_matrix(
|
|
|
+ repo: Path,
|
|
|
+ *,
|
|
|
+ verification_tip: str,
|
|
|
+ run_id: str,
|
|
|
+) -> Path:
|
|
|
+ path = current_matrix_path(repo, run_id=run_id)
|
|
|
+ if not path.is_file():
|
|
|
+ raise CurrentEvidenceError(f"missing_current_matrix:{path}")
|
|
|
+ doc = json.loads(path.read_text(encoding="utf-8"))
|
|
|
+ failures = validate_matrix_report(
|
|
|
+ doc, verification_tip=verification_tip, run_id=run_id
|
|
|
+ )
|
|
|
+ if failures:
|
|
|
+ raise CurrentEvidenceError("current_matrix_invalid:" + ",".join(failures[:12]))
|
|
|
+ return path
|
|
|
+
|
|
|
+
|
|
|
+def select_current_formal(
|
|
|
+ repo: Path,
|
|
|
+ *,
|
|
|
+ verification_tip: str,
|
|
|
+ run_id: str,
|
|
|
+) -> Path:
|
|
|
+ path = current_formal_path(repo, run_id=run_id)
|
|
|
+ if not path.is_file():
|
|
|
+ raise CurrentEvidenceError(f"missing_current_formal:{path}")
|
|
|
+ doc = json.loads(path.read_text(encoding="utf-8"))
|
|
|
+ failures = validate_formal_receipt(doc, verification_tip=verification_tip)
|
|
|
+ if failures:
|
|
|
+ raise CurrentEvidenceError("current_formal_invalid:" + ",".join(failures[:12]))
|
|
|
+ return path
|
|
|
+
|
|
|
+
|
|
|
+def stage_current_evidence(
|
|
|
+ *,
|
|
|
+ repo: Path,
|
|
|
+ staging_root: Path,
|
|
|
+ verification_tip: str,
|
|
|
+ run_id: str,
|
|
|
+) -> dict[str, Path]:
|
|
|
+ """Copy the explicitly selected current receipts onto canonical evidence/ paths."""
|
|
|
+ matrix_src = select_current_matrix(
|
|
|
+ repo, verification_tip=verification_tip, run_id=run_id
|
|
|
+ )
|
|
|
+ formal_src = select_current_formal(
|
|
|
+ repo, verification_tip=verification_tip, run_id=run_id
|
|
|
+ )
|
|
|
+ matrix_dest = staging_root / Path(*CANONICAL_MATRIX_REL.split("/"))
|
|
|
+ formal_dest = staging_root / Path(*CANONICAL_FORMAL_REL.split("/"))
|
|
|
+ matrix_dest.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ formal_dest.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ matrix_dest.write_bytes(matrix_src.read_bytes())
|
|
|
+ formal_dest.write_bytes(formal_src.read_bytes())
|
|
|
+ return {"matrix": matrix_dest, "formal": formal_dest}
|
|
|
+
|
|
|
+
|
|
|
+def validate_matrix_report(
|
|
|
+ doc: Any,
|
|
|
+ *,
|
|
|
+ verification_tip: str | None = None,
|
|
|
+ run_id: str | None = None,
|
|
|
+) -> list[str]:
|
|
|
+ failures: list[str] = []
|
|
|
+ if not isinstance(doc, dict) or not doc:
|
|
|
+ return ["matrix_not_object_or_empty"]
|
|
|
+ schema = str(doc.get("schema") or "")
|
|
|
+ if "verification-matrix" not in schema.casefold():
|
|
|
+ failures.append(f"matrix_schema_unexpected:{schema or 'empty'}")
|
|
|
+ status = str(doc.get("status") or "").casefold()
|
|
|
+ if status != "pass":
|
|
|
+ failures.append(f"matrix_status_not_pass:{status or 'empty'}")
|
|
|
+ failures_field = doc.get("failures")
|
|
|
+ if failures_field is None:
|
|
|
+ failures.append("matrix_failures_missing")
|
|
|
+ elif failures_field not in ([], ()):
|
|
|
+ failures.append("matrix_failures_not_empty")
|
|
|
+ if verification_tip:
|
|
|
+ commit = str(doc.get("commit_full") or doc.get("commit") or "")
|
|
|
+ if not commits_match(commit, verification_tip):
|
|
|
+ failures.append("matrix_tip_mismatch")
|
|
|
+ lanes = doc.get("lanes")
|
|
|
+ if not isinstance(lanes, dict):
|
|
|
+ failures.append("matrix_lanes_missing")
|
|
|
+ lanes = {}
|
|
|
+ for name in REQUIRED_MATRIX_LANES:
|
|
|
+ lane = lanes.get(name)
|
|
|
+ if not isinstance(lane, dict):
|
|
|
+ failures.append(f"matrix_lane_missing:{name}")
|
|
|
+ continue
|
|
|
+ lane_status = str(lane.get("status") or "").casefold()
|
|
|
+ if lane_status != "pass":
|
|
|
+ failures.append(f"matrix_lane_not_pass:{name}:{lane_status or 'empty'}")
|
|
|
+ if verification_tip:
|
|
|
+ lane_commit = str(lane.get("commit_full") or lane.get("commit") or "")
|
|
|
+ if lane_commit and not commits_match(lane_commit, verification_tip):
|
|
|
+ failures.append(f"matrix_lane_tip_mismatch:{name}")
|
|
|
+ if name == "board_viewer":
|
|
|
+ mode = str(lane.get("mode") or lane.get("selection", {}).get("mode") or "")
|
|
|
+ if mode and mode != "detached_derived":
|
|
|
+ failures.append(f"board_viewer_mode_not_detached_derived:{mode}")
|
|
|
+ if run_id:
|
|
|
+ # User-level run id lives in the receipts path; JSON may use a hex verification_run_id.
|
|
|
+ json_run = str(doc.get("software_verification_run_id") or doc.get("run_id") or "")
|
|
|
+ if json_run and json_run != run_id and run_id not in json_run:
|
|
|
+ # Hex lane ids are expected; only fail when a conflicting mse-r* id is present.
|
|
|
+ if re.match(r"^mse-r\d+-", json_run) and json_run != run_id:
|
|
|
+ failures.append(f"matrix_run_id_mismatch:{json_run}")
|
|
|
+ return failures
|
|
|
+
|
|
|
+
|
|
|
+def validate_formal_receipt(
|
|
|
+ doc: Any,
|
|
|
+ *,
|
|
|
+ verification_tip: str | None = None,
|
|
|
+) -> list[str]:
|
|
|
+ failures: list[str] = []
|
|
|
+ if not isinstance(doc, dict) or not doc:
|
|
|
+ return ["formal_not_object_or_empty"]
|
|
|
+ schema = str(doc.get("schema") or "")
|
|
|
+ if schema != "prod2u-p4-normal-v3-formal-receipt-v1":
|
|
|
+ failures.append(f"formal_schema_unexpected:{schema or 'empty'}")
|
|
|
+ status = str(doc.get("status") or "").casefold()
|
|
|
+ if status != "pass":
|
|
|
+ failures.append(f"formal_status_not_pass:{status or 'empty'}")
|
|
|
+ if verification_tip:
|
|
|
+ commit = str(doc.get("commit_full") or doc.get("commit") or "")
|
|
|
+ if commit and not commits_match(commit, verification_tip):
|
|
|
+ failures.append("formal_tip_mismatch")
|
|
|
+ targets = doc.get("targets")
|
|
|
+ if not isinstance(targets, list):
|
|
|
+ failures.append("formal_targets_missing")
|
|
|
+ return failures
|
|
|
+ if len(targets) != REQUIRED_FORMAL_TARGET_COUNT:
|
|
|
+ failures.append(f"formal_target_count:{len(targets)}")
|
|
|
+ names: list[str] = []
|
|
|
+ dispatcher = None
|
|
|
+ for target in targets:
|
|
|
+ if not isinstance(target, dict):
|
|
|
+ failures.append("formal_target_not_object")
|
|
|
+ continue
|
|
|
+ name = str(target.get("name") or "")
|
|
|
+ names.append(name)
|
|
|
+ t_status = str(target.get("status") or "").casefold()
|
|
|
+ if t_status != "pass":
|
|
|
+ failures.append(f"formal_target_not_pass:{name or '?'}:{t_status or 'empty'}")
|
|
|
+ rc = target.get("returncode")
|
|
|
+ if rc not in (0, "0"):
|
|
|
+ failures.append(f"formal_target_rc:{name}:{rc}")
|
|
|
+ tasks = target.get("task_results")
|
|
|
+ if isinstance(tasks, list):
|
|
|
+ if not tasks:
|
|
|
+ failures.append(f"formal_target_tasks_empty:{name}")
|
|
|
+ for task in tasks:
|
|
|
+ if not isinstance(task, dict):
|
|
|
+ failures.append(f"formal_task_not_object:{name}")
|
|
|
+ continue
|
|
|
+ raw = str(task.get("status") or "").casefold()
|
|
|
+ if raw not in {"pass", "passed"}:
|
|
|
+ failures.append(
|
|
|
+ f"formal_task_not_pass:{name}:{task.get('name')}:{raw or 'empty'}"
|
|
|
+ )
|
|
|
+ task_rc = task.get("returncode")
|
|
|
+ if task_rc not in (0, "0"):
|
|
|
+ failures.append(
|
|
|
+ f"formal_task_rc:{name}:{task.get('name')}:{task_rc}"
|
|
|
+ )
|
|
|
+ if name == DISPATCHER_TARGET:
|
|
|
+ dispatcher = target
|
|
|
+ if len(set(names)) != len(names):
|
|
|
+ failures.append("formal_duplicate_target_names")
|
|
|
+ if dispatcher is None:
|
|
|
+ failures.append("formal_dispatcher_missing")
|
|
|
+ else:
|
|
|
+ hit = dispatcher.get("cover_hit_count")
|
|
|
+ count = dispatcher.get("cover_count")
|
|
|
+ ids = dispatcher.get("cover_hit_ids") or []
|
|
|
+ if count != DISPATCHER_COVER_EXACT:
|
|
|
+ failures.append(f"dispatcher_cover_count:{count}")
|
|
|
+ if hit != DISPATCHER_COVER_EXACT:
|
|
|
+ failures.append(f"dispatcher_cover_hit:{hit}")
|
|
|
+ if isinstance(ids, list) and len(ids) not in (0, DISPATCHER_COVER_EXACT):
|
|
|
+ # Some receipts list all 10 ids; empty list with hit_count=10 is still checked above.
|
|
|
+ if len(ids) != DISPATCHER_COVER_EXACT:
|
|
|
+ failures.append(f"dispatcher_cover_ids:{len(ids)}")
|
|
|
+ if dispatcher.get("cover_required") is not True:
|
|
|
+ failures.append("dispatcher_cover_not_required")
|
|
|
+ manifest = doc.get("target_manifest")
|
|
|
+ if isinstance(manifest, dict):
|
|
|
+ expected = manifest.get("expected")
|
|
|
+ if isinstance(expected, dict) and len(expected) != REQUIRED_FORMAL_TARGET_COUNT:
|
|
|
+ failures.append(f"formal_manifest_expected_count:{len(expected)}")
|
|
|
+ m_fail = manifest.get("failures")
|
|
|
+ if m_fail not in (None, [], ()):
|
|
|
+ failures.append("formal_manifest_failures_not_empty")
|
|
|
+ return failures
|
|
|
+
|
|
|
+
|
|
|
+def validate_release_identity(
|
|
|
+ identity: Any,
|
|
|
+ *,
|
|
|
+ zip_head: str | None = None,
|
|
|
+ require_final: bool = True,
|
|
|
+) -> list[str]:
|
|
|
+ failures: list[str] = []
|
|
|
+ if not isinstance(identity, dict) or not identity:
|
|
|
+ return ["release_identity_not_object_or_empty"]
|
|
|
+ schema = str(identity.get("schema") or "")
|
|
|
+ if schema != "prod2u-release-set-identity-v1":
|
|
|
+ failures.append(f"release_identity_schema:{schema or 'empty'}")
|
|
|
+ if not str(identity.get("algorithm_version") or "").strip():
|
|
|
+ failures.append("release_identity_missing_algorithm_version")
|
|
|
+ stage = str(identity.get("package_stage") or "")
|
|
|
+ if require_final and stage != "final-review":
|
|
|
+ failures.append(f"release_identity_stage_not_final:{stage or 'empty'}")
|
|
|
+ required = (
|
|
|
+ "release_set_id",
|
|
|
+ "base_dev_commit",
|
|
|
+ "delivery_commit",
|
|
|
+ "td_bound_commit",
|
|
|
+ "artifact_source_commit",
|
|
|
+ "bitstream_sha256",
|
|
|
+ "td_artifact_run_id",
|
|
|
+ "td_receipt_sha256",
|
|
|
+ "production_binding",
|
|
|
+ "hardware_validation",
|
|
|
+ )
|
|
|
+ for key in required:
|
|
|
+ value = identity.get(key)
|
|
|
+ if value is None or str(value).strip() in {"", "null", "None"}:
|
|
|
+ failures.append(f"release_identity_missing:{key}")
|
|
|
+ tip = str(
|
|
|
+ identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
|
|
|
+ ).strip()
|
|
|
+ if require_final and not tip:
|
|
|
+ failures.append("release_identity_missing_matrix_tip")
|
|
|
+ run = str(
|
|
|
+ identity.get("software_verification_run_id")
|
|
|
+ or identity.get("verification_run_id")
|
|
|
+ or ""
|
|
|
+ ).strip()
|
|
|
+ if require_final and not run:
|
|
|
+ failures.append("release_identity_missing_matrix_run")
|
|
|
+ if zip_head:
|
|
|
+ delivery = str(identity.get("delivery_commit") or "")
|
|
|
+ if delivery and zip_head and delivery != zip_head:
|
|
|
+ failures.append("release_identity_delivery_ne_zip_head")
|
|
|
+ lut = identity.get("lut")
|
|
|
+ mslice = identity.get("mslice")
|
|
|
+ if require_final:
|
|
|
+ if mslice is None:
|
|
|
+ failures.append("release_identity_mslice_missing")
|
|
|
+ if lut is None:
|
|
|
+ failures.append("release_identity_lut_missing")
|
|
|
+ if lut is not None and mslice is not None and lut == mslice and lut not in (0, 0.0, "0"):
|
|
|
+ failures.append("release_identity_mslice_equals_lut")
|
|
|
+ blob = json.dumps(identity, sort_keys=True)
|
|
|
+ for token in FORBIDDEN_IDENTITY_TOKENS:
|
|
|
+ if token in blob:
|
|
|
+ failures.append(f"release_identity_forbidden_token:{token}")
|
|
|
+ hw = str(identity.get("hardware_validation") or "").casefold().replace(" ", "_")
|
|
|
+ if hw not in {"not_run", "not-run"}:
|
|
|
+ failures.append(f"hardware_validation_not_not_run:{identity.get('hardware_validation')}")
|
|
|
+ return failures
|
|
|
+
|
|
|
+
|
|
|
+def stale_current_doc_failures(text: str) -> list[str]:
|
|
|
+ """Fail when R7/R8 ids are presented as current without historical negation."""
|
|
|
+ failures: list[str] = []
|
|
|
+ negate = re.compile(
|
|
|
+ r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|"
|
|
|
+ r"将被|取代|not\s+current|stale"
|
|
|
+ )
|
|
|
+ for token in STALE_CURRENT_TOKENS:
|
|
|
+ for line in text.splitlines():
|
|
|
+ if token not in line:
|
|
|
+ continue
|
|
|
+ if negate.search(line):
|
|
|
+ continue
|
|
|
+ failures.append(f"stale_current_doc:{token}")
|
|
|
+ break
|
|
|
+ return failures
|