test_prod2u_validator.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #!/usr/bin/env python3
  2. """TDD coverage for raw-first Prod2U evidence validation."""
  3. from __future__ import annotations
  4. import hashlib
  5. import importlib.util
  6. import json
  7. import sys
  8. import tempfile
  9. import unittest
  10. from pathlib import Path
  11. from types import SimpleNamespace
  12. from unittest import mock
  13. import jsonschema
  14. ROOT = Path(__file__).resolve().parents[2]
  15. VALIDATOR = ROOT / "tools" / "prod2u_validate.py"
  16. TOOLS = ROOT / "tools"
  17. if str(TOOLS) not in sys.path:
  18. sys.path.insert(0, str(TOOLS))
  19. def load_validator():
  20. if not VALIDATOR.is_file():
  21. raise AssertionError(f"missing validator: {VALIDATOR}")
  22. spec = importlib.util.spec_from_file_location("prod2u_validate_test", VALIDATOR)
  23. if spec is None or spec.loader is None:
  24. raise AssertionError("unable to load Prod2U validator")
  25. module = importlib.util.module_from_spec(spec)
  26. spec.loader.exec_module(module)
  27. return module
  28. def program_receipt() -> dict:
  29. build_id = "1234ABCD"
  30. return {
  31. "schema": "prod2u-program-sram-receipt-v1",
  32. "status": "pass",
  33. "request": {
  34. "operation": "PROGRAM_SRAM",
  35. "target_chip": "EF2L45",
  36. "cable_index": 0,
  37. "speed_code": 2,
  38. "speed_hz": 200000,
  39. "attempt_limit": 1,
  40. "power_cycle_allowed": False,
  41. },
  42. "bitstream": {"path": f"C:/P2U/{build_id}/fw.bit", "sha256": "a" * 64, "build_id": build_id},
  43. "staging": {
  44. "expected_path": f"C:/P2U/{build_id}/fw.bit",
  45. "observed_path": f"C:/P2U/{build_id}/fw.bit",
  46. "matches_expected_path": True,
  47. },
  48. "execution": {
  49. "exit_code": 0,
  50. "timed_out": False,
  51. "attempt_count": 1,
  52. "retry_count": 0,
  53. "power_cycle_count": 0,
  54. "command_execution_attempted": True,
  55. "timeout_seconds": 60,
  56. "started_at": "2026-07-10T10:00:00Z",
  57. "finished_at": "2026-07-10T10:00:02Z",
  58. "duration_seconds": 2.0,
  59. },
  60. "parser": {
  61. "status": "pass",
  62. "exit_code_trusted": False,
  63. "ordered_markers": [
  64. "download_start",
  65. "chip_validation",
  66. "bit_to_vec_start",
  67. "bit_to_vec_finish",
  68. "program_start",
  69. "program_finish",
  70. "download_finish",
  71. ],
  72. "ordered_markers_complete": True,
  73. "observed_markers": [
  74. "download_start",
  75. "chip_validation",
  76. "bit_to_vec_start",
  77. "bit_to_vec_finish",
  78. "program_start",
  79. "program_finish",
  80. "download_finish",
  81. ],
  82. "observed_marker_lines": [1, 2, 3, 4, 5, 6, 7],
  83. "error_markers": [],
  84. "failures": [],
  85. "transcript_sha256": "9" * 64,
  86. },
  87. "tool": {"path": "C:/TD/bin/bw_commands_prompt.exe", "td_root": "C:/TD", "td_bin": "C:/TD/bin"},
  88. "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
  89. "process_cleanup": {"status": "pass", "td_root": "C:/TD", "wait_seconds": 5.0, "remaining": []},
  90. "artifacts": {
  91. "tcl": {"path": "program-sram.tcl", "size": 1, "sha256": "1" * 64},
  92. "stdout": {"path": "bitwriter-stdout.log", "size": 1, "sha256": "2" * 64},
  93. "stderr": {"path": "bitwriter-stderr.log", "size": 1, "sha256": "3" * 64},
  94. "log_delta": {"path": "bitwriter-log-delta.log", "size": 1, "sha256": "4" * 64},
  95. "log_delta_sources": [
  96. {
  97. "path": "C:/TD/log/bw_test.log",
  98. "start_offset": 0,
  99. "byte_count": 1,
  100. "sha256": "8" * 64,
  101. }
  102. ],
  103. },
  104. "safety": {
  105. "flash_attempted": False,
  106. "programs_nonvolatile": False,
  107. "power_cycle_attempted": False,
  108. "driver_install_attempted": False,
  109. "toggles_dtr_rts": False,
  110. "real_ptc_fan_action_attempted": False,
  111. "external_programming_command_executed": True,
  112. },
  113. }
  114. class Prod2UValidatorTests(unittest.TestCase):
  115. def build_fixture(self, root: Path) -> tuple[dict, dict, Path]:
  116. import prod2u_collector as collector
  117. from binary921 import CommandId, FrameType, build_host_command, encode_frame
  118. profile_id = 3
  119. build_id = "1234ABCD"
  120. command_wire = b"".join(
  121. build_host_command(
  122. seq=index,
  123. command=command,
  124. channel=channel,
  125. percent=percent,
  126. profile_id=profile_id,
  127. )
  128. for index, (_, command, channel, percent) in enumerate(collector.COMMAND_SEQUENCE, start=1)
  129. )
  130. ready = encode_frame(
  131. profile_id=profile_id,
  132. frame_type=FrameType.READY,
  133. seq=1,
  134. timestamp_tick=250000,
  135. payload=bytes([profile_id]) + int(build_id, 16).to_bytes(4, "little") + bytes([1, 0]),
  136. )
  137. acks = b"".join(
  138. encode_frame(
  139. profile_id=profile_id,
  140. frame_type=FrameType.HOST_ACK,
  141. seq=index,
  142. timestamp_tick=0,
  143. payload=bytes([1, command, 0, 0, 0x34, 0x12]),
  144. )
  145. for index, (_, command, _, _) in enumerate(collector.COMMAND_SEQUENCE, start=1)
  146. )
  147. bmc_payload_bytes = bytes([0x1E, 0x4B] + [0xFF] * 22 + [0x20, 0x19] + [0xFF] * 22)
  148. bmc_checksum = sum(bmc_payload_bytes) & 0xFFFF
  149. bmc = encode_frame(
  150. profile_id=profile_id,
  151. frame_type=FrameType.BMC_PAYLOAD,
  152. seq=30,
  153. timestamp_tick=0,
  154. payload=bytes(
  155. [48, 48, 1, 0, bmc_payload_bytes[0], bmc_payload_bytes[-1], bmc_checksum & 0xFF, bmc_checksum >> 8]
  156. ),
  157. )
  158. sensor = encode_frame(
  159. profile_id=profile_id,
  160. frame_type=FrameType.SENSOR_CACHE,
  161. seq=31,
  162. timestamp_tick=0,
  163. payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
  164. )
  165. snapshot = encode_frame(
  166. profile_id=profile_id,
  167. frame_type=FrameType.MODULE_SNAPSHOT,
  168. seq=32,
  169. timestamp_tick=0,
  170. payload=bytes(
  171. [
  172. profile_id,
  173. 0,
  174. 12,
  175. 0,
  176. 0x1E,
  177. 0xFF,
  178. 0x08,
  179. 0x14,
  180. CommandId.DISABLE,
  181. 0,
  182. 0,
  183. 0,
  184. 0,
  185. 1,
  186. 2,
  187. 22,
  188. 0,
  189. 0,
  190. 30,
  191. 30,
  192. 0,
  193. 0x0F,
  194. 0,
  195. 0,
  196. ]
  197. ),
  198. )
  199. combined = ready + acks + bmc + sensor + snapshot
  200. (root / "combined-rx.raw").write_bytes(combined)
  201. (root / "host-command-wire.bin").write_bytes(command_wire)
  202. collector_manifest = {
  203. "schema": "prod2u-collector-manifest-v1",
  204. "status": "pass",
  205. "artifact_hashes": {
  206. "combined-rx.raw": hashlib.sha256(combined).hexdigest(),
  207. "host-command-wire.bin": hashlib.sha256(command_wire).hexdigest(),
  208. },
  209. "safety": {
  210. "flash_attempted": False,
  211. "programs_nonvolatile": False,
  212. "driver_install_attempted": False,
  213. "toggles_dtr_rts": False,
  214. },
  215. }
  216. source_manifest = {
  217. "schema": "prod2u-source-manifest-v1",
  218. "profile": "prod2u-bmc-replay-binary921",
  219. "source_manifest_sha256": "1234abcd" + "b" * 56,
  220. "build_id": build_id,
  221. }
  222. bmc_receipt = root / "bmc-replay-session.json"
  223. bmc_receipt.write_text(
  224. json.dumps(
  225. {
  226. "schema": "prod2u-bmc-replay-session-v1",
  227. "status": "pass",
  228. "bmc_source": "pc_replay_from_real_bmc_capture",
  229. "reply_sha256": hashlib.sha256(
  230. (" ".join(f"{value:02x}" for value in bmc_payload_bytes) + "\r\n").encode("ascii")
  231. ).hexdigest(),
  232. "payload_hex": [f"{value:02x}" for value in bmc_payload_bytes],
  233. "byte_count": 48,
  234. "valid_count": 2,
  235. "missing_count": 22,
  236. "matched_poll_count": 1,
  237. "reply_count": 1,
  238. "started_at": "2026-07-10T09:59:59Z",
  239. "last_reply_at": "2026-07-10T10:00:01Z",
  240. }
  241. ),
  242. encoding="utf-8",
  243. )
  244. return collector_manifest, source_manifest, bmc_receipt
  245. def test_raw_first_validator_passes_complete_software_chain(self) -> None:
  246. validator = load_validator()
  247. with tempfile.TemporaryDirectory() as tmp:
  248. root = Path(tmp)
  249. collector, source, bmc = self.build_fixture(root)
  250. evidence = validator.validate_evidence_directory(
  251. collector_dir=root,
  252. collector=collector,
  253. program=program_receipt(),
  254. source_manifest=source,
  255. programmer_receipt_path="programmer/program-sram-receipt.json",
  256. programmer_receipt_sha256="c" * 64,
  257. bmc_replay_receipt_path=bmc,
  258. )
  259. self.assertEqual(evidence["status"], "pass", evidence["blockers"])
  260. self.assertEqual(evidence["startup_ready"]["build_id"], "1234ABCD")
  261. self.assertEqual(evidence["host_command_count"], 12)
  262. self.assertEqual(evidence["host_ack_matched_count"], 12)
  263. self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
  264. self.assertEqual(evidence["raw_validation"]["sensor_cache"]["valid_count"], 2)
  265. self.assertEqual(evidence["raw_validation"]["sensor_cache"]["missing_count"], 22)
  266. self.assertEqual(evidence["raw_validation"]["timeout_fallback"]["status"], "pass")
  267. def test_missing_bmc_replay_receipt_remains_schema_valid_blocked_evidence(self) -> None:
  268. validator = load_validator()
  269. schema = json.loads(
  270. (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
  271. )
  272. with tempfile.TemporaryDirectory() as tmp:
  273. root = Path(tmp)
  274. collector, source, bmc = self.build_fixture(root)
  275. bmc.unlink()
  276. evidence = validator.validate_evidence_directory(
  277. collector_dir=root,
  278. collector=collector,
  279. program=program_receipt(),
  280. source_manifest=source,
  281. programmer_receipt_path="programmer/program-sram-receipt.json",
  282. programmer_receipt_sha256="c" * 64,
  283. bmc_replay_receipt_path=bmc,
  284. )
  285. self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
  286. self.assertEqual(
  287. evidence["bmc_replay"],
  288. {
  289. "status": "not_run",
  290. "bmc_source": "not_run",
  291. "payload_sha256": None,
  292. },
  293. )
  294. jsonschema.validate(evidence, schema)
  295. def test_missing_bmc_uart_frames_are_not_independent_failures_when_replay_was_not_run(self) -> None:
  296. validator = load_validator()
  297. from binary921 import FrameType, decode_stream
  298. with tempfile.TemporaryDirectory() as tmp:
  299. root = Path(tmp)
  300. collector, source, bmc = self.build_fixture(root)
  301. frames, remainder = decode_stream((root / "combined-rx.raw").read_bytes())
  302. self.assertEqual(remainder, b"")
  303. combined = b"".join(
  304. frame.raw
  305. for frame in frames
  306. if frame.frame_type not in (FrameType.BMC_PAYLOAD, FrameType.SENSOR_CACHE)
  307. )
  308. (root / "combined-rx.raw").write_bytes(combined)
  309. collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
  310. bmc.unlink()
  311. evidence = validator.validate_evidence_directory(
  312. collector_dir=root,
  313. collector=collector,
  314. program=program_receipt(),
  315. source_manifest=source,
  316. programmer_receipt_path="programmer/program-sram-receipt.json",
  317. programmer_receipt_sha256="c" * 64,
  318. bmc_replay_receipt_path=bmc,
  319. )
  320. self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
  321. self.assertEqual(evidence["blockers"], ["bmc_replay_not_pass"])
  322. self.assertEqual(evidence["raw_validation"]["sensor_cache"]["status"], "not_run")
  323. def test_invalid_bmc_replay_receipt_remains_schema_valid_failed_evidence(self) -> None:
  324. validator = load_validator()
  325. schema = json.loads(
  326. (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
  327. )
  328. for invalid_payload in ("{", "[]"):
  329. with self.subTest(invalid_payload=invalid_payload), tempfile.TemporaryDirectory() as tmp:
  330. root = Path(tmp)
  331. collector, source, bmc = self.build_fixture(root)
  332. bmc.write_text(invalid_payload, encoding="utf-8")
  333. evidence = validator.validate_evidence_directory(
  334. collector_dir=root,
  335. collector=collector,
  336. program=program_receipt(),
  337. source_manifest=source,
  338. programmer_receipt_path="programmer/program-sram-receipt.json",
  339. programmer_receipt_sha256="c" * 64,
  340. bmc_replay_receipt_path=bmc,
  341. )
  342. self.assertEqual(evidence["status"], "fail")
  343. self.assertEqual(evidence["bmc_replay"]["bmc_source"], "not_run")
  344. self.assertIsNone(evidence["bmc_replay"]["payload_sha256"])
  345. jsonschema.validate(evidence, schema)
  346. def test_ready_epoch_selects_last_matching_ready_in_the_post_callback_stream(self) -> None:
  347. validator = load_validator()
  348. from binary921 import FrameType, decode_stream, encode_frame
  349. with tempfile.TemporaryDirectory() as tmp:
  350. root = Path(tmp)
  351. collector, source, bmc = self.build_fixture(root)
  352. combined = (root / "combined-rx.raw").read_bytes()
  353. frames, remainder = decode_stream(combined)
  354. self.assertEqual(remainder, b"")
  355. first_ready_len = len(frames[0].raw)
  356. later_ready = encode_frame(
  357. profile_id=3,
  358. frame_type=FrameType.READY,
  359. seq=1,
  360. timestamp_tick=250001,
  361. payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, 2]),
  362. )
  363. combined = combined[:first_ready_len] + later_ready + combined[first_ready_len:]
  364. (root / "combined-rx.raw").write_bytes(combined)
  365. collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
  366. evidence = validator.validate_evidence_directory(
  367. collector_dir=root,
  368. collector=collector,
  369. program=program_receipt(),
  370. source_manifest=source,
  371. programmer_receipt_path="programmer/program-sram-receipt.json",
  372. programmer_receipt_sha256="c" * 64,
  373. bmc_replay_receipt_path=bmc,
  374. )
  375. self.assertEqual(evidence["status"], "pass", evidence["blockers"])
  376. self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
  377. self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 2)
  378. self.assertEqual(evidence["startup_ready"]["selection_policy"], "last_matching_ready")
  379. def test_collector_wait_selects_last_matching_ready_from_one_buffered_chunk(self) -> None:
  380. import prod2u_collector as collector
  381. from binary921 import FrameType, encode_frame
  382. ready_frames = b"".join(
  383. encode_frame(
  384. profile_id=3,
  385. frame_type=FrameType.READY,
  386. seq=1,
  387. timestamp_tick=250000 + announcement,
  388. payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
  389. )
  390. for announcement in (0, 2)
  391. )
  392. class BufferedSerial:
  393. def __init__(self, payload: bytes) -> None:
  394. self.payload = payload
  395. def read(self, _size: int) -> bytes:
  396. payload, self.payload = self.payload, b""
  397. return payload
  398. result = collector.wait_for_ready(
  399. BufferedSerial(ready_frames),
  400. timeout_sec=0.05,
  401. expected_profile_id=3,
  402. expected_build_id="1234ABCD",
  403. expected_epoch=1,
  404. expected_por_reason=1,
  405. max_announcement_seq=2,
  406. )
  407. self.assertEqual(result["status"], "pass")
  408. self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
  409. self.assertEqual(result["matching_ready_count"], 2)
  410. self.assertEqual(result["selection_policy"], "last_matching_ready")
  411. def test_collector_splits_corrupt_and_old_build_bytes_before_three_matching_ready_frames(self) -> None:
  412. import prod2u_collector as collector
  413. from binary921 import FrameType, encode_frame
  414. old_ready = encode_frame(
  415. profile_id=3,
  416. frame_type=FrameType.READY,
  417. seq=1,
  418. timestamp_tick=249999,
  419. payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
  420. )
  421. corrupt_ready = bytearray(old_ready)
  422. corrupt_ready[-1] ^= 1
  423. matching_ready = b"".join(
  424. encode_frame(
  425. profile_id=3,
  426. frame_type=FrameType.READY,
  427. seq=1,
  428. timestamp_tick=250000 + announcement,
  429. payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
  430. )
  431. for announcement in (0, 1, 2)
  432. )
  433. pre_ready = bytes(corrupt_ready) + old_ready
  434. stream = pre_ready + matching_ready
  435. class BufferedSerial:
  436. def __init__(self, payload: bytes) -> None:
  437. self.payload = payload
  438. def read(self, _size: int) -> bytes:
  439. payload, self.payload = self.payload, b""
  440. return payload
  441. result = collector.wait_for_ready(
  442. BufferedSerial(stream),
  443. timeout_sec=0.05,
  444. expected_profile_id=3,
  445. expected_build_id="1234ABCD",
  446. expected_epoch=1,
  447. expected_por_reason=1,
  448. max_announcement_seq=2,
  449. )
  450. self.assertEqual(result["status"], "pass")
  451. self.assertEqual(result["raw"], stream)
  452. self.assertEqual(result["pre_ready_raw"], pre_ready)
  453. self.assertEqual(result["epoch_start_offset"], len(pre_ready))
  454. self.assertEqual(result["epoch_raw"], matching_ready)
  455. self.assertEqual(result["matching_ready_count"], 3)
  456. self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
  457. def test_combined_collector_writes_pre_ready_diagnostics_and_formal_epoch_separately(self) -> None:
  458. import prod2u_collector as collector
  459. from binary921 import FrameType, encode_frame
  460. old_ready = encode_frame(
  461. profile_id=3,
  462. frame_type=FrameType.READY,
  463. seq=1,
  464. timestamp_tick=249999,
  465. payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
  466. )
  467. corrupt_ready = bytearray(old_ready)
  468. corrupt_ready[-1] ^= 1
  469. matching_ready = b"".join(
  470. encode_frame(
  471. profile_id=3,
  472. frame_type=FrameType.READY,
  473. seq=1,
  474. timestamp_tick=250000 + announcement,
  475. payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
  476. )
  477. for announcement in (0, 1, 2)
  478. )
  479. pre_ready = bytes(corrupt_ready) + old_ready
  480. class FakeSerial:
  481. def __init__(self, payload: bytes) -> None:
  482. self.payload = payload
  483. self.closed = False
  484. def read(self, _size: int) -> bytes:
  485. payload, self.payload = self.payload, b""
  486. return payload
  487. def write(self, payload: bytes) -> int:
  488. return len(payload)
  489. def flush(self) -> None:
  490. return None
  491. def close(self) -> None:
  492. self.closed = True
  493. with tempfile.TemporaryDirectory() as tmp:
  494. root = Path(tmp)
  495. endpoint = FakeSerial(pre_ready + matching_ready)
  496. args = SimpleNamespace(
  497. output_dir=str(root),
  498. profile="prod2u-bmc-replay-binary921",
  499. transport="combined-single-com",
  500. combined_port="COM5",
  501. host_port="",
  502. expected_build_id="1234ABCD",
  503. expected_epoch=1,
  504. ready_timeout_sec=0.05,
  505. ack_window_sec=0.0,
  506. duration_sec=0.0,
  507. bmc_replay_receipt="",
  508. )
  509. with mock.patch.object(collector, "_open_serial", return_value=endpoint):
  510. manifest = collector.collect_live(args)
  511. self.assertTrue(endpoint.closed)
  512. self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), pre_ready)
  513. self.assertEqual((root / "combined-rx.raw").read_bytes(), matching_ready)
  514. self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), pre_ready + matching_ready)
  515. preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
  516. self.assertEqual(preflight["epoch_start_offset"], len(pre_ready))
  517. self.assertEqual(manifest["startup_ready"]["matching_ready_count"], 3)
  518. self.assertEqual(
  519. manifest["artifact_hashes"]["combined-rx.raw"],
  520. hashlib.sha256(matching_ready).hexdigest(),
  521. )
  522. self.assertEqual(
  523. manifest["artifact_hashes"]["pre-ready-uart.raw"],
  524. hashlib.sha256(pre_ready).hexdigest(),
  525. )
  526. def test_ready_timeout_preserves_diagnostics_without_creating_a_formal_epoch(self) -> None:
  527. import prod2u_collector as collector
  528. from binary921 import FrameType, encode_frame
  529. old_ready = encode_frame(
  530. profile_id=3,
  531. frame_type=FrameType.READY,
  532. seq=1,
  533. timestamp_tick=249999,
  534. payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
  535. )
  536. corrupt_ready = bytearray(old_ready)
  537. corrupt_ready[-1] ^= 1
  538. observed = bytes(corrupt_ready) + old_ready
  539. with tempfile.TemporaryDirectory() as tmp:
  540. root = Path(tmp)
  541. manifest = collector.write_blocked_manifest(
  542. root,
  543. profile="prod2u-bmc-replay-binary921",
  544. status="blocked_waiting_for_binary921_ready",
  545. startup_raw=observed,
  546. startup_frames=[],
  547. error="build_mismatch",
  548. timeout_evidence={"status": "blocked_waiting_for_binary921_ready"},
  549. )
  550. self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), observed)
  551. self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), observed)
  552. self.assertEqual((root / "combined-rx.raw").read_bytes(), b"")
  553. preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
  554. self.assertIsNone(preflight["epoch_start_offset"])
  555. self.assertEqual(
  556. manifest["artifact_hashes"]["pre-ready-uart.raw"],
  557. hashlib.sha256(observed).hexdigest(),
  558. )
  559. def test_validator_rejects_formal_combined_rx_that_starts_before_matching_ready_epoch(self) -> None:
  560. validator = load_validator()
  561. from binary921 import FrameType, encode_frame
  562. with tempfile.TemporaryDirectory() as tmp:
  563. root = Path(tmp)
  564. collector, source, bmc = self.build_fixture(root)
  565. combined = (root / "combined-rx.raw").read_bytes()
  566. old_ready = encode_frame(
  567. profile_id=3,
  568. frame_type=FrameType.READY,
  569. seq=1,
  570. timestamp_tick=249999,
  571. payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
  572. )
  573. contaminated = old_ready + combined
  574. (root / "combined-rx.raw").write_bytes(contaminated)
  575. collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(contaminated).hexdigest()
  576. evidence = validator.validate_evidence_directory(
  577. collector_dir=root,
  578. collector=collector,
  579. program=program_receipt(),
  580. source_manifest=source,
  581. programmer_receipt_path="programmer/program-sram-receipt.json",
  582. programmer_receipt_sha256="c" * 64,
  583. bmc_replay_receipt_path=bmc,
  584. )
  585. self.assertEqual(evidence["status"], "fail")
  586. self.assertIn("formal_epoch_does_not_start_at_matching_ready", evidence["blockers"])
  587. def test_validator_strictly_decodes_post_epoch_artifact_and_ignores_pre_ready_diagnostics(self) -> None:
  588. validator = load_validator()
  589. from binary921 import FrameType, decode_stream, encode_frame
  590. with tempfile.TemporaryDirectory() as tmp:
  591. root = Path(tmp)
  592. collector, source, bmc = self.build_fixture(root)
  593. original = (root / "combined-rx.raw").read_bytes()
  594. frames, remainder = decode_stream(original)
  595. self.assertEqual(remainder, b"")
  596. ready_length = len(frames[0].raw)
  597. formal_tail = original[ready_length:]
  598. old_ready = encode_frame(
  599. profile_id=3,
  600. frame_type=FrameType.READY,
  601. seq=1,
  602. timestamp_tick=249999,
  603. payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
  604. )
  605. corrupt_ready = bytearray(old_ready)
  606. corrupt_ready[-1] ^= 1
  607. pre_ready = bytes(corrupt_ready) + old_ready
  608. matching_ready = b"".join(
  609. encode_frame(
  610. profile_id=3,
  611. frame_type=FrameType.READY,
  612. seq=1,
  613. timestamp_tick=250000 + announcement,
  614. payload=bytes([3])
  615. + int("1234ABCD", 16).to_bytes(4, "little")
  616. + bytes([1, announcement]),
  617. )
  618. for announcement in (0, 1, 2)
  619. )
  620. formal = matching_ready + formal_tail
  621. (root / "pre-ready-uart.raw").write_bytes(pre_ready)
  622. (root / "combined-rx.raw").write_bytes(formal)
  623. collector["artifact_hashes"]["pre-ready-uart.raw"] = hashlib.sha256(pre_ready).hexdigest()
  624. collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(formal).hexdigest()
  625. collector["startup_ready"] = {"epoch_start_offset": len(pre_ready)}
  626. evidence = validator.validate_evidence_directory(
  627. collector_dir=root,
  628. collector=collector,
  629. program=program_receipt(),
  630. source_manifest=source,
  631. programmer_receipt_path="programmer/program-sram-receipt.json",
  632. programmer_receipt_sha256="c" * 64,
  633. bmc_replay_receipt_path=bmc,
  634. )
  635. self.assertEqual(evidence["status"], "pass", evidence["blockers"])
  636. self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 3)
  637. self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
  638. self.assertEqual(evidence["startup_ready"]["epoch_start_offset"], len(pre_ready))
  639. self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
  640. def test_raw_corruption_sequence_gap_and_manifest_hash_mismatch_fail_closed(self) -> None:
  641. validator = load_validator()
  642. cases = (
  643. "corrupt_crc",
  644. "command_seq",
  645. "manifest_hash",
  646. "pre_ready_acks",
  647. "bmc_provenance",
  648. "malformed_bmc_counts",
  649. "stale_bmc_session",
  650. )
  651. for name in cases:
  652. with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
  653. root = Path(tmp)
  654. collector, source, bmc = self.build_fixture(root)
  655. if name == "corrupt_crc":
  656. raw = bytearray((root / "combined-rx.raw").read_bytes())
  657. raw[-1] ^= 1
  658. (root / "combined-rx.raw").write_bytes(raw)
  659. elif name == "command_seq":
  660. from binary921 import CommandId, build_host_command
  661. wire = (root / "host-command-wire.bin").read_bytes()
  662. first_len = 19
  663. replacement = build_host_command(seq=2, command=CommandId.SET_PTC, channel=1, percent=10, profile_id=3)
  664. (root / "host-command-wire.bin").write_bytes(replacement + wire[first_len:])
  665. elif name == "pre_ready_acks":
  666. from binary921 import FrameType, decode_stream
  667. raw = (root / "combined-rx.raw").read_bytes()
  668. frames, remainder = decode_stream(raw)
  669. self.assertEqual(remainder, b"")
  670. ready_len = len(frames[0].raw)
  671. ack_len = sum(len(frame.raw) for frame in frames[1:13])
  672. ready = raw[:ready_len]
  673. acks = raw[ready_len : ready_len + ack_len]
  674. tail = raw[ready_len + ack_len :]
  675. (root / "combined-rx.raw").write_bytes(acks + ready + tail)
  676. collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(acks + ready + tail).hexdigest()
  677. elif name == "bmc_provenance":
  678. receipt = json.loads(bmc.read_text(encoding="utf-8"))
  679. receipt["payload_hex"][0] = "20"
  680. bmc.write_text(json.dumps(receipt), encoding="utf-8")
  681. elif name == "stale_bmc_session":
  682. receipt = json.loads(bmc.read_text(encoding="utf-8"))
  683. receipt["last_reply_at"] = "2026-07-10T09:59:58Z"
  684. bmc.write_text(json.dumps(receipt), encoding="utf-8")
  685. elif name == "malformed_bmc_counts":
  686. receipt = json.loads(bmc.read_text(encoding="utf-8"))
  687. receipt["matched_poll_count"] = "not-a-number"
  688. receipt["reply_count"] = {"truncated": True}
  689. bmc.write_text(json.dumps(receipt), encoding="utf-8")
  690. else:
  691. collector["artifact_hashes"]["combined-rx.raw"] = "0" * 64
  692. evidence = validator.validate_evidence_directory(
  693. collector_dir=root,
  694. collector=collector,
  695. program=program_receipt(),
  696. source_manifest=source,
  697. programmer_receipt_path="programmer/program-sram-receipt.json",
  698. programmer_receipt_sha256="c" * 64,
  699. bmc_replay_receipt_path=bmc,
  700. )
  701. self.assertEqual(evidence["status"], "fail")
  702. self.assertTrue(evidence["blockers"])
  703. class TestProd2UP4Validator(unittest.TestCase):
  704. @staticmethod
  705. def qualification_fixture() -> dict:
  706. def layer(status: str, **artifacts: dict) -> dict:
  707. return {"status": status, "artifacts": artifacts}
  708. return {
  709. "schema": "prod2u-p4-static-qualification-v1",
  710. "status": "pass",
  711. "profile": "prod2u-fan-tach-binary921-v2",
  712. "profile_id": 4,
  713. "layers": {
  714. "source": layer(
  715. "pass",
  716. normal_source_manifest={"path": "normal-source.json", "sha256": "b" * 64},
  717. trace_source_manifest={"path": "trace-source.json", "sha256": "b" * 64},
  718. ),
  719. "protocol": layer("pass", protocol_junit={"path": "protocol.xml", "sha256": "4" * 64}),
  720. "rtl": layer("pass", rtl_sim_receipt={"path": "rtl.json", "sha256": "5" * 64}),
  721. "formal": layer("pass", formal_receipt={"path": "formal.json", "sha256": "6" * 64}),
  722. "td_normal": layer("pass", normal_td_receipt={"path": "normal-td.json", "sha256": "1" * 64}),
  723. "td_trace": layer("pass", trace_td_receipt={"path": "trace-td.json", "sha256": "1" * 64}),
  724. "package": layer(
  725. "pass",
  726. package_manifest={"path": "manifest.json", "sha256": "2" * 64},
  727. package_inventory={"path": "inventory.json", "sha256": "3" * 64},
  728. static_receipt={"path": "static.json", "sha256": "7" * 64},
  729. ),
  730. },
  731. "variants": {},
  732. "failures": [],
  733. }
  734. @staticmethod
  735. def round_fixture(round_number: int, *, identity: dict | None = None) -> dict:
  736. identity = identity or {
  737. "dut_id": "DUT-P4-01",
  738. "build_id": "P4BUILD01",
  739. "bitstream_sha256": "a" * 64,
  740. "profile": "prod2u-p4",
  741. }
  742. variant = "trace" if round_number <= 5 else "normal"
  743. identity = {
  744. **identity,
  745. "variant": variant,
  746. "source_manifest_sha256": identity.get("source_manifest_sha256", "b" * 64),
  747. }
  748. rpm_by_setting = {0: 1200, 20: 1400, 40: 1600, 60: 1900, 80: 2200, 100: 2400}
  749. windows = []
  750. raw_samples = []
  751. snapshot_seq = 100
  752. window_index = 0
  753. for setting in (0, 20, 40, 60, 80, 100):
  754. for _ in range(2):
  755. windows.append(
  756. {
  757. "index": window_index,
  758. "start_s": window_index,
  759. "end_s": window_index + 1,
  760. "continuous": True,
  761. "snapshot_seq": snapshot_seq,
  762. "overflow_mask": 0,
  763. }
  764. )
  765. snapshot_seq += 1
  766. window_index += 1
  767. for sample_index in range(5):
  768. windows.append(
  769. {
  770. "index": window_index,
  771. "start_s": window_index,
  772. "end_s": window_index + 1,
  773. "continuous": True,
  774. "snapshot_seq": snapshot_seq,
  775. "overflow_mask": 0,
  776. }
  777. )
  778. raw_samples.append(
  779. {
  780. "fan_setting_percent": setting,
  781. "snapshot_seq": snapshot_seq,
  782. "overflow_mask": 0,
  783. "FG5": {
  784. "window_edges": 1 if setting in (80, 100) else 0,
  785. "rpm": rpm_by_setting[setting],
  786. },
  787. "FG6": {
  788. "window_edges": 1 if setting == 80 and sample_index == 0 else 0,
  789. "rpm": rpm_by_setting[setting] if setting == 80 and sample_index == 0 else 0,
  790. },
  791. }
  792. )
  793. snapshot_seq += 1
  794. window_index += 1
  795. return {
  796. "round": round_number,
  797. "identity": identity,
  798. "layers": {
  799. "required": {
  800. name: "pass"
  801. for name in (
  802. "program_sram",
  803. "fresh_ready",
  804. "host_ack",
  805. "pwm_state",
  806. "fan3_tach_trend",
  807. "timeout_fallback",
  808. "disable",
  809. "ptc_command_path",
  810. )
  811. },
  812. "optional": {
  813. "rtl_replay": "not_run",
  814. "td_elaboration": "not_run",
  815. "uart_strict_receipt": "not_run",
  816. },
  817. },
  818. "fan": {
  819. "FAN3": {
  820. "FG5": "detected",
  821. "FG6": "intermittent",
  822. }
  823. },
  824. "windows": windows,
  825. "raw_samples": raw_samples,
  826. "correlation": {
  827. "samples": [
  828. {"fan_setting_percent": setting, "rpm": rpm}
  829. for setting, rpm in ((0, 1200), (20, 1400), (40, 1600), (60, 1900), (80, 2200), (100, 2400))
  830. ],
  831. "spearman_rho": 1.0,
  832. "low_mean_rpm": 1500,
  833. "high_mean_rpm": 2300,
  834. "high_significantly_higher": True,
  835. },
  836. "rpm": {"status": "not_qualified", "reason": "FG input is not a qualified RPM measurement"},
  837. "ptc": {"actuation": True, "measurement": "not_run"},
  838. "evidence_binding": {
  839. "programmer_receipt": {
  840. "path": "round/programmer/program-sram-receipt.json",
  841. "sha256": "c" * 64,
  842. "status": "pass",
  843. },
  844. "pre_program_raw": {"path": "round/pre-program.raw", "sha256": "d" * 64},
  845. "combined_rx_raw": {"path": "round/combined-rx.raw", "sha256": "e" * 64},
  846. "raw_transcript": {"path": "round/wire-transcript.json", "sha256": "f" * 64},
  847. "td_receipt": {"path": f"{variant}-td.json", "sha256": "1" * 64},
  848. "source_manifest": {"path": f"{variant}-source-manifest.json", "sha256": identity["source_manifest_sha256"]},
  849. "package_manifest": {"path": "manifest.json", "sha256": "2" * 64},
  850. "package_inventory": {"path": "sha256-inventory.json", "sha256": "3" * 64},
  851. "identity": dict(identity),
  852. },
  853. }
  854. @classmethod
  855. def campaign_fixture(cls) -> dict:
  856. identity = {
  857. "dut_id": "DUT-P4-01",
  858. "build_id": "P4BUILD01",
  859. "bitstream_sha256": "a" * 64,
  860. "profile": "prod2u-p4",
  861. }
  862. return {
  863. "schema": "prod2u-p4-campaign-v2",
  864. "campaign_id": "P4-20260712-01",
  865. "campaign_identity": {**identity, "planned_rounds": 10},
  866. "bmc": {"status": "out_of_scope", "reason": "BMC capture is not part of P4 offline evidence"},
  867. "qualification": cls.qualification_fixture(),
  868. "rounds": [cls.round_fixture(index, identity=identity) for index in range(1, 11)],
  869. "evidence_bindings": [
  870. {"round": index, "evidence_binding": cls.round_fixture(index, identity=identity)["evidence_binding"]}
  871. for index in range(1, 11)
  872. ],
  873. }
  874. def test_valid_ten_round_campaign_is_accepted_and_bmc_is_out_of_scope(self) -> None:
  875. validator = load_p4_validator()
  876. result = validator.validate_campaign(self.campaign_fixture())
  877. self.assertEqual(result["status"], "pass", result["failures"])
  878. self.assertEqual(result["campaign_id"], "P4-20260712-01")
  879. self.assertEqual(result["round_count"], 10)
  880. self.assertEqual(result["bmc"], "out_of_scope")
  881. def test_campaign_requires_all_static_qualification_layers(self) -> None:
  882. validator = load_p4_validator()
  883. fixture = self.campaign_fixture()
  884. del fixture["qualification"]["layers"]["formal"]
  885. result = validator.validate_campaign(fixture)
  886. self.assertEqual(result["status"], "fail")
  887. self.assertIn("static_layer_missing:formal", result["failures"])
  888. def test_campaign_rejects_static_and_dynamic_artifact_cross_binding_mismatch(self) -> None:
  889. validator = load_p4_validator()
  890. fixture = self.campaign_fixture()
  891. fixture["qualification"]["layers"]["package"]["artifacts"]["package_inventory"]["sha256"] = "9" * 64
  892. result = validator.validate_campaign(fixture)
  893. self.assertEqual(result["status"], "fail")
  894. self.assertIn("qualification_binding_mismatch:1:package_inventory", result["failures"])
  895. def test_required_layers_must_pass_but_optional_layers_may_be_not_run(self) -> None:
  896. validator = load_p4_validator()
  897. fixture = self.campaign_fixture()
  898. fixture["rounds"][0]["layers"]["required"]["program_sram"] = "not_run"
  899. result = validator.validate_campaign(fixture)
  900. self.assertEqual(result["status"], "fail")
  901. self.assertIn("required_layer_not_pass:1:program_sram", result["failures"])
  902. def test_campaign_requires_contiguous_rounds_and_identical_identity(self) -> None:
  903. validator = load_p4_validator()
  904. fixture = self.campaign_fixture()
  905. fixture["rounds"][4]["round"] = 6
  906. fixture["rounds"][5]["identity"]["build_id"] = "OTHERBUILD"
  907. result = validator.validate_campaign(fixture)
  908. self.assertEqual(result["status"], "fail")
  909. self.assertIn("round_sequence_not_1_to_10", result["failures"])
  910. self.assertIn("identity_mismatch:6:build_id", result["failures"])
  911. def test_fan_statuses_window_continuity_and_ptc_rpm_boundaries_are_checked(self) -> None:
  912. validator = load_p4_validator()
  913. fixture = self.campaign_fixture()
  914. fixture["rounds"][0]["fan"]["FAN3"]["FG5"] = "unknown"
  915. fixture["rounds"][1]["windows"][2]["start_s"] = 99
  916. fixture["rounds"][2]["rpm"]["status"] = "qualified"
  917. fixture["rounds"][3]["ptc"]["measurement"] = "pass"
  918. result = validator.validate_campaign(fixture)
  919. self.assertEqual(result["status"], "fail")
  920. self.assertIn("invalid_fan_status:1:FAN3:FG5", result["failures"])
  921. self.assertIn("window_not_continuous:2", result["failures"])
  922. self.assertIn("rpm_not_qualified:3", result["failures"])
  923. self.assertIn("ptc_measurement_must_be_not_run:4", result["failures"])
  924. def test_correlation_requires_spearman_threshold_and_high_setting_margin(self) -> None:
  925. validator = load_p4_validator()
  926. fixture = self.campaign_fixture()
  927. fixture["rounds"][0]["correlation"]["spearman_rho"] = 0.59
  928. fixture["rounds"][1]["correlation"]["high_mean_rpm"] = 1300
  929. result = validator.validate_campaign(fixture)
  930. self.assertEqual(result["status"], "fail")
  931. self.assertIn("spearman_declared_mismatch:1", result["failures"])
  932. self.assertIn("high_setting_mean_mismatch:2", result["failures"])
  933. def test_direct_evidence_requires_identity_fields_and_checks_computed_spearman(self) -> None:
  934. validator = load_p4_validator()
  935. round_data = self.round_fixture(1)
  936. evidence = {
  937. "schema": "prod2u-p4-evidence-v2",
  938. "evidence_id": "P4-20260712-01-R01",
  939. "campaign_id": "P4-20260712-01",
  940. "campaign_identity": {**round_data["identity"], "planned_rounds": 10},
  941. "bmc": {"status": "out_of_scope", "reason": "offline"},
  942. **round_data,
  943. }
  944. evidence["correlation"]["samples"] = [
  945. {"fan_setting_percent": setting, "rpm": rpm}
  946. for setting, rpm in ((20, 1000), (40, 1500), (60, 2100), (80, 2800))
  947. ]
  948. evidence["correlation"]["spearman_rho"] = 1.0
  949. del evidence["campaign_id"]
  950. result = validator.validate_evidence(evidence)
  951. self.assertEqual(result["status"], "fail")
  952. self.assertIn("missing_required:evidence:campaign_id", result["failures"])
  953. def test_final_gate_rejects_missing_status_even_when_layers_are_valid(self) -> None:
  954. validator = load_p4_validator()
  955. gate = {
  956. "schema": "prod2u-p4-final-gate-v2",
  957. "campaign_id": "P4-20260712-01",
  958. "bmc": {"status": "out_of_scope", "reason": "offline"},
  959. "layers": {"required": {"software_model": "pass"}, "optional": {}},
  960. "round_count": 10,
  961. "failures": [],
  962. }
  963. result = validator.validate_final_gate(gate)
  964. self.assertEqual(result["status"], "fail")
  965. self.assertIn("missing_required:final_gate:status", result["failures"])
  966. def test_schema_files_describe_the_three_v2_documents(self) -> None:
  967. for name, schema_id in (
  968. ("prod2u_p4_evidence.schema.json", "prod2u-p4-evidence-v2"),
  969. ("prod2u_p4_final_gate.schema.json", "prod2u-p4-final-gate-v2"),
  970. ("prod2u_p4_campaign.schema.json", "prod2u-p4-campaign-v2"),
  971. ):
  972. with self.subTest(name=name):
  973. schema = json.loads((ROOT / "schemas" / name).read_text(encoding="utf-8"))
  974. self.assertEqual(schema["$id"], schema_id)
  975. def load_p4_validator():
  976. validator_path = ROOT / "tools" / "prod2u_p4_validate.py"
  977. if not validator_path.is_file():
  978. raise AssertionError(f"missing v2 validator: {validator_path}")
  979. spec = importlib.util.spec_from_file_location("prod2u_p4_validate_test", validator_path)
  980. if spec is None or spec.loader is None:
  981. raise AssertionError("unable to load Prod2U P4 validator")
  982. module = importlib.util.module_from_spec(spec)
  983. spec.loader.exec_module(module)
  984. return module
  985. if __name__ == "__main__":
  986. unittest.main()