| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089 |
- #!/usr/bin/env python3
- """TDD coverage for raw-first Prod2U evidence validation."""
- from __future__ import annotations
- import hashlib
- import importlib.util
- import json
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- from types import SimpleNamespace
- from unittest import mock
- import jsonschema
- ROOT = Path(__file__).resolve().parents[2]
- VALIDATOR = ROOT / "tools" / "prod2u_validate.py"
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- def load_validator():
- if not VALIDATOR.is_file():
- raise AssertionError(f"missing validator: {VALIDATOR}")
- spec = importlib.util.spec_from_file_location("prod2u_validate_test", VALIDATOR)
- if spec is None or spec.loader is None:
- raise AssertionError("unable to load Prod2U validator")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- def program_receipt() -> dict:
- build_id = "1234ABCD"
- return {
- "schema": "prod2u-program-sram-receipt-v1",
- "status": "pass",
- "request": {
- "operation": "PROGRAM_SRAM",
- "target_chip": "EF2L45",
- "cable_index": 0,
- "speed_code": 2,
- "speed_hz": 200000,
- "attempt_limit": 1,
- "power_cycle_allowed": False,
- },
- "bitstream": {"path": f"C:/P2U/{build_id}/fw.bit", "sha256": "a" * 64, "build_id": build_id},
- "staging": {
- "expected_path": f"C:/P2U/{build_id}/fw.bit",
- "observed_path": f"C:/P2U/{build_id}/fw.bit",
- "matches_expected_path": True,
- },
- "execution": {
- "exit_code": 0,
- "timed_out": False,
- "attempt_count": 1,
- "retry_count": 0,
- "power_cycle_count": 0,
- "command_execution_attempted": True,
- "timeout_seconds": 60,
- "started_at": "2026-07-10T10:00:00Z",
- "finished_at": "2026-07-10T10:00:02Z",
- "duration_seconds": 2.0,
- },
- "parser": {
- "status": "pass",
- "exit_code_trusted": False,
- "ordered_markers": [
- "download_start",
- "chip_validation",
- "bit_to_vec_start",
- "bit_to_vec_finish",
- "program_start",
- "program_finish",
- "download_finish",
- ],
- "ordered_markers_complete": True,
- "observed_markers": [
- "download_start",
- "chip_validation",
- "bit_to_vec_start",
- "bit_to_vec_finish",
- "program_start",
- "program_finish",
- "download_finish",
- ],
- "observed_marker_lines": [1, 2, 3, 4, 5, 6, 7],
- "error_markers": [],
- "failures": [],
- "transcript_sha256": "9" * 64,
- },
- "tool": {"path": "C:/TD/bin/bw_commands_prompt.exe", "td_root": "C:/TD", "td_bin": "C:/TD/bin"},
- "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
- "process_cleanup": {"status": "pass", "td_root": "C:/TD", "wait_seconds": 5.0, "remaining": []},
- "artifacts": {
- "tcl": {"path": "program-sram.tcl", "size": 1, "sha256": "1" * 64},
- "stdout": {"path": "bitwriter-stdout.log", "size": 1, "sha256": "2" * 64},
- "stderr": {"path": "bitwriter-stderr.log", "size": 1, "sha256": "3" * 64},
- "log_delta": {"path": "bitwriter-log-delta.log", "size": 1, "sha256": "4" * 64},
- "log_delta_sources": [
- {
- "path": "C:/TD/log/bw_test.log",
- "start_offset": 0,
- "byte_count": 1,
- "sha256": "8" * 64,
- }
- ],
- },
- "safety": {
- "flash_attempted": False,
- "programs_nonvolatile": False,
- "power_cycle_attempted": False,
- "driver_install_attempted": False,
- "toggles_dtr_rts": False,
- "real_ptc_fan_action_attempted": False,
- "external_programming_command_executed": True,
- },
- }
- class Prod2UValidatorTests(unittest.TestCase):
- def build_fixture(self, root: Path) -> tuple[dict, dict, Path]:
- import prod2u_collector as collector
- from binary921 import CommandId, FrameType, build_host_command, encode_frame
- profile_id = 3
- build_id = "1234ABCD"
- command_wire = b"".join(
- build_host_command(
- seq=index,
- command=command,
- channel=channel,
- percent=percent,
- profile_id=profile_id,
- )
- for index, (_, command, channel, percent) in enumerate(collector.COMMAND_SEQUENCE, start=1)
- )
- ready = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000,
- payload=bytes([profile_id]) + int(build_id, 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- acks = b"".join(
- encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.HOST_ACK,
- seq=index,
- timestamp_tick=0,
- payload=bytes([1, command, 0, 0, 0x34, 0x12]),
- )
- for index, (_, command, _, _) in enumerate(collector.COMMAND_SEQUENCE, start=1)
- )
- bmc_payload_bytes = bytes([0x1E, 0x4B] + [0xFF] * 22 + [0x20, 0x19] + [0xFF] * 22)
- bmc_checksum = sum(bmc_payload_bytes) & 0xFFFF
- bmc = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.BMC_PAYLOAD,
- seq=30,
- timestamp_tick=0,
- payload=bytes(
- [48, 48, 1, 0, bmc_payload_bytes[0], bmc_payload_bytes[-1], bmc_checksum & 0xFF, bmc_checksum >> 8]
- ),
- )
- sensor = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.SENSOR_CACHE,
- seq=31,
- timestamp_tick=0,
- payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
- )
- snapshot = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.MODULE_SNAPSHOT,
- seq=32,
- timestamp_tick=0,
- payload=bytes(
- [
- profile_id,
- 0,
- 12,
- 0,
- 0x1E,
- 0xFF,
- 0x08,
- 0x14,
- CommandId.DISABLE,
- 0,
- 0,
- 0,
- 0,
- 1,
- 2,
- 22,
- 0,
- 0,
- 30,
- 30,
- 0,
- 0x0F,
- 0,
- 0,
- ]
- ),
- )
- combined = ready + acks + bmc + sensor + snapshot
- (root / "combined-rx.raw").write_bytes(combined)
- (root / "host-command-wire.bin").write_bytes(command_wire)
- collector_manifest = {
- "schema": "prod2u-collector-manifest-v1",
- "status": "pass",
- "artifact_hashes": {
- "combined-rx.raw": hashlib.sha256(combined).hexdigest(),
- "host-command-wire.bin": hashlib.sha256(command_wire).hexdigest(),
- },
- "safety": {
- "flash_attempted": False,
- "programs_nonvolatile": False,
- "driver_install_attempted": False,
- "toggles_dtr_rts": False,
- },
- }
- source_manifest = {
- "schema": "prod2u-source-manifest-v1",
- "profile": "prod2u-bmc-replay-binary921",
- "source_manifest_sha256": "1234abcd" + "b" * 56,
- "build_id": build_id,
- }
- bmc_receipt = root / "bmc-replay-session.json"
- bmc_receipt.write_text(
- json.dumps(
- {
- "schema": "prod2u-bmc-replay-session-v1",
- "status": "pass",
- "bmc_source": "pc_replay_from_real_bmc_capture",
- "reply_sha256": hashlib.sha256(
- (" ".join(f"{value:02x}" for value in bmc_payload_bytes) + "\r\n").encode("ascii")
- ).hexdigest(),
- "payload_hex": [f"{value:02x}" for value in bmc_payload_bytes],
- "byte_count": 48,
- "valid_count": 2,
- "missing_count": 22,
- "matched_poll_count": 1,
- "reply_count": 1,
- "started_at": "2026-07-10T09:59:59Z",
- "last_reply_at": "2026-07-10T10:00:01Z",
- }
- ),
- encoding="utf-8",
- )
- return collector_manifest, source_manifest, bmc_receipt
- def test_raw_first_validator_passes_complete_software_chain(self) -> None:
- validator = load_validator()
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["build_id"], "1234ABCD")
- self.assertEqual(evidence["host_command_count"], 12)
- self.assertEqual(evidence["host_ack_matched_count"], 12)
- self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["valid_count"], 2)
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["missing_count"], 22)
- self.assertEqual(evidence["raw_validation"]["timeout_fallback"]["status"], "pass")
- def test_missing_bmc_replay_receipt_remains_schema_valid_blocked_evidence(self) -> None:
- validator = load_validator()
- schema = json.loads(
- (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
- )
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- bmc.unlink()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
- self.assertEqual(
- evidence["bmc_replay"],
- {
- "status": "not_run",
- "bmc_source": "not_run",
- "payload_sha256": None,
- },
- )
- jsonschema.validate(evidence, schema)
- def test_missing_bmc_uart_frames_are_not_independent_failures_when_replay_was_not_run(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- frames, remainder = decode_stream((root / "combined-rx.raw").read_bytes())
- self.assertEqual(remainder, b"")
- combined = b"".join(
- frame.raw
- for frame in frames
- if frame.frame_type not in (FrameType.BMC_PAYLOAD, FrameType.SENSOR_CACHE)
- )
- (root / "combined-rx.raw").write_bytes(combined)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
- bmc.unlink()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
- self.assertEqual(evidence["blockers"], ["bmc_replay_not_pass"])
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["status"], "not_run")
- def test_invalid_bmc_replay_receipt_remains_schema_valid_failed_evidence(self) -> None:
- validator = load_validator()
- schema = json.loads(
- (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
- )
- for invalid_payload in ("{", "[]"):
- with self.subTest(invalid_payload=invalid_payload), tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- bmc.write_text(invalid_payload, encoding="utf-8")
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertEqual(evidence["bmc_replay"]["bmc_source"], "not_run")
- self.assertIsNone(evidence["bmc_replay"]["payload_sha256"])
- jsonschema.validate(evidence, schema)
- def test_ready_epoch_selects_last_matching_ready_in_the_post_callback_stream(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- combined = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(combined)
- self.assertEqual(remainder, b"")
- first_ready_len = len(frames[0].raw)
- later_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250001,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, 2]),
- )
- combined = combined[:first_ready_len] + later_ready + combined[first_ready_len:]
- (root / "combined-rx.raw").write_bytes(combined)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
- self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 2)
- self.assertEqual(evidence["startup_ready"]["selection_policy"], "last_matching_ready")
- def test_collector_wait_selects_last_matching_ready_from_one_buffered_chunk(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- ready_frames = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 2)
- )
- class BufferedSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- result = collector.wait_for_ready(
- BufferedSerial(ready_frames),
- timeout_sec=0.05,
- expected_profile_id=3,
- expected_build_id="1234ABCD",
- expected_epoch=1,
- expected_por_reason=1,
- max_announcement_seq=2,
- )
- self.assertEqual(result["status"], "pass")
- self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
- self.assertEqual(result["matching_ready_count"], 2)
- self.assertEqual(result["selection_policy"], "last_matching_ready")
- def test_collector_splits_corrupt_and_old_build_bytes_before_three_matching_ready_frames(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- pre_ready = bytes(corrupt_ready) + old_ready
- stream = pre_ready + matching_ready
- class BufferedSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- result = collector.wait_for_ready(
- BufferedSerial(stream),
- timeout_sec=0.05,
- expected_profile_id=3,
- expected_build_id="1234ABCD",
- expected_epoch=1,
- expected_por_reason=1,
- max_announcement_seq=2,
- )
- self.assertEqual(result["status"], "pass")
- self.assertEqual(result["raw"], stream)
- self.assertEqual(result["pre_ready_raw"], pre_ready)
- self.assertEqual(result["epoch_start_offset"], len(pre_ready))
- self.assertEqual(result["epoch_raw"], matching_ready)
- self.assertEqual(result["matching_ready_count"], 3)
- self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
- def test_combined_collector_writes_pre_ready_diagnostics_and_formal_epoch_separately(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- pre_ready = bytes(corrupt_ready) + old_ready
- class FakeSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- self.closed = False
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- def write(self, payload: bytes) -> int:
- return len(payload)
- def flush(self) -> None:
- return None
- def close(self) -> None:
- self.closed = True
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- endpoint = FakeSerial(pre_ready + matching_ready)
- args = SimpleNamespace(
- output_dir=str(root),
- profile="prod2u-bmc-replay-binary921",
- transport="combined-single-com",
- combined_port="COM5",
- host_port="",
- expected_build_id="1234ABCD",
- expected_epoch=1,
- ready_timeout_sec=0.05,
- ack_window_sec=0.0,
- duration_sec=0.0,
- bmc_replay_receipt="",
- )
- with mock.patch.object(collector, "_open_serial", return_value=endpoint):
- manifest = collector.collect_live(args)
- self.assertTrue(endpoint.closed)
- self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), pre_ready)
- self.assertEqual((root / "combined-rx.raw").read_bytes(), matching_ready)
- self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), pre_ready + matching_ready)
- preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
- self.assertEqual(preflight["epoch_start_offset"], len(pre_ready))
- self.assertEqual(manifest["startup_ready"]["matching_ready_count"], 3)
- self.assertEqual(
- manifest["artifact_hashes"]["combined-rx.raw"],
- hashlib.sha256(matching_ready).hexdigest(),
- )
- self.assertEqual(
- manifest["artifact_hashes"]["pre-ready-uart.raw"],
- hashlib.sha256(pre_ready).hexdigest(),
- )
- def test_ready_timeout_preserves_diagnostics_without_creating_a_formal_epoch(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- observed = bytes(corrupt_ready) + old_ready
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- manifest = collector.write_blocked_manifest(
- root,
- profile="prod2u-bmc-replay-binary921",
- status="blocked_waiting_for_binary921_ready",
- startup_raw=observed,
- startup_frames=[],
- error="build_mismatch",
- timeout_evidence={"status": "blocked_waiting_for_binary921_ready"},
- )
- self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), observed)
- self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), observed)
- self.assertEqual((root / "combined-rx.raw").read_bytes(), b"")
- preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
- self.assertIsNone(preflight["epoch_start_offset"])
- self.assertEqual(
- manifest["artifact_hashes"]["pre-ready-uart.raw"],
- hashlib.sha256(observed).hexdigest(),
- )
- def test_validator_rejects_formal_combined_rx_that_starts_before_matching_ready_epoch(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- combined = (root / "combined-rx.raw").read_bytes()
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- contaminated = old_ready + combined
- (root / "combined-rx.raw").write_bytes(contaminated)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(contaminated).hexdigest()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertIn("formal_epoch_does_not_start_at_matching_ready", evidence["blockers"])
- def test_validator_strictly_decodes_post_epoch_artifact_and_ignores_pre_ready_diagnostics(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- original = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(original)
- self.assertEqual(remainder, b"")
- ready_length = len(frames[0].raw)
- formal_tail = original[ready_length:]
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- pre_ready = bytes(corrupt_ready) + old_ready
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3])
- + int("1234ABCD", 16).to_bytes(4, "little")
- + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- formal = matching_ready + formal_tail
- (root / "pre-ready-uart.raw").write_bytes(pre_ready)
- (root / "combined-rx.raw").write_bytes(formal)
- collector["artifact_hashes"]["pre-ready-uart.raw"] = hashlib.sha256(pre_ready).hexdigest()
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(formal).hexdigest()
- collector["startup_ready"] = {"epoch_start_offset": len(pre_ready)}
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 3)
- self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
- self.assertEqual(evidence["startup_ready"]["epoch_start_offset"], len(pre_ready))
- self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
- def test_raw_corruption_sequence_gap_and_manifest_hash_mismatch_fail_closed(self) -> None:
- validator = load_validator()
- cases = (
- "corrupt_crc",
- "command_seq",
- "manifest_hash",
- "pre_ready_acks",
- "bmc_provenance",
- "malformed_bmc_counts",
- "stale_bmc_session",
- )
- for name in cases:
- with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- if name == "corrupt_crc":
- raw = bytearray((root / "combined-rx.raw").read_bytes())
- raw[-1] ^= 1
- (root / "combined-rx.raw").write_bytes(raw)
- elif name == "command_seq":
- from binary921 import CommandId, build_host_command
- wire = (root / "host-command-wire.bin").read_bytes()
- first_len = 19
- replacement = build_host_command(seq=2, command=CommandId.SET_PTC, channel=1, percent=10, profile_id=3)
- (root / "host-command-wire.bin").write_bytes(replacement + wire[first_len:])
- elif name == "pre_ready_acks":
- from binary921 import FrameType, decode_stream
- raw = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(raw)
- self.assertEqual(remainder, b"")
- ready_len = len(frames[0].raw)
- ack_len = sum(len(frame.raw) for frame in frames[1:13])
- ready = raw[:ready_len]
- acks = raw[ready_len : ready_len + ack_len]
- tail = raw[ready_len + ack_len :]
- (root / "combined-rx.raw").write_bytes(acks + ready + tail)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(acks + ready + tail).hexdigest()
- elif name == "bmc_provenance":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["payload_hex"][0] = "20"
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- elif name == "stale_bmc_session":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["last_reply_at"] = "2026-07-10T09:59:58Z"
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- elif name == "malformed_bmc_counts":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["matched_poll_count"] = "not-a-number"
- receipt["reply_count"] = {"truncated": True}
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- else:
- collector["artifact_hashes"]["combined-rx.raw"] = "0" * 64
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertTrue(evidence["blockers"])
- class TestProd2UP4Validator(unittest.TestCase):
- @staticmethod
- def qualification_fixture() -> dict:
- def layer(status: str, **artifacts: dict) -> dict:
- return {"status": status, "artifacts": artifacts}
- return {
- "schema": "prod2u-p4-static-qualification-v1",
- "status": "pass",
- "profile": "prod2u-fan-tach-binary921-v2",
- "profile_id": 4,
- "layers": {
- "source": layer(
- "pass",
- normal_source_manifest={"path": "normal-source.json", "sha256": "b" * 64},
- trace_source_manifest={"path": "trace-source.json", "sha256": "b" * 64},
- ),
- "protocol": layer("pass", protocol_junit={"path": "protocol.xml", "sha256": "4" * 64}),
- "rtl": layer("pass", rtl_sim_receipt={"path": "rtl.json", "sha256": "5" * 64}),
- "formal": layer("pass", formal_receipt={"path": "formal.json", "sha256": "6" * 64}),
- "td_normal": layer("pass", normal_td_receipt={"path": "normal-td.json", "sha256": "1" * 64}),
- "td_trace": layer("pass", trace_td_receipt={"path": "trace-td.json", "sha256": "1" * 64}),
- "package": layer(
- "pass",
- package_manifest={"path": "manifest.json", "sha256": "2" * 64},
- package_inventory={"path": "inventory.json", "sha256": "3" * 64},
- static_receipt={"path": "static.json", "sha256": "7" * 64},
- ),
- },
- "variants": {},
- "failures": [],
- }
- @staticmethod
- def round_fixture(round_number: int, *, identity: dict | None = None) -> dict:
- identity = identity or {
- "dut_id": "DUT-P4-01",
- "build_id": "P4BUILD01",
- "bitstream_sha256": "a" * 64,
- "profile": "prod2u-p4",
- }
- variant = "trace" if round_number <= 5 else "normal"
- identity = {
- **identity,
- "variant": variant,
- "source_manifest_sha256": identity.get("source_manifest_sha256", "b" * 64),
- }
- rpm_by_setting = {0: 1200, 20: 1400, 40: 1600, 60: 1900, 80: 2200, 100: 2400}
- windows = []
- raw_samples = []
- snapshot_seq = 100
- window_index = 0
- for setting in (0, 20, 40, 60, 80, 100):
- for _ in range(2):
- windows.append(
- {
- "index": window_index,
- "start_s": window_index,
- "end_s": window_index + 1,
- "continuous": True,
- "snapshot_seq": snapshot_seq,
- "overflow_mask": 0,
- }
- )
- snapshot_seq += 1
- window_index += 1
- for sample_index in range(5):
- windows.append(
- {
- "index": window_index,
- "start_s": window_index,
- "end_s": window_index + 1,
- "continuous": True,
- "snapshot_seq": snapshot_seq,
- "overflow_mask": 0,
- }
- )
- raw_samples.append(
- {
- "fan_setting_percent": setting,
- "snapshot_seq": snapshot_seq,
- "overflow_mask": 0,
- "FG5": {
- "window_edges": 1 if setting in (80, 100) else 0,
- "rpm": rpm_by_setting[setting],
- },
- "FG6": {
- "window_edges": 1 if setting == 80 and sample_index == 0 else 0,
- "rpm": rpm_by_setting[setting] if setting == 80 and sample_index == 0 else 0,
- },
- }
- )
- snapshot_seq += 1
- window_index += 1
- return {
- "round": round_number,
- "identity": identity,
- "layers": {
- "required": {
- name: "pass"
- for name in (
- "program_sram",
- "fresh_ready",
- "host_ack",
- "pwm_state",
- "fan3_tach_trend",
- "timeout_fallback",
- "disable",
- "ptc_command_path",
- )
- },
- "optional": {
- "rtl_replay": "not_run",
- "td_elaboration": "not_run",
- "uart_strict_receipt": "not_run",
- },
- },
- "fan": {
- "FAN3": {
- "FG5": "detected",
- "FG6": "intermittent",
- }
- },
- "windows": windows,
- "raw_samples": raw_samples,
- "correlation": {
- "samples": [
- {"fan_setting_percent": setting, "rpm": rpm}
- for setting, rpm in ((0, 1200), (20, 1400), (40, 1600), (60, 1900), (80, 2200), (100, 2400))
- ],
- "spearman_rho": 1.0,
- "low_mean_rpm": 1500,
- "high_mean_rpm": 2300,
- "high_significantly_higher": True,
- },
- "rpm": {"status": "not_qualified", "reason": "FG input is not a qualified RPM measurement"},
- "ptc": {"actuation": True, "measurement": "not_run"},
- "evidence_binding": {
- "programmer_receipt": {
- "path": "round/programmer/program-sram-receipt.json",
- "sha256": "c" * 64,
- "status": "pass",
- },
- "pre_program_raw": {"path": "round/pre-program.raw", "sha256": "d" * 64},
- "combined_rx_raw": {"path": "round/combined-rx.raw", "sha256": "e" * 64},
- "raw_transcript": {"path": "round/wire-transcript.json", "sha256": "f" * 64},
- "td_receipt": {"path": f"{variant}-td.json", "sha256": "1" * 64},
- "source_manifest": {"path": f"{variant}-source-manifest.json", "sha256": identity["source_manifest_sha256"]},
- "package_manifest": {"path": "manifest.json", "sha256": "2" * 64},
- "package_inventory": {"path": "sha256-inventory.json", "sha256": "3" * 64},
- "identity": dict(identity),
- },
- }
- @classmethod
- def campaign_fixture(cls) -> dict:
- identity = {
- "dut_id": "DUT-P4-01",
- "build_id": "P4BUILD01",
- "bitstream_sha256": "a" * 64,
- "profile": "prod2u-p4",
- }
- return {
- "schema": "prod2u-p4-campaign-v2",
- "campaign_id": "P4-20260712-01",
- "campaign_identity": {**identity, "planned_rounds": 10},
- "bmc": {"status": "out_of_scope", "reason": "BMC capture is not part of P4 offline evidence"},
- "qualification": cls.qualification_fixture(),
- "rounds": [cls.round_fixture(index, identity=identity) for index in range(1, 11)],
- "evidence_bindings": [
- {"round": index, "evidence_binding": cls.round_fixture(index, identity=identity)["evidence_binding"]}
- for index in range(1, 11)
- ],
- }
- def test_valid_ten_round_campaign_is_accepted_and_bmc_is_out_of_scope(self) -> None:
- validator = load_p4_validator()
- result = validator.validate_campaign(self.campaign_fixture())
- self.assertEqual(result["status"], "pass", result["failures"])
- self.assertEqual(result["campaign_id"], "P4-20260712-01")
- self.assertEqual(result["round_count"], 10)
- self.assertEqual(result["bmc"], "out_of_scope")
- def test_campaign_requires_all_static_qualification_layers(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- del fixture["qualification"]["layers"]["formal"]
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("static_layer_missing:formal", result["failures"])
- def test_campaign_rejects_static_and_dynamic_artifact_cross_binding_mismatch(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- fixture["qualification"]["layers"]["package"]["artifacts"]["package_inventory"]["sha256"] = "9" * 64
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("qualification_binding_mismatch:1:package_inventory", result["failures"])
- def test_required_layers_must_pass_but_optional_layers_may_be_not_run(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- fixture["rounds"][0]["layers"]["required"]["program_sram"] = "not_run"
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("required_layer_not_pass:1:program_sram", result["failures"])
- def test_campaign_requires_contiguous_rounds_and_identical_identity(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- fixture["rounds"][4]["round"] = 6
- fixture["rounds"][5]["identity"]["build_id"] = "OTHERBUILD"
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("round_sequence_not_1_to_10", result["failures"])
- self.assertIn("identity_mismatch:6:build_id", result["failures"])
- def test_fan_statuses_window_continuity_and_ptc_rpm_boundaries_are_checked(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- fixture["rounds"][0]["fan"]["FAN3"]["FG5"] = "unknown"
- fixture["rounds"][1]["windows"][2]["start_s"] = 99
- fixture["rounds"][2]["rpm"]["status"] = "qualified"
- fixture["rounds"][3]["ptc"]["measurement"] = "pass"
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("invalid_fan_status:1:FAN3:FG5", result["failures"])
- self.assertIn("window_not_continuous:2", result["failures"])
- self.assertIn("rpm_not_qualified:3", result["failures"])
- self.assertIn("ptc_measurement_must_be_not_run:4", result["failures"])
- def test_correlation_requires_spearman_threshold_and_high_setting_margin(self) -> None:
- validator = load_p4_validator()
- fixture = self.campaign_fixture()
- fixture["rounds"][0]["correlation"]["spearman_rho"] = 0.59
- fixture["rounds"][1]["correlation"]["high_mean_rpm"] = 1300
- result = validator.validate_campaign(fixture)
- self.assertEqual(result["status"], "fail")
- self.assertIn("spearman_declared_mismatch:1", result["failures"])
- self.assertIn("high_setting_mean_mismatch:2", result["failures"])
- def test_direct_evidence_requires_identity_fields_and_checks_computed_spearman(self) -> None:
- validator = load_p4_validator()
- round_data = self.round_fixture(1)
- evidence = {
- "schema": "prod2u-p4-evidence-v2",
- "evidence_id": "P4-20260712-01-R01",
- "campaign_id": "P4-20260712-01",
- "campaign_identity": {**round_data["identity"], "planned_rounds": 10},
- "bmc": {"status": "out_of_scope", "reason": "offline"},
- **round_data,
- }
- evidence["correlation"]["samples"] = [
- {"fan_setting_percent": setting, "rpm": rpm}
- for setting, rpm in ((20, 1000), (40, 1500), (60, 2100), (80, 2800))
- ]
- evidence["correlation"]["spearman_rho"] = 1.0
- del evidence["campaign_id"]
- result = validator.validate_evidence(evidence)
- self.assertEqual(result["status"], "fail")
- self.assertIn("missing_required:evidence:campaign_id", result["failures"])
- def test_final_gate_rejects_missing_status_even_when_layers_are_valid(self) -> None:
- validator = load_p4_validator()
- gate = {
- "schema": "prod2u-p4-final-gate-v2",
- "campaign_id": "P4-20260712-01",
- "bmc": {"status": "out_of_scope", "reason": "offline"},
- "layers": {"required": {"software_model": "pass"}, "optional": {}},
- "round_count": 10,
- "failures": [],
- }
- result = validator.validate_final_gate(gate)
- self.assertEqual(result["status"], "fail")
- self.assertIn("missing_required:final_gate:status", result["failures"])
- def test_schema_files_describe_the_three_v2_documents(self) -> None:
- for name, schema_id in (
- ("prod2u_p4_evidence.schema.json", "prod2u-p4-evidence-v2"),
- ("prod2u_p4_final_gate.schema.json", "prod2u-p4-final-gate-v2"),
- ("prod2u_p4_campaign.schema.json", "prod2u-p4-campaign-v2"),
- ):
- with self.subTest(name=name):
- schema = json.loads((ROOT / "schemas" / name).read_text(encoding="utf-8"))
- self.assertEqual(schema["$id"], schema_id)
- def load_p4_validator():
- validator_path = ROOT / "tools" / "prod2u_p4_validate.py"
- if not validator_path.is_file():
- raise AssertionError(f"missing v2 validator: {validator_path}")
- spec = importlib.util.spec_from_file_location("prod2u_p4_validate_test", validator_path)
- if spec is None or spec.loader is None:
- raise AssertionError("unable to load Prod2U P4 validator")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- if __name__ == "__main__":
- unittest.main()
|