prod2u_p4_validate.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #!/usr/bin/env python3
  2. """Offline validator for the Prod2U P4 evidence, campaign, and final gate JSON."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import math
  7. import re
  8. import sys
  9. from pathlib import Path
  10. from typing import Any, Mapping, Sequence
  11. SCHEMAS = {
  12. "evidence": "prod2u-p4-evidence-v2",
  13. "campaign": "prod2u-p4-campaign-v2",
  14. "final_gate": "prod2u-p4-final-gate-v2",
  15. }
  16. FAN_STATUSES = {"detected", "absent", "intermittent"}
  17. LAYER_STATUSES = {"pass", "fail", "blocked", "not_run"}
  18. SPEARMAN_MIN = 0.60
  19. ROUND_COUNT = 10
  20. FAN_SETTINGS = (0, 20, 40, 60, 80, 100)
  21. TREND_SETTINGS = (20, 40, 60, 80, 100)
  22. LOW_SETTINGS = (20, 40)
  23. HIGH_SETTINGS = (80, 100)
  24. SAMPLES_PER_SETTING = 5
  25. SETTLE_WINDOWS_PER_SETTING = 2
  26. WINDOWS_PER_ROUND = len(FAN_SETTINGS) * (SAMPLES_PER_SETTING + SETTLE_WINDOWS_PER_SETTING)
  27. REQUIRED_DYNAMIC_LAYERS = (
  28. "program_sram",
  29. "fresh_ready",
  30. "host_ack",
  31. "pwm_state",
  32. "fan3_tach_trend",
  33. "timeout_fallback",
  34. "disable",
  35. "ptc_command_path",
  36. )
  37. REQUIRED_STATIC_LAYERS = (
  38. "source",
  39. "protocol",
  40. "rtl",
  41. "formal",
  42. "td_normal",
  43. "td_trace",
  44. "package",
  45. )
  46. STATIC_LAYER_ARTIFACTS = {
  47. "source": ("normal_source_manifest", "trace_source_manifest"),
  48. "protocol": ("protocol_junit",),
  49. "rtl": ("rtl_sim_receipt",),
  50. "formal": ("formal_receipt",),
  51. "td_normal": ("normal_td_receipt",),
  52. "td_trace": ("trace_td_receipt",),
  53. "package": ("package_manifest", "package_inventory", "static_receipt"),
  54. }
  55. SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
  56. IDENTITY_FIELDS = ("dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256")
  57. BOUND_ARTIFACTS = (
  58. "programmer_receipt",
  59. "pre_program_raw",
  60. "combined_rx_raw",
  61. "raw_transcript",
  62. "td_receipt",
  63. "source_manifest",
  64. "package_manifest",
  65. "package_inventory",
  66. )
  67. EVIDENCE_REQUIRED = (
  68. "schema",
  69. "evidence_id",
  70. "campaign_id",
  71. "campaign_identity",
  72. "round",
  73. "identity",
  74. "bmc",
  75. "layers",
  76. "fan",
  77. "windows",
  78. "raw_samples",
  79. "correlation",
  80. "rpm",
  81. "ptc",
  82. "evidence_binding",
  83. )
  84. FINAL_GATE_REQUIRED = (
  85. "schema",
  86. "status",
  87. "campaign_id",
  88. "campaign_identity",
  89. "bmc",
  90. "qualification",
  91. "layers",
  92. "round_count",
  93. "evidence_bindings",
  94. "failures",
  95. )
  96. def _mapping(value: Any) -> Mapping[str, Any]:
  97. return value if isinstance(value, Mapping) else {}
  98. def _number(value: Any) -> float | None:
  99. if isinstance(value, bool) or not isinstance(value, (int, float)):
  100. return None
  101. result = float(value)
  102. return result if math.isfinite(result) else None
  103. def _rank(values: Sequence[float]) -> list[float]:
  104. ordered = sorted((value, index) for index, value in enumerate(values))
  105. ranks = [0.0] * len(values)
  106. position = 0
  107. while position < len(ordered):
  108. end = position + 1
  109. while end < len(ordered) and ordered[end][0] == ordered[position][0]:
  110. end += 1
  111. average = (position + 1 + end) / 2.0
  112. for _, index in ordered[position:end]:
  113. ranks[index] = average
  114. position = end
  115. return ranks
  116. def spearman_rho(x_values: Sequence[float], y_values: Sequence[float]) -> float | None:
  117. """Return Spearman rank correlation without scipy or another dependency."""
  118. if len(x_values) != len(y_values) or len(x_values) < 2:
  119. return None
  120. x_rank = _rank(x_values)
  121. y_rank = _rank(y_values)
  122. x_mean = sum(x_rank) / len(x_rank)
  123. y_mean = sum(y_rank) / len(y_rank)
  124. numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_rank, y_rank))
  125. x_denominator = math.sqrt(sum((x - x_mean) ** 2 for x in x_rank))
  126. y_denominator = math.sqrt(sum((y - y_mean) ** 2 for y in y_rank))
  127. if x_denominator == 0 or y_denominator == 0:
  128. return None
  129. return numerator / (x_denominator * y_denominator)
  130. def _validate_layers(layers: Any, round_number: int | None = None) -> list[str]:
  131. failures: list[str] = []
  132. payload = _mapping(layers)
  133. required = _mapping(payload.get("required"))
  134. optional = _mapping(payload.get("optional"))
  135. prefix = f"{round_number}:" if round_number is not None else ""
  136. if not required:
  137. failures.append(f"required_layers_missing:{prefix[:-1] if prefix else 'campaign'}")
  138. for name in REQUIRED_DYNAMIC_LAYERS:
  139. if name not in required:
  140. failures.append(f"required_layer_missing:{prefix}{name}" if prefix else f"required_layer_missing:campaign:{name}")
  141. for name, status in required.items():
  142. if status not in LAYER_STATUSES:
  143. failures.append(f"invalid_layer_status:{prefix}{name}")
  144. elif status != "pass":
  145. failures.append(f"required_layer_not_pass:{prefix}{name}")
  146. for name, status in optional.items():
  147. if status not in LAYER_STATUSES:
  148. failures.append(f"invalid_optional_layer_status:{prefix}{name}")
  149. return failures
  150. def _validate_windows(windows: Any, round_number: int) -> list[str]:
  151. failures: list[str] = []
  152. if not isinstance(windows, list) or not windows:
  153. return [f"windows_missing:{round_number}"]
  154. if len(windows) != WINDOWS_PER_ROUND:
  155. failures.append(f"windows_count:{round_number}:{len(windows)}")
  156. previous_end: float | None = None
  157. previous_index: int | None = None
  158. previous_snapshot_seq: int | None = None
  159. for expected_index, item in enumerate(windows):
  160. window = _mapping(item)
  161. index = window.get("index", window.get("window_index"))
  162. start = _number(window.get("start_s"))
  163. end = _number(window.get("end_s"))
  164. continuous = window.get("continuous")
  165. snapshot_seq = window.get("snapshot_seq")
  166. overflow_mask = window.get("overflow_mask")
  167. if not isinstance(index, int) or isinstance(index, bool) or start is None or end is None or end <= start:
  168. failures.append(f"invalid_window:{round_number}")
  169. continue
  170. if continuous is not True or (previous_end is not None and not math.isclose(start, previous_end, abs_tol=1e-9)):
  171. failures.append(f"window_not_continuous:{round_number}")
  172. if index != expected_index or (previous_index is not None and index != previous_index + 1):
  173. failures.append(f"window_index_not_contiguous:{round_number}")
  174. if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or not 0 <= snapshot_seq <= 0xFFFFFFFF:
  175. failures.append(f"window_snapshot_seq_invalid:{round_number}:{expected_index}")
  176. elif previous_snapshot_seq is not None and snapshot_seq != ((previous_snapshot_seq + 1) & 0xFFFFFFFF):
  177. failures.append(f"window_snapshot_seq_not_contiguous:{round_number}")
  178. if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
  179. failures.append(f"window_overflow_mask_invalid:{round_number}:{expected_index}")
  180. previous_end = end
  181. previous_index = index
  182. if isinstance(snapshot_seq, int) and not isinstance(snapshot_seq, bool):
  183. previous_snapshot_seq = snapshot_seq
  184. return list(dict.fromkeys(failures))
  185. def _validate_correlation(correlation: Any, round_number: int) -> list[str]:
  186. failures: list[str] = []
  187. payload = _mapping(correlation)
  188. samples = payload.get("samples")
  189. if not isinstance(samples, list) or len(samples) != len(FAN_SETTINGS):
  190. failures.append(f"trend_samples_must_cover_all_settings:{round_number}")
  191. samples = []
  192. by_setting: dict[float, float] = {}
  193. for sample in samples:
  194. row = _mapping(sample)
  195. x = _number(row.get("fan_setting_percent", row.get("fan_percent")))
  196. y = _number(row.get("rpm"))
  197. if x is None or y is None:
  198. failures.append(f"invalid_correlation_sample:{round_number}")
  199. continue
  200. if x in by_setting:
  201. failures.append(f"duplicate_correlation_setting:{round_number}:{int(x)}")
  202. by_setting[x] = y
  203. if tuple(by_setting) != FAN_SETTINGS:
  204. failures.append(f"trend_settings_must_be_0_20_40_60_80_100:{round_number}")
  205. x_values = [float(setting) for setting in TREND_SETTINGS if float(setting) in by_setting]
  206. y_values = [by_setting[setting] for setting in x_values]
  207. computed = spearman_rho(x_values, y_values) if len(x_values) == len(TREND_SETTINGS) else None
  208. declared = _number(payload.get("spearman_rho"))
  209. if computed is None:
  210. failures.append(f"spearman_not_computable:{round_number}")
  211. elif declared is None:
  212. failures.append(f"spearman_declared_missing:{round_number}")
  213. elif not math.isclose(declared, computed, abs_tol=1e-6):
  214. failures.append(f"spearman_declared_mismatch:{round_number}")
  215. if computed is None or computed < SPEARMAN_MIN:
  216. failures.append(f"spearman_below_threshold:{round_number}")
  217. low = _number(payload.get("low_mean_rpm"))
  218. high = _number(payload.get("high_mean_rpm"))
  219. expected_low = (
  220. sum(by_setting[float(setting)] for setting in LOW_SETTINGS) / len(LOW_SETTINGS)
  221. if all(float(setting) in by_setting for setting in LOW_SETTINGS)
  222. else None
  223. )
  224. expected_high = (
  225. sum(by_setting[float(setting)] for setting in HIGH_SETTINGS) / len(HIGH_SETTINGS)
  226. if all(float(setting) in by_setting for setting in HIGH_SETTINGS)
  227. else None
  228. )
  229. if low is None or expected_low is None or not math.isclose(low, expected_low, abs_tol=1e-9):
  230. failures.append(f"low_setting_mean_mismatch:{round_number}")
  231. if high is None or expected_high is None or not math.isclose(high, expected_high, abs_tol=1e-9):
  232. failures.append(f"high_setting_mean_mismatch:{round_number}")
  233. significant = payload.get("high_significantly_higher") is True
  234. if expected_low is None or expected_high is None or not significant or expected_high < expected_low + max(100.0, expected_low * 0.10):
  235. failures.append(f"high_setting_not_significantly_higher:{round_number}")
  236. return failures
  237. def _validate_raw_samples(raw_samples: Any, fan3: Mapping[str, Any], round_number: int) -> list[str]:
  238. failures: list[str] = []
  239. expected_total = len(FAN_SETTINGS) * SAMPLES_PER_SETTING
  240. if not isinstance(raw_samples, list):
  241. return [f"raw_samples_missing:{round_number}"]
  242. if len(raw_samples) != expected_total:
  243. failures.append(f"raw_samples_count:{round_number}:{len(raw_samples)}")
  244. rows_by_setting: dict[int, list[Mapping[str, Any]]] = {setting: [] for setting in FAN_SETTINGS}
  245. valid_rows: list[Mapping[str, Any]] = []
  246. for row_index, item in enumerate(raw_samples):
  247. row = _mapping(item)
  248. setting = row.get("fan_setting_percent")
  249. if not isinstance(setting, int) or isinstance(setting, bool) or setting not in rows_by_setting:
  250. failures.append(f"raw_sample_setting_invalid:{round_number}:{row_index}")
  251. else:
  252. rows_by_setting[setting].append(row)
  253. snapshot_seq = row.get("snapshot_seq")
  254. if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or snapshot_seq < 0:
  255. failures.append(f"snapshot_seq_invalid:{round_number}:{row_index}")
  256. overflow_mask = row.get("overflow_mask")
  257. if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
  258. failures.append(f"overflow_mask_invalid:{round_number}:{row_index}")
  259. for signal in ("FG5", "FG6"):
  260. channel = _mapping(row.get(signal))
  261. edges = channel.get("window_edges")
  262. if not isinstance(edges, int) or isinstance(edges, bool) or edges < 0:
  263. failures.append(f"window_edges_invalid:{round_number}:{row_index}:{signal}")
  264. valid_rows.append(row)
  265. for setting in FAN_SETTINGS:
  266. count = len(rows_by_setting[setting])
  267. if count != SAMPLES_PER_SETTING:
  268. failures.append(f"raw_samples_setting_count:{round_number}:{setting}:{count}")
  269. for setting, setting_rows in rows_by_setting.items():
  270. setting_sequences = [
  271. row.get("snapshot_seq")
  272. for row in setting_rows
  273. if isinstance(row.get("snapshot_seq"), int) and not isinstance(row.get("snapshot_seq"), bool)
  274. ]
  275. if len(setting_sequences) == SAMPLES_PER_SETTING:
  276. for previous, current in zip(setting_sequences, setting_sequences[1:]):
  277. if current != ((previous + 1) & 0xFFFFFFFF):
  278. failures.append(f"snapshot_seq_not_contiguous:{round_number}")
  279. break
  280. computed_statuses: dict[str, str] = {}
  281. for signal, bit_index in (("FG5", 4), ("FG6", 5)):
  282. nonzero_counts = []
  283. high_edges: list[int] = []
  284. for setting in HIGH_SETTINGS:
  285. edges = [
  286. int(_mapping(row.get(signal)).get("window_edges", 0))
  287. for row in rows_by_setting[setting]
  288. if isinstance(_mapping(row.get(signal)).get("window_edges"), int)
  289. and not isinstance(_mapping(row.get(signal)).get("window_edges"), bool)
  290. ]
  291. high_edges.extend(edges)
  292. nonzero_counts.append(sum(value > 0 for value in edges))
  293. if any(count >= 4 for count in nonzero_counts):
  294. computed = "detected"
  295. elif len(high_edges) == len(HIGH_SETTINGS) * SAMPLES_PER_SETTING and all(value == 0 for value in high_edges):
  296. computed = "absent"
  297. else:
  298. computed = "intermittent"
  299. computed_statuses[signal] = computed
  300. declared = fan3.get(signal)
  301. if declared in FAN_STATUSES and declared != computed:
  302. failures.append(f"fan_status_mismatch:{round_number}:FAN3:{signal}:{computed}")
  303. if computed == "detected" and any(
  304. isinstance(row.get("overflow_mask"), int) and row["overflow_mask"] & (1 << bit_index)
  305. for row in valid_rows
  306. ):
  307. failures.append(f"detected_channel_overflow:{round_number}:{signal}")
  308. if "detected" not in computed_statuses.values():
  309. failures.append(f"fan3_signal_not_detected:{round_number}")
  310. return failures
  311. def _validate_binding_artifact(binding: Any, name: str, round_number: int) -> list[str]:
  312. failures: list[str] = []
  313. payload = _mapping(binding)
  314. if not payload:
  315. return [f"missing_binding:{name}:{round_number}"]
  316. path = payload.get("path")
  317. digest = payload.get("sha256")
  318. if not isinstance(path, str) or not path:
  319. failures.append(f"binding_path_invalid:{round_number}:{name}")
  320. if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
  321. failures.append(f"binding_sha256_invalid:{round_number}:{name}")
  322. if name == "programmer_receipt" and payload.get("status") != "pass":
  323. failures.append(f"programmer_receipt_not_pass:{round_number}")
  324. receipt = payload.get("receipt")
  325. if isinstance(receipt, Mapping) and receipt.get("status") != "pass":
  326. failures.append(f"programmer_receipt_payload_not_pass:{round_number}")
  327. return failures
  328. def _validate_static_qualification(qualification: Any) -> list[str]:
  329. failures: list[str] = []
  330. payload = _mapping(qualification)
  331. if not payload:
  332. return ["static_qualification_missing"]
  333. if payload.get("schema") != "prod2u-p4-static-qualification-v1":
  334. failures.append("static_qualification_schema_mismatch")
  335. if payload.get("status") != "pass":
  336. failures.append("static_qualification_not_pass")
  337. if payload.get("profile") != "prod2u-fan-tach-binary921-v2" or payload.get("profile_id") != 4:
  338. failures.append("static_qualification_profile_mismatch")
  339. declared_failures = payload.get("failures")
  340. if not isinstance(declared_failures, list):
  341. failures.append("static_qualification_failures_invalid")
  342. elif declared_failures:
  343. failures.append("static_qualification_declares_failures")
  344. layers = _mapping(payload.get("layers"))
  345. for layer_name in REQUIRED_STATIC_LAYERS:
  346. layer = _mapping(layers.get(layer_name))
  347. if not layer:
  348. failures.append(f"static_layer_missing:{layer_name}")
  349. continue
  350. if layer.get("status") != "pass":
  351. failures.append(f"static_layer_not_pass:{layer_name}")
  352. artifacts = _mapping(layer.get("artifacts"))
  353. for artifact_name in STATIC_LAYER_ARTIFACTS[layer_name]:
  354. if artifact_name not in artifacts:
  355. failures.append(f"static_artifact_missing:{layer_name}:{artifact_name}")
  356. continue
  357. for failure in _validate_binding_artifact(artifacts.get(artifact_name), artifact_name, 0):
  358. failures.append(f"static_{failure}")
  359. return failures
  360. def _qualification_artifact_sha256(qualification: Any, layer: str, artifact: str) -> str | None:
  361. payload = _mapping(qualification)
  362. layer_payload = _mapping(_mapping(payload.get("layers")).get(layer))
  363. artifact_payload = _mapping(_mapping(layer_payload.get("artifacts")).get(artifact))
  364. digest = artifact_payload.get("sha256")
  365. return str(digest).casefold() if isinstance(digest, str) and SHA256_RE.fullmatch(digest) else None
  366. def _validate_qualification_binding(
  367. qualification: Any,
  368. evidence_binding: Any,
  369. variant: Any,
  370. round_number: int,
  371. ) -> list[str]:
  372. failures: list[str] = []
  373. binding = _mapping(evidence_binding)
  374. if variant not in {"normal", "trace"}:
  375. return [f"qualification_binding_variant_invalid:{round_number}"]
  376. expected = {
  377. "source_manifest": _qualification_artifact_sha256(
  378. qualification, "source", f"{variant}_source_manifest"
  379. ),
  380. "td_receipt": _qualification_artifact_sha256(
  381. qualification, f"td_{variant}", f"{variant}_td_receipt"
  382. ),
  383. "package_manifest": _qualification_artifact_sha256(
  384. qualification, "package", "package_manifest"
  385. ),
  386. "package_inventory": _qualification_artifact_sha256(
  387. qualification, "package", "package_inventory"
  388. ),
  389. }
  390. for artifact_name, expected_hash in expected.items():
  391. actual_hash = _mapping(binding.get(artifact_name)).get("sha256")
  392. if expected_hash is None or not isinstance(actual_hash, str) or actual_hash.casefold() != expected_hash:
  393. failures.append(f"qualification_binding_mismatch:{round_number}:{artifact_name}")
  394. return failures
  395. def _validate_evidence_binding(binding: Any, identity: Mapping[str, Any], round_number: int) -> list[str]:
  396. failures: list[str] = []
  397. payload = _mapping(binding)
  398. if not payload:
  399. return [f"missing_required:evidence:evidence_binding:{round_number}"]
  400. for name in BOUND_ARTIFACTS:
  401. failures.extend(_validate_binding_artifact(payload.get(name), name, round_number))
  402. bound_identity = _mapping(payload.get("identity"))
  403. if not bound_identity:
  404. failures.append(f"binding_identity_missing:{round_number}")
  405. variant_identity = _mapping(identity.get("variants")).get(bound_identity.get("variant"))
  406. for name in IDENTITY_FIELDS:
  407. expected = identity.get(name)
  408. if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
  409. expected = variant_identity.get(name, expected)
  410. if name in identity and expected is not None and bound_identity.get(name) != expected:
  411. failures.append(f"binding_identity_mismatch:{round_number}:{name}")
  412. source_manifest = _mapping(payload.get("source_manifest"))
  413. expected_source_hash = identity.get("source_manifest_sha256")
  414. if expected_source_hash:
  415. declared_source_hash = source_manifest.get("declared_sha256")
  416. if declared_source_hash is not None:
  417. if declared_source_hash != expected_source_hash:
  418. failures.append(f"source_manifest_binding_mismatch:{round_number}")
  419. elif source_manifest.get("sha256") != expected_source_hash:
  420. failures.append(f"source_manifest_binding_mismatch:{round_number}")
  421. return failures
  422. def validate_evidence(evidence: Mapping[str, Any]) -> dict[str, Any]:
  423. failures: list[str] = []
  424. failures.extend(f"missing_required:evidence:{name}" for name in EVIDENCE_REQUIRED if name not in evidence)
  425. if evidence.get("schema") != SCHEMAS["evidence"]:
  426. failures.append("schema_mismatch")
  427. round_number = evidence.get("round")
  428. if not isinstance(round_number, int) or isinstance(round_number, bool) or not 1 <= round_number <= ROUND_COUNT:
  429. failures.append("round_invalid")
  430. round_number = 0
  431. if _mapping(evidence.get("bmc")).get("status") != "out_of_scope":
  432. failures.append("bmc_must_be_out_of_scope")
  433. actual_identity = _mapping(evidence.get("identity"))
  434. for name in IDENTITY_FIELDS:
  435. if not actual_identity.get(name):
  436. failures.append(f"identity_field_missing:{round_number}:{name}")
  437. if evidence.get("variant") is not None and evidence.get("variant") != actual_identity.get("variant"):
  438. failures.append(f"variant_identity_mismatch:{round_number}")
  439. failures.extend(_validate_layers(evidence.get("layers"), round_number))
  440. fan3 = _mapping(_mapping(evidence.get("fan")).get("FAN3"))
  441. for signal in ("FG5", "FG6"):
  442. if fan3.get(signal) not in FAN_STATUSES:
  443. failures.append(f"invalid_fan_status:{round_number}:FAN3:{signal}")
  444. failures.extend(_validate_windows(evidence.get("windows"), round_number))
  445. failures.extend(_validate_raw_samples(evidence.get("raw_samples"), fan3, round_number))
  446. failures.extend(_validate_correlation(evidence.get("correlation"), round_number))
  447. if _mapping(evidence.get("rpm")).get("status") != "not_qualified":
  448. failures.append(f"rpm_not_qualified:{round_number}")
  449. ptc = _mapping(evidence.get("ptc"))
  450. if ptc.get("actuation") is not True:
  451. failures.append(f"ptc_actuation_must_be_true:{round_number}")
  452. if ptc.get("measurement") != "not_run":
  453. failures.append(f"ptc_measurement_must_be_not_run:{round_number}")
  454. failures.extend(_validate_evidence_binding(evidence.get("evidence_binding"), actual_identity, round_number))
  455. return {
  456. "status": "pass" if not failures else "fail",
  457. "round": round_number,
  458. "failures": list(dict.fromkeys(failures)),
  459. }
  460. def _identity_failures(expected: Mapping[str, Any], actual: Mapping[str, Any], round_number: int) -> list[str]:
  461. failures: list[str] = []
  462. for name in ("dut_id", "profile"):
  463. if actual.get(name) != expected.get(name):
  464. failures.append(f"identity_mismatch:{round_number}:{name}")
  465. variant_identity = _mapping(expected.get("variants")).get(actual.get("variant"))
  466. for name in ("build_id", "bitstream_sha256", "source_manifest_sha256"):
  467. expected_value = expected.get(name)
  468. if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
  469. expected_value = variant_identity.get(name, expected_value)
  470. if expected_value is not None and actual.get(name) != expected_value:
  471. failures.append(f"identity_mismatch:{round_number}:{name}")
  472. return failures
  473. def validate_campaign(campaign: Mapping[str, Any]) -> dict[str, Any]:
  474. failures: list[str] = []
  475. if campaign.get("schema") != SCHEMAS["campaign"]:
  476. failures.append("schema_mismatch")
  477. campaign_identity = _mapping(campaign.get("campaign_identity"))
  478. if campaign_identity.get("planned_rounds") != ROUND_COUNT:
  479. failures.append("planned_rounds_must_be_10")
  480. if _mapping(campaign.get("bmc")).get("status") != "out_of_scope":
  481. failures.append("bmc_must_be_out_of_scope")
  482. qualification = campaign.get("qualification")
  483. failures.extend(_validate_static_qualification(qualification))
  484. evidence_bindings = campaign.get("evidence_bindings")
  485. if not isinstance(evidence_bindings, list) or len(evidence_bindings) != ROUND_COUNT:
  486. failures.append("evidence_bindings_must_contain_10_rounds")
  487. if "layers" in campaign:
  488. failures.extend(_validate_layers(campaign.get("layers")))
  489. rounds = campaign.get("rounds")
  490. if not isinstance(rounds, list) or len(rounds) != ROUND_COUNT:
  491. failures.append("round_count_must_be_10")
  492. rounds = rounds if isinstance(rounds, list) else []
  493. numbers = [round_item.get("round") for round_item in rounds if isinstance(round_item, Mapping)]
  494. if numbers != list(range(1, ROUND_COUNT + 1)):
  495. failures.append("round_sequence_not_1_to_10")
  496. for position, round_item in enumerate(rounds, start=1):
  497. if not isinstance(round_item, Mapping):
  498. failures.append(f"round_not_object:{position}")
  499. continue
  500. round_number = round_item.get("round", position)
  501. result = validate_evidence(
  502. {
  503. **round_item,
  504. "schema": SCHEMAS["evidence"],
  505. "evidence_id": f"{campaign.get('campaign_id', 'campaign')}-R{position:02d}",
  506. "campaign_id": campaign.get("campaign_id"),
  507. "campaign_identity": campaign_identity,
  508. "bmc": campaign.get("bmc"),
  509. }
  510. )
  511. failures.extend(result["failures"])
  512. failures.extend(_identity_failures(campaign_identity, _mapping(round_item.get("identity")), position))
  513. failures.extend(
  514. _validate_qualification_binding(
  515. qualification,
  516. round_item.get("evidence_binding"),
  517. _mapping(round_item.get("identity")).get("variant"),
  518. position,
  519. )
  520. )
  521. if round_item.get("variant") is not None and round_item.get("variant") != _mapping(round_item.get("identity")).get("variant"):
  522. failures.append(f"variant_identity_mismatch:{position}")
  523. if isinstance(evidence_bindings, list) and len(evidence_bindings) == ROUND_COUNT:
  524. for position, item in enumerate(evidence_bindings, start=1):
  525. wrapper = _mapping(item)
  526. if wrapper.get("round") != position:
  527. failures.append(f"evidence_binding_round_mismatch:{position}")
  528. round_item = rounds[position - 1] if position <= len(rounds) and isinstance(rounds[position - 1], Mapping) else {}
  529. expected_binding = _mapping(round_item.get("evidence_binding"))
  530. if wrapper.get("evidence_binding") != expected_binding:
  531. failures.append(f"evidence_binding_not_preserved:{position}")
  532. return {
  533. "status": "pass" if not failures else "fail",
  534. "campaign_id": campaign.get("campaign_id"),
  535. "round_count": len(rounds),
  536. "bmc": _mapping(campaign.get("bmc")).get("status"),
  537. "failures": list(dict.fromkeys(failures)),
  538. }
  539. def validate_final_gate(gate: Mapping[str, Any]) -> dict[str, Any]:
  540. failures: list[str] = []
  541. failures.extend(f"missing_required:final_gate:{name}" for name in FINAL_GATE_REQUIRED if name not in gate)
  542. if gate.get("schema") != SCHEMAS["final_gate"]:
  543. failures.append("schema_mismatch")
  544. if _mapping(gate.get("bmc")).get("status") != "out_of_scope":
  545. failures.append("bmc_must_be_out_of_scope")
  546. qualification = gate.get("qualification")
  547. failures.extend(_validate_static_qualification(qualification))
  548. failures.extend(_validate_layers(gate.get("layers")))
  549. if gate.get("round_count") != ROUND_COUNT:
  550. failures.append("round_count_must_be_10")
  551. declared = gate.get("failures")
  552. if not isinstance(declared, list):
  553. failures.append("failures_must_be_array")
  554. elif gate.get("status") == "pass" and declared:
  555. failures.append("pass_gate_has_failures")
  556. bindings = gate.get("evidence_bindings")
  557. if not isinstance(bindings, list) or len(bindings) != ROUND_COUNT:
  558. failures.append("evidence_bindings_must_contain_10_rounds")
  559. else:
  560. gate_identity = _mapping(gate.get("campaign_identity"))
  561. for position, item in enumerate(bindings, start=1):
  562. wrapper = _mapping(item)
  563. if wrapper.get("round") != position:
  564. failures.append(f"evidence_binding_round_mismatch:{position}")
  565. failures.extend(_validate_evidence_binding(wrapper.get("evidence_binding"), gate_identity, position))
  566. binding_identity = _mapping(_mapping(wrapper.get("evidence_binding")).get("identity"))
  567. failures.extend(
  568. _validate_qualification_binding(
  569. qualification,
  570. wrapper.get("evidence_binding"),
  571. binding_identity.get("variant"),
  572. position,
  573. )
  574. )
  575. if gate.get("status") == "pass" and failures:
  576. failures.append("final_gate_pass_inconsistent")
  577. return {
  578. "status": "pass" if not failures else "fail",
  579. "campaign_id": gate.get("campaign_id"),
  580. "bmc": _mapping(gate.get("bmc")).get("status"),
  581. "failures": list(dict.fromkeys(failures)),
  582. }
  583. def build_final_gate(campaign: Mapping[str, Any]) -> dict[str, Any]:
  584. """Build the strict P4 final-gate document without performing live I/O."""
  585. campaign_result = validate_campaign(campaign)
  586. rounds = campaign.get("rounds") if isinstance(campaign.get("rounds"), list) else []
  587. required_layers: dict[str, str] = {}
  588. optional_layers: dict[str, str] = {}
  589. for round_item in rounds:
  590. layers = _mapping(round_item.get("layers")) if isinstance(round_item, Mapping) else {}
  591. for name, status in _mapping(layers.get("required")).items():
  592. if name not in required_layers:
  593. required_layers[name] = status
  594. elif required_layers[name] != "pass" or status != "pass":
  595. required_layers[name] = "fail"
  596. for name, status in _mapping(layers.get("optional")).items():
  597. if name not in optional_layers:
  598. optional_layers[name] = status
  599. bindings = campaign.get("evidence_bindings")
  600. if not isinstance(bindings, list):
  601. bindings = []
  602. return {
  603. "schema": SCHEMAS["final_gate"],
  604. "status": "pass" if campaign_result["status"] == "pass" else "fail",
  605. "campaign_id": campaign.get("campaign_id"),
  606. "campaign_identity": _mapping(campaign.get("campaign_identity")),
  607. "bmc": _mapping(campaign.get("bmc")),
  608. "qualification": _mapping(campaign.get("qualification")),
  609. "layers": {"required": required_layers, "optional": optional_layers},
  610. "round_count": len(rounds),
  611. "evidence_bindings": bindings,
  612. "failures": list(campaign_result["failures"]),
  613. "summary": {"campaign_status": campaign_result["status"], "round_count": len(rounds)},
  614. }
  615. def load_json(source: str | Path | Mapping[str, Any]) -> Mapping[str, Any]:
  616. if isinstance(source, Mapping):
  617. return source
  618. payload = json.loads(Path(source).read_text(encoding="utf-8-sig"))
  619. if not isinstance(payload, Mapping):
  620. raise ValueError("document must be a JSON object")
  621. return payload
  622. def validate_document(source: str | Path | Mapping[str, Any], kind: str | None = None) -> dict[str, Any]:
  623. document = load_json(source)
  624. selected = kind
  625. if selected is None:
  626. selected = next((name for name, schema_id in SCHEMAS.items() if document.get("schema") == schema_id), None)
  627. if selected == "evidence":
  628. return validate_evidence(document)
  629. if selected == "campaign":
  630. return validate_campaign(document)
  631. if selected == "final_gate":
  632. return validate_final_gate(document)
  633. return {"status": "fail", "failures": ["unknown_schema"]}
  634. def main(argv: Sequence[str] | None = None) -> int:
  635. parser = argparse.ArgumentParser(description=__doc__)
  636. parser.add_argument("document", type=Path)
  637. parser.add_argument("--kind", choices=sorted(SCHEMAS), help="document kind; inferred from schema when omitted")
  638. args = parser.parse_args(argv)
  639. try:
  640. result = validate_document(args.document, args.kind)
  641. except (OSError, ValueError, json.JSONDecodeError) as exc:
  642. result = {"status": "fail", "failures": [f"input_error:{exc}"]}
  643. print(json.dumps(result, ensure_ascii=True, sort_keys=True))
  644. return 0 if result.get("status") == "pass" else 1
  645. if __name__ == "__main__":
  646. sys.exit(main())