test_prod2u_p4_harness.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  1. #!/usr/bin/env python3
  2. """Focused contracts for the minimal Normal-v3 verification harness."""
  3. from __future__ import annotations
  4. import argparse
  5. import copy
  6. import hashlib
  7. import json
  8. import re
  9. import subprocess
  10. import tempfile
  11. import unittest
  12. from pathlib import Path
  13. from unittest import mock
  14. ROOT = Path(__file__).resolve().parents[2]
  15. import sys
  16. sys.path.insert(0, str(ROOT / "tools"))
  17. import prod2u_p4_harness as harness # noqa: E402
  18. EXPECTED_SOURCES = (
  19. "src/rtl/uart_rx_8n1.v",
  20. "src/rtl/uart_tx_8n1.v",
  21. "src/rtl/binary921_crc16.v",
  22. "src/rtl/binary921_frame_tx.v",
  23. "src/rtl/prod2u_por.v",
  24. "src/rtl/prod2u_p4_us_tick.v",
  25. "src/rtl/prod2u_p4_normal_v3_rx.v",
  26. "src/rtl/prod2u_p4_normal_v3_output_state.v",
  27. "src/rtl/prod2u_p4_normal_v3_watchdog.v",
  28. "src/rtl/prod2u_p4_axis_executor.v",
  29. "src/rtl/prod2u_p4_motor_hub.v",
  30. "src/rtl/prod2u_p4_response_scheduler.v",
  31. "src/rtl/prod2u_p4_normal_v3_tx.v",
  32. "src/rtl/prod2u_p4_pwm_outputs.v",
  33. "src/rtl/prod2u_p4_normal_v3_core.v",
  34. "src/top/prod2u_p4_normal_v3_top.v",
  35. )
  36. REQUIRED_MOTOR_LIMIT_PINS = {
  37. "motor_en_n": {"location": "A10", "direction": "OUTPUT", "pull_type": "NONE"},
  38. "x_step": {"location": "C11", "direction": "OUTPUT", "pull_type": "NONE"},
  39. "x_dir": {"location": "B12", "direction": "OUTPUT", "pull_type": "NONE"},
  40. "y_step": {"location": "D15", "direction": "OUTPUT", "pull_type": "NONE"},
  41. "y_dir": {"location": "H14", "direction": "OUTPUT", "pull_type": "NONE"},
  42. "x_limit_raw": {"location": "B9", "direction": "INPUT", "pull_type": "PULLUP"},
  43. "y_limit_raw": {"location": "A11", "direction": "INPUT", "pull_type": "PULLUP"},
  44. }
  45. UART_ONLY_CDC_REGISTERS = frozenset(
  46. {
  47. "u_uart_rx/rx_sync_pipe[0]",
  48. "u_uart_rx/rx_sync_pipe[1]",
  49. }
  50. )
  51. UART_ONLY_CDC_ENDPOINTS = frozenset({"u_uart_rx/rx_sync_pipe[0]"})
  52. VERIFICATION_RUN_ID = "d" * 32
  53. def valid_io_rows() -> list[dict[str, str]]:
  54. rows = [
  55. {
  56. "name": f"dummy_{index}",
  57. "direction": "OUTPUT",
  58. "location": f"DUMMY{index}",
  59. "io_standard": "LVCMOS33",
  60. "io_type": "PAD",
  61. "drive_strength": "8",
  62. "pull_type": "NONE",
  63. "pack_reg": "NONE",
  64. "diff_resistor": "NONE",
  65. }
  66. for index in range(43 - len(REQUIRED_MOTOR_LIMIT_PINS))
  67. ]
  68. template = rows[0]
  69. rows.extend(
  70. {
  71. **template,
  72. "name": name,
  73. "location": expected["location"],
  74. "direction": expected["direction"],
  75. "pull_type": expected["pull_type"],
  76. }
  77. for name, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
  78. )
  79. return rows
  80. def valid_resources() -> dict[str, object]:
  81. return {
  82. "utilization": {
  83. name: {"used": used}
  84. for name, used in {
  85. "bram": 0,
  86. "bram32k": 0,
  87. "bram128k": 0,
  88. "bram256k": 0,
  89. "dsp": 0,
  90. "pad": 43,
  91. "ireg": 0,
  92. }.items()
  93. }
  94. }
  95. def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 8) -> dict[str, object]:
  96. digest = harness.sha256_file(bitstream)
  97. observed_pins = {
  98. row["name"]: row
  99. for row in valid_io_rows()
  100. if row["name"] in REQUIRED_MOTOR_LIMIT_PINS
  101. }
  102. return {
  103. "schema": harness.TD_RECEIPT_SCHEMA,
  104. "status": "pass",
  105. "verification_run_id": VERIFICATION_RUN_ID,
  106. "commit": commit,
  107. "bitstream_sha256": digest,
  108. "synthesis_input_hash": "b" * 64,
  109. "source_state": {"clean": True, "commit": commit},
  110. "source_binding_gate": {"status": "pass"},
  111. "pin_binding_gate": {"status": "pass"},
  112. "post_route_pin_gate": {
  113. "status": "pass",
  114. "row_count": 43,
  115. "observed": observed_pins,
  116. },
  117. "binding_gate": {"status": "pass"},
  118. "timing_gate": {"status": "pass"},
  119. "structural_gate": {
  120. "status": "pass",
  121. "cdc": {
  122. "status": "pass",
  123. "async_reg": {"used": 2},
  124. "input_registers": {"used": 0},
  125. "retained_sync_registers": {"used": 2},
  126. "first_stage_endpoints": {"used": 1},
  127. },
  128. "fsm_encoding": {
  129. "status": "pass",
  130. "encoding": "sequential",
  131. "axes": {"x": 2, "y": 2},
  132. "td_log_marker": True,
  133. "reencoded_motion_phase_count": 0,
  134. },
  135. },
  136. "resources": valid_resources(),
  137. "timing": {
  138. "fmax_mhz": 50.0,
  139. "worst_setup_slack_ns": 0.1,
  140. "worst_hold_slack_ns": 0.1,
  141. "error_count": 0,
  142. },
  143. "syn": {
  144. "status": "pass",
  145. "returncode": 0,
  146. "log_has_error": False,
  147. "critical_warning_count": 0,
  148. },
  149. "phy": {
  150. "status": "pass",
  151. "returncode": 0,
  152. "log_has_error": False,
  153. "critical_warning_count": 0,
  154. },
  155. "bitgen": {
  156. "status": "pass",
  157. "returncode": 0,
  158. "log_has_error": False,
  159. "critical_warning_count": 0,
  160. },
  161. "bitstream": {
  162. "path": str(bitstream),
  163. "size": bitstream.stat().st_size,
  164. "sha256": digest,
  165. },
  166. "run_id": "1" * 32,
  167. "work_root": "C:/td-a",
  168. "td_tool": {"sha256": "c" * 64},
  169. "synthesis_input_manifest": {"sha256": "b" * 64},
  170. }
  171. def valid_offline_receipt(*, commit: str = "a" * 8) -> dict[str, object]:
  172. layers = {
  173. name: {"status": "pass"}
  174. for name in ("source_integrity", "unit", "hdl_sim", "formal")
  175. }
  176. return {
  177. "schema": harness.OFFLINE_RECEIPT_SCHEMA,
  178. "status": "pass",
  179. "verification_run_id": VERIFICATION_RUN_ID,
  180. "commit": commit,
  181. "source_state": {"clean": True, "commit": commit},
  182. "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"],
  183. "layers": layers,
  184. "failures": [],
  185. }
  186. def valid_package_receipt(
  187. package: Path,
  188. *,
  189. digest: str,
  190. commit: str = "a" * 8,
  191. ) -> dict[str, object]:
  192. return {
  193. "schema": harness.PACKAGE_RECEIPT_SCHEMA,
  194. "status": "pass",
  195. "verification_run_id": VERIFICATION_RUN_ID,
  196. "commit": commit,
  197. "bitstream_sha256": digest,
  198. "package_dir": str(package),
  199. "delivery_mode": "normal_dual_td",
  200. "verification_complete": True,
  201. "confirmation_td_present": True,
  202. "validation_status": "pass",
  203. "packaged_selftest_status": "pass",
  204. "failures": [],
  205. "selftest": {"status": "pass", "returncode": 0},
  206. }
  207. def materialize_valid_package(
  208. package: Path,
  209. *,
  210. bitstream_bytes: bytes = b"package-final-gate",
  211. commit: str = "a" * 8,
  212. ) -> tuple[dict[str, object], dict[str, object], dict[str, object]]:
  213. package.mkdir(parents=True)
  214. bitstream = package / "fw.bit"
  215. bitstream.write_bytes(bitstream_bytes)
  216. digest = harness.sha256_file(bitstream)
  217. primary = valid_td_receipt(bitstream, commit=commit)
  218. confirmation = copy.deepcopy(primary)
  219. confirmation["run_id"] = "2" * 32
  220. confirmation["work_root"] = "C:/td-b"
  221. for relative in harness.package_required_files(confirmation_td_present=True):
  222. path = package / relative
  223. path.parent.mkdir(parents=True, exist_ok=True)
  224. if not path.exists():
  225. path.write_text(f"fixture:{relative}\n", encoding="utf-8")
  226. primary_path = package / "evidence" / "td-primary-receipt.json"
  227. confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
  228. primary_path.write_text(json.dumps(primary), encoding="utf-8")
  229. confirmation_path.write_text(json.dumps(confirmation), encoding="utf-8")
  230. validation = {
  231. "schema": "prod2u-p4-normal-v3-validation-summary-v1",
  232. "verification_run_id": VERIFICATION_RUN_ID,
  233. "commit": commit,
  234. "bitstream_sha256": digest,
  235. "delivery_mode": "normal_dual_td",
  236. "verification_complete": True,
  237. "confirmation_td_present": True,
  238. "layers": {
  239. name: {"status": "pass"}
  240. for name in (
  241. "python",
  242. "icarus",
  243. "verilator",
  244. "cocotb",
  245. "formal",
  246. "td_primary",
  247. "td_confirmation",
  248. "td_primary_artifacts",
  249. "td_confirmation_artifacts",
  250. "td_confirmation_bitstream",
  251. "td_confirmation_synthesis",
  252. "td_confirmation_manifest",
  253. "resource_primary",
  254. "resource_confirmation",
  255. "package_selftest",
  256. )
  257. },
  258. }
  259. validation_path = package / "evidence" / "validation-summary.json"
  260. validation_path.write_text(json.dumps(validation), encoding="utf-8")
  261. packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
  262. packaged_selftest_path.write_text(
  263. json.dumps(
  264. {
  265. "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
  266. "status": "pass",
  267. "returncode": 0,
  268. }
  269. ),
  270. encoding="utf-8",
  271. )
  272. info_path = package / "package-info.json"
  273. actual_files = {
  274. path.relative_to(package).as_posix(): harness.sha256_file(path)
  275. for path in sorted(package.rglob("*"))
  276. if path.is_file() and path not in {info_path, packaged_selftest_path}
  277. }
  278. info = {
  279. "schema": "prod2u-p4-normal-v3-folder-package-info-v3",
  280. "profile": harness.RUNTIME_PROFILE,
  281. "verification_run_id": VERIFICATION_RUN_ID,
  282. "commit": commit,
  283. "bitstream_sha256": digest,
  284. "delivery_mode": "normal_dual_td",
  285. "verification_complete": True,
  286. "confirmation_td_present": True,
  287. "confirmation_bitstream_sha256": digest,
  288. "td_receipt_sha256": harness.sha256_file(primary_path),
  289. "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
  290. "validation_summary_sha256": harness.sha256_file(validation_path),
  291. "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
  292. "synthesis_input_hash": primary["synthesis_input_hash"],
  293. "confirmation_synthesis_input_hash": confirmation["synthesis_input_hash"],
  294. "file_sha256": actual_files,
  295. }
  296. info_path.write_text(json.dumps(info), encoding="utf-8")
  297. receipt = valid_package_receipt(package, digest=digest, commit=commit)
  298. receipt.update(
  299. {
  300. "package_info_sha256": harness.sha256_file(info_path),
  301. "td_receipt_sha256": harness.sha256_file(primary_path),
  302. "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
  303. "validation_summary_sha256": harness.sha256_file(validation_path),
  304. "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
  305. "package_file_sha256": actual_files,
  306. "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
  307. }
  308. )
  309. return receipt, primary, confirmation
  310. def refresh_package_bindings(package: Path, receipt: dict[str, object]) -> None:
  311. info_path = package / "package-info.json"
  312. primary_path = package / "evidence" / "td-primary-receipt.json"
  313. confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
  314. validation_path = package / "evidence" / "validation-summary.json"
  315. packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
  316. info = json.loads(info_path.read_text(encoding="utf-8"))
  317. info["td_receipt_sha256"] = harness.sha256_file(primary_path)
  318. info["confirmation_td_receipt_sha256"] = (
  319. harness.sha256_file(confirmation_path) if confirmation_path.is_file() else None
  320. )
  321. info["validation_summary_sha256"] = harness.sha256_file(validation_path)
  322. info["package_selftest_result_sha256"] = harness.sha256_file(packaged_selftest_path)
  323. actual_files = {
  324. path.relative_to(package).as_posix(): harness.sha256_file(path)
  325. for path in sorted(package.rglob("*"))
  326. if path.is_file() and path not in {info_path, packaged_selftest_path}
  327. }
  328. info["file_sha256"] = actual_files
  329. info_path.write_text(json.dumps(info), encoding="utf-8")
  330. receipt.update(
  331. {
  332. "delivery_mode": info["delivery_mode"],
  333. "verification_complete": info["verification_complete"],
  334. "confirmation_td_present": info["confirmation_td_present"],
  335. "package_info_sha256": harness.sha256_file(info_path),
  336. "td_receipt_sha256": info["td_receipt_sha256"],
  337. "confirmation_td_receipt_sha256": info[
  338. "confirmation_td_receipt_sha256"
  339. ],
  340. "validation_summary_sha256": info["validation_summary_sha256"],
  341. "package_selftest_result_sha256": info[
  342. "package_selftest_result_sha256"
  343. ],
  344. "package_file_sha256": actual_files,
  345. "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
  346. }
  347. )
  348. def update_package_info(package: Path, **updates: object) -> None:
  349. info_path = package / "package-info.json"
  350. info = json.loads(info_path.read_text(encoding="utf-8"))
  351. info.update(updates)
  352. info_path.write_text(json.dumps(info), encoding="utf-8")
  353. class Prod2UP4HarnessTests(unittest.TestCase):
  354. def test_cdc_report_preserves_advisory_failures_and_source_only_paths(self) -> None:
  355. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  356. report_path = Path(temporary) / "cdc.rpt"
  357. report_path.write_text(
  358. "\n".join(
  359. (
  360. f"schema={harness.CDC_REPORT_SCHEMA}",
  361. "retained_sync_register=u_uart_rx/rx_sync_pipe[1]",
  362. "false_path_source=host_uart_rx",
  363. "structural_failure=retained_sync_register_count:host_uart_rx:0",
  364. )
  365. )
  366. + "\n",
  367. encoding="ascii",
  368. )
  369. report = harness.parse_td_cdc_report(report_path)
  370. self.assertIsNotNone(report)
  371. assert report is not None
  372. self.assertEqual(report["source_only_false_paths"], ["host_uart_rx"])
  373. self.assertEqual(
  374. report["structural_failures"],
  375. ["retained_sync_register_count:host_uart_rx:0"],
  376. )
  377. gate = harness.structural_cdc_gate(
  378. report,
  379. async_reg_count=1,
  380. input_register_count=0,
  381. )
  382. self.assertEqual(gate["status"], "fail")
  383. self.assertIn(
  384. "td_report:retained_sync_register_count:host_uart_rx:0",
  385. gate["failures"],
  386. )
  387. self.assertIn("source_only_false_paths_used:host_uart_rx", gate["failures"])
  388. def test_cdc_gate_accepts_uart_only_synchronizers(self) -> None:
  389. uart_only_report = {
  390. "retained_sync_registers": sorted(UART_ONLY_CDC_REGISTERS),
  391. "false_path_endpoints": sorted(UART_ONLY_CDC_ENDPOINTS),
  392. "source_only_false_paths": [],
  393. "structural_failures": [],
  394. }
  395. accepted = harness.structural_cdc_gate(
  396. uart_only_report,
  397. async_reg_count=2,
  398. input_register_count=0,
  399. )
  400. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  401. def test_cdc_gate_rejects_legacy_limit_synchronizers(self) -> None:
  402. legacy_registers = sorted(
  403. UART_ONLY_CDC_REGISTERS
  404. | {
  405. "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
  406. "u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
  407. "u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
  408. "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
  409. "u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
  410. "u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
  411. }
  412. )
  413. legacy_report = {
  414. "retained_sync_registers": legacy_registers,
  415. "false_path_endpoints": sorted(
  416. UART_ONLY_CDC_ENDPOINTS
  417. | {
  418. "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
  419. "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
  420. }
  421. ),
  422. "source_only_false_paths": [],
  423. "structural_failures": [],
  424. }
  425. rejected = harness.structural_cdc_gate(
  426. legacy_report,
  427. async_reg_count=8,
  428. input_register_count=0,
  429. )
  430. self.assertEqual(rejected["status"], "fail")
  431. def test_fsm_report_preserves_advisory_discovery_failures(self) -> None:
  432. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  433. report_path = Path(temporary) / "fsm.rpt"
  434. report_path.write_text(
  435. "\n".join(
  436. (
  437. f"schema={harness.FSM_REPORT_SCHEMA}",
  438. "motion_phase=x:0:unknown",
  439. "motion_phase=y:3:sequential",
  440. "structural_failure=motion_phase_register_count:x:0",
  441. )
  442. )
  443. + "\n",
  444. encoding="ascii",
  445. )
  446. report = harness.parse_td_fsm_report(report_path)
  447. self.assertIsNotNone(report)
  448. assert report is not None
  449. self.assertEqual(
  450. report["structural_failures"],
  451. ["motion_phase_register_count:x:0"],
  452. )
  453. gate = harness.structural_fsm_gate(report, syn_log="")
  454. self.assertEqual(gate["status"], "fail")
  455. self.assertIn(
  456. "td_report:motion_phase_register_count:x:0",
  457. gate["failures"],
  458. )
  459. def test_fsm_gate_accepts_two_bit_simplified_axes(self) -> None:
  460. accepted = harness.structural_fsm_gate(
  461. {
  462. "axes": {"x": 2, "y": 2},
  463. "encodings": {"x": "sequential", "y": "sequential"},
  464. "structural_failures": [],
  465. },
  466. syn_log="FSM_ENCODING_GATE_PASS=sequential",
  467. )
  468. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  469. def test_fsm_gate_rejects_legacy_three_bit_axes(self) -> None:
  470. rejected = harness.structural_fsm_gate(
  471. {
  472. "axes": {"x": 3, "y": 3},
  473. "encodings": {"x": "sequential", "y": "sequential"},
  474. "structural_failures": [],
  475. },
  476. syn_log="FSM_ENCODING_GATE_PASS=sequential",
  477. )
  478. self.assertEqual(rejected["status"], "fail")
  479. def test_bitgen_eligibility_depends_only_on_successful_route(self) -> None:
  480. self.assertTrue(
  481. harness.td_bitgen_eligible(
  482. route_artifact_usable=True,
  483. timing_status="fail",
  484. structural_status="fail",
  485. )
  486. )
  487. self.assertFalse(
  488. harness.td_bitgen_eligible(
  489. route_artifact_usable=False,
  490. timing_status="pass",
  491. structural_status="pass",
  492. )
  493. )
  494. def test_td_stage_artifact_usability_ignores_validation_warnings(self) -> None:
  495. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  496. artifact = Path(temporary) / "routed.db"
  497. artifact.write_bytes(b"routed database")
  498. warning_only = subprocess.CompletedProcess(
  499. ["td"],
  500. 0,
  501. stdout="CRITICAL WARNING: validation evidence remains advisory",
  502. stderr="",
  503. )
  504. self.assertTrue(harness.td_stage_artifact_usable(warning_only, artifact))
  505. error = subprocess.CompletedProcess(
  506. ["td"],
  507. 0,
  508. stdout="ERROR: routed database is unusable",
  509. stderr="",
  510. )
  511. self.assertFalse(harness.td_stage_artifact_usable(error, artifact))
  512. artifact.unlink()
  513. self.assertFalse(harness.td_stage_artifact_usable(warning_only, artifact))
  514. def test_parser_has_closed_commands_and_fixed_td_top(self) -> None:
  515. parser = harness.build_parser()
  516. commands = parser._subparsers._group_actions[0].choices
  517. self.assertEqual(
  518. set(commands),
  519. {
  520. "p4-normal-v3-strict-offline-gate",
  521. "hdl-sim",
  522. "formal",
  523. "td-build",
  524. "package-selftest",
  525. "p4-normal-v3-final-gate",
  526. },
  527. )
  528. td_parser = commands["td-build"]
  529. top_action = next(action for action in td_parser._actions if action.dest == "top")
  530. self.assertEqual(tuple(top_action.choices), ("prod2u_p4_normal_v3",))
  531. for retired in ("resource-baseline-produce", "normal-actuator-trace-gate", "uart-board-sram-test"):
  532. self.assertNotIn(retired, commands)
  533. def test_delivery_commands_require_one_explicit_verification_run_id(self) -> None:
  534. parser = harness.build_parser()
  535. commands = parser._subparsers._group_actions[0].choices
  536. for command in (
  537. "p4-normal-v3-strict-offline-gate",
  538. "td-build",
  539. "package-selftest",
  540. "p4-normal-v3-final-gate",
  541. ):
  542. action = next(
  543. item
  544. for item in commands[command]._actions
  545. if item.dest == "verification_run_id"
  546. )
  547. with self.subTest(command=command):
  548. self.assertTrue(action.required)
  549. with self.assertRaisesRegex(ValueError, "verification_run_id is required"):
  550. harness.normalize_verification_run_id(None)
  551. final_schema = json.loads(
  552. (
  553. ROOT
  554. / "schemas"
  555. / "prod2u_p4_normal_v3_final_gate_receipt.schema.json"
  556. ).read_text(encoding="utf-8")
  557. )
  558. self.assertEqual(
  559. final_schema["properties"]["verification_run_id"]["type"],
  560. "string",
  561. )
  562. def test_package_selftest_schema_matches_emitted_metadata_and_statuses(self) -> None:
  563. schema = json.loads(
  564. (
  565. ROOT
  566. / "schemas"
  567. / "prod2u_p4_normal_v3_package_selftest_receipt.schema.json"
  568. ).read_text(encoding="utf-8")
  569. )
  570. for field in (
  571. "delivery_mode",
  572. "verification_complete",
  573. "confirmation_td_present",
  574. ):
  575. with self.subTest(field=field):
  576. self.assertIn(field, schema["required"])
  577. self.assertIn(field, schema["properties"])
  578. self.assertEqual(
  579. set(schema["properties"]["validation_status"]["enum"]),
  580. {"pass", "fail", "running", "not_run"},
  581. )
  582. def test_all_external_commit_schemas_accept_only_lowercase_sha8(self) -> None:
  583. schema_fields = {
  584. "prod2u_p4_normal_v3_final_gate_receipt.schema.json": (
  585. "properties",
  586. "commit",
  587. ),
  588. "prod2u_p4_normal_v3_offline_gate_receipt.schema.json": (
  589. "properties",
  590. "commit",
  591. ),
  592. "prod2u_p4_normal_v3_package_selftest_receipt.schema.json": (
  593. "properties",
  594. "commit",
  595. ),
  596. "prod2u_p4_normal_v3_resource_baseline.schema.json": (
  597. "properties",
  598. "measured_commit",
  599. ),
  600. "prod2u_p4_normal_v3_td_build_receipt.schema.json": ("properties", "commit"),
  601. "prod2u_program_sram_receipt.schema.json": (
  602. "properties",
  603. "bitstream",
  604. "properties",
  605. "commit",
  606. ),
  607. }
  608. invalid = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
  609. for filename, path in schema_fields.items():
  610. with self.subTest(schema=filename):
  611. value = json.loads(
  612. (ROOT / "schemas" / filename).read_text(encoding="utf-8")
  613. )
  614. for component in path:
  615. value = value[component]
  616. pattern = value["pattern"]
  617. self.assertIsNotNone(re.fullmatch(pattern, "abcdef12"))
  618. for rejected in invalid:
  619. self.assertIsNone(re.fullmatch(pattern, rejected), rejected)
  620. def test_source_state_validates_full_head_but_exposes_only_sha8(self) -> None:
  621. full_commit = "abcdef12" + ("3" * 32)
  622. results = (
  623. subprocess.CompletedProcess(
  624. ["git"], 0, stdout=full_commit + "\n", stderr=""
  625. ),
  626. subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
  627. )
  628. with mock.patch.object(harness, "_git", side_effect=results) as git:
  629. observed = harness.source_state()
  630. self.assertEqual(observed["status"], "pass")
  631. self.assertEqual(observed["commit"], "abcdef12")
  632. git.assert_any_call("rev-parse", "HEAD")
  633. invalid_results = (
  634. subprocess.CompletedProcess(["git"], 0, stdout="abcdef12\n", stderr=""),
  635. subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
  636. )
  637. with mock.patch.object(harness, "_git", side_effect=invalid_results):
  638. invalid = harness.source_state()
  639. self.assertEqual(invalid["status"], "fail")
  640. self.assertIn("git_commit_unavailable", invalid["failures"])
  641. def test_td_receipt_identifiers_are_valid_and_canonically_independent(self) -> None:
  642. schema = json.loads(
  643. (
  644. ROOT
  645. / "schemas"
  646. / "prod2u_p4_normal_v3_td_build_receipt.schema.json"
  647. ).read_text(encoding="utf-8")
  648. )
  649. pass_required = schema["allOf"][0]["then"]["required"]
  650. self.assertIn("run_id", pass_required)
  651. self.assertIn("work_root", pass_required)
  652. self.assertEqual(
  653. schema["properties"]["run_id"]["pattern"],
  654. "^[0-9a-f]{32}$",
  655. )
  656. self.assertEqual(
  657. schema["properties"]["work_root"]["pattern"],
  658. "^[A-Za-z]:[\\\\/]",
  659. )
  660. primary = {"run_id": "1" * 32, "work_root": "C:/td-a"}
  661. confirmation = {"run_id": "2" * 32, "work_root": "C:/td-b"}
  662. self.assertTrue(harness.td_receipts_are_independent(primary, confirmation))
  663. invalid_run_primary = {**primary, "run_id": "invalid-a"}
  664. invalid_run_confirmation = {**confirmation, "run_id": "invalid-b"}
  665. self.assertFalse(
  666. harness.td_receipts_are_independent(
  667. invalid_run_primary,
  668. invalid_run_confirmation,
  669. )
  670. )
  671. self.assertFalse(
  672. harness.td_receipts_are_independent(
  673. {**primary, "work_root": "td-a"},
  674. {**confirmation, "work_root": "td-b"},
  675. )
  676. )
  677. self.assertFalse(
  678. harness.td_receipts_are_independent(
  679. primary,
  680. {**confirmation, "work_root": "c:\\TD-A\\child\\.."},
  681. )
  682. )
  683. def test_readme_documents_one_run_id_across_complete_delivery_chain(self) -> None:
  684. readme = (ROOT / "README.zh-CN.md").read_text(encoding="utf-8")
  685. run_id_assignment = "$verificationRunId = [Guid]::NewGuid().ToString('N')"
  686. self.assertLess(
  687. readme.index(run_id_assignment),
  688. readme.index("p4-normal-v3-strict-offline-gate"),
  689. )
  690. self.assertGreaterEqual(
  691. readme.count("--verification-run-id $verificationRunId"),
  692. 5,
  693. )
  694. self.assertIn("p4-normal-v3-minimal-td-b", readme)
  695. self.assertIn("-VerificationRunId $verificationRunId", readme)
  696. self.assertIn("package-selftest", readme)
  697. self.assertIn("p4-normal-v3-final-gate", readme)
  698. def test_unit_payload_uses_pytest_collection_for_function_tests(self) -> None:
  699. completed = subprocess.CompletedProcess(
  700. ["python", "-m", "pytest"],
  701. 0,
  702. stdout="195 passed",
  703. stderr="",
  704. )
  705. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  706. with mock.patch.object(
  707. harness.subprocess,
  708. "run",
  709. return_value=completed,
  710. ) as run:
  711. payload = harness.unit_payload(Path(temporary))
  712. command = run.call_args.args[0]
  713. self.assertEqual(payload["status"], "pass")
  714. self.assertIn("pytest", command)
  715. self.assertIn("-p", command)
  716. self.assertIn("no:cacheprovider", command)
  717. self.assertIn("tests/unit", command)
  718. self.assertIn("tests/test_project_structure.py", command)
  719. self.assertNotIn("unittest", command)
  720. def test_production_source_manifest_is_exact_and_has_no_retired_rtl(self) -> None:
  721. self.assertEqual(tuple(harness.PRODUCTION_RTL_SOURCES), EXPECTED_SOURCES)
  722. self.assertEqual(tuple(harness.active_rtl_sources()), EXPECTED_SOURCES)
  723. combined = "\n".join(EXPECTED_SOURCES).casefold()
  724. for retired in ("trace", "temperature", "ct7428", "limit_filter", "build_identity"):
  725. self.assertNotIn(retired, combined)
  726. def test_versioned_target_manifest_matches_every_discovered_layer(self) -> None:
  727. inventory = harness.target_inventory()
  728. evidence = harness.target_manifest_evidence("all", inventory)
  729. self.assertEqual(evidence["status"], "pass", evidence["failures"])
  730. self.assertEqual(set(inventory), set(harness.TARGET_MANIFEST_LAYERS))
  731. def test_discovered_targets_exclude_retired_motion_and_trace_contracts(self) -> None:
  732. inventory = harness.target_inventory()
  733. names = [
  734. *inventory["unit"],
  735. *inventory["icarus"],
  736. *inventory["verilator"],
  737. *inventory["cocotb"],
  738. *inventory["formal"].keys(),
  739. ]
  740. retired_tokens = (
  741. "trace",
  742. "recovery",
  743. "mark",
  744. "late_evidence",
  745. "terminal",
  746. "locked",
  747. "learning",
  748. "limit_filter",
  749. "rx_bram",
  750. "build_identity",
  751. )
  752. offenders = [name for name in names if any(token in name.casefold() for token in retired_tokens)]
  753. self.assertEqual(offenders, [])
  754. def test_dry_run_layers_never_claim_pass_or_hardware_access(self) -> None:
  755. hdl = harness.hdl_sim_payload(run=False, backend="all")
  756. formal = harness.formal_payload(run=False)
  757. td = harness.td_build_payload(
  758. run=False,
  759. verification_run_id=VERIFICATION_RUN_ID,
  760. )
  761. for payload in (hdl, formal, td):
  762. with self.subTest(schema=payload["schema"]):
  763. self.assertEqual(payload["status"], "skipped")
  764. self.assertEqual(payload["safety"], harness.SAFETY_BOUNDARY)
  765. self.assertFalse(payload["safety"]["opens_serial"])
  766. self.assertFalse(payload["safety"]["programs_hardware"])
  767. def test_synthesis_manifest_hashes_only_exact_production_inputs(self) -> None:
  768. manifest = harness.build_synthesis_input_manifest(ROOT)
  769. expected = set(EXPECTED_SOURCES) | {
  770. "constraints/prod2u_p4_normal_v3.adc",
  771. "constraints/prod2u_p4_normal_v3.sdc",
  772. "td/prod2u_p4_normal_v3.prj",
  773. "td/syn/prod2u_p4_normal_v3.tcl",
  774. "td/phy/prod2u_p4_normal_v3.tcl",
  775. "td/bitgen/prod2u_p4_normal_v3.tcl",
  776. }
  777. self.assertEqual(set(manifest["inputs"]), expected)
  778. self.assertRegex(manifest["sha256"], r"^[0-9a-f]{64}$")
  779. self.assertNotIn("@build_identity", manifest["inputs"])
  780. def test_external_clean_staging_rechecks_synthesis_hash(self) -> None:
  781. clean_state = {
  782. "status": "pass",
  783. "commit": "a" * 8,
  784. "clean": True,
  785. "tracked_changes": [],
  786. "failures": [],
  787. }
  788. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  789. with mock.patch.object(harness, "source_state", return_value=clean_state):
  790. staged = harness.prepare_td_build_dirs(work_root=Path(temporary))
  791. verified = harness.verify_staged_source_manifest(staged)
  792. self.assertEqual(verified["status"], "pass", verified["failures"])
  793. self.assertEqual(staged.source_state["commit"], "a" * 8)
  794. self.assertEqual(
  795. staged.synthesis_input_manifest["sha256"],
  796. harness.build_synthesis_input_manifest(ROOT)["sha256"],
  797. )
  798. def test_work_and_receipt_paths_must_stay_outside_repository(self) -> None:
  799. with self.assertRaisesRegex(ValueError, "outside the repository"):
  800. harness.resolve_work_root(ROOT / "tmp", run=False)
  801. with self.assertRaisesRegex(ValueError, "outside the repository"):
  802. harness.resolve_report_file(ROOT / "receipt.json")
  803. def test_pin_binding_gate_blocks_every_motor_and_limit_ball_mutation(self) -> None:
  804. evidence = harness.pin_binding_gate()
  805. self.assertEqual(evidence["status"], "pass", evidence["failures"])
  806. self.assertEqual(evidence["pad_count"], 43)
  807. original = (ROOT / "constraints" / "prod2u_p4_normal_v3.adc").read_text(
  808. encoding="ascii"
  809. )
  810. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  811. temporary_root = Path(temporary)
  812. constraints = temporary_root / "constraints"
  813. constraints.mkdir()
  814. target = constraints / "prod2u_p4_normal_v3.adc"
  815. for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items():
  816. with self.subTest(signal=signal):
  817. pattern = re.compile(
  818. rf"(set_pin_assignment\s+\{{\s*{re.escape(signal)}\s*\}}\s+"
  819. rf"\{{\s*LOCATION\s*=\s*){re.escape(expected['location'])}(;)"
  820. )
  821. mutated, count = pattern.subn(r"\1WRONG_BALL\2", original)
  822. self.assertEqual(count, 1)
  823. target.write_text(mutated, encoding="ascii")
  824. with mock.patch.object(harness, "ROOT", temporary_root):
  825. rejected = harness.pin_binding_gate()
  826. self.assertEqual(rejected["status"], "fail", rejected)
  827. target.write_text(
  828. original.replace("LOCATION = A10;", "LOCATION = A5;", 1),
  829. encoding="ascii",
  830. )
  831. with mock.patch.object(harness, "ROOT", temporary_root):
  832. forbidden = harness.pin_binding_gate()
  833. self.assertEqual(forbidden["status"], "fail")
  834. self.assertIn("forbidden_ball_assigned:A5", forbidden["failures"])
  835. def test_post_route_pin_gate_blocks_motor_limit_a5_and_io_count_mutations(self) -> None:
  836. rows = valid_io_rows()
  837. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  838. report_path = Path(temporary) / "prod2u_p4_normal_v3_phy.area"
  839. report_path.write_text(
  840. "\n".join(
  841. [
  842. "Detailed IO Report",
  843. (
  844. "Name Direction Location IOStandard IOType "
  845. "DriveStrength PullType PackReg DiffResistor"
  846. ),
  847. *(
  848. " ".join(
  849. row[field]
  850. for field in (
  851. "name",
  852. "direction",
  853. "location",
  854. "io_standard",
  855. "io_type",
  856. "drive_strength",
  857. "pull_type",
  858. "pack_reg",
  859. "diff_resistor",
  860. )
  861. )
  862. for row in rows
  863. ),
  864. "",
  865. ]
  866. ),
  867. encoding="ascii",
  868. )
  869. parsed_rows = harness.parse_td_io_report(report_path)
  870. self.assertIsNotNone(parsed_rows)
  871. assert parsed_rows is not None
  872. self.assertEqual(len(parsed_rows), 43)
  873. evidence = harness.post_route_pin_gate(parsed_rows)
  874. self.assertEqual(evidence["status"], "pass", evidence["failures"])
  875. for signal in REQUIRED_MOTOR_LIMIT_PINS:
  876. with self.subTest(signal=signal):
  877. changed = copy.deepcopy(parsed_rows)
  878. row = next(item for item in changed if item["name"] == signal)
  879. row["location"] = "WRONG_BALL"
  880. rejected = harness.post_route_pin_gate(changed)
  881. self.assertEqual(rejected["status"], "fail", rejected)
  882. forbidden_rows = copy.deepcopy(parsed_rows)
  883. forbidden_rows[0]["location"] = "A5"
  884. forbidden = harness.post_route_pin_gate(forbidden_rows)
  885. self.assertEqual(forbidden["status"], "fail")
  886. self.assertIn("forbidden_location_assigned:A5", forbidden["failures"])
  887. missing_row = harness.post_route_pin_gate(parsed_rows[:-1])
  888. self.assertEqual(missing_row["status"], "fail")
  889. self.assertIn("io_row_count:42", missing_row["failures"])
  890. def test_structural_resource_gate_requires_reported_bram_dsp_and_io_43(self) -> None:
  891. accepted = harness.structural_resource_gate(valid_resources())
  892. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  893. for resource in ("bram", "bram32k", "bram128k", "bram256k", "dsp"):
  894. with self.subTest(resource=resource):
  895. changed = valid_resources()
  896. changed["utilization"][resource]["used"] = 1
  897. accepted = harness.structural_resource_gate(changed)
  898. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  899. missing = valid_resources()
  900. del missing["utilization"][resource]
  901. rejected = harness.structural_resource_gate(missing)
  902. self.assertEqual(rejected["status"], "fail")
  903. invalid = valid_resources()
  904. invalid["utilization"][resource]["used"] = "1"
  905. rejected = harness.structural_resource_gate(invalid)
  906. self.assertEqual(rejected["status"], "fail")
  907. wrong_pad = valid_resources()
  908. wrong_pad["utilization"]["pad"]["used"] = 41
  909. rejected = harness.structural_resource_gate(wrong_pad)
  910. self.assertEqual(rejected["status"], "fail")
  911. def test_timing_gate_requires_positive_setup_hold_fmax_and_zero_errors(self) -> None:
  912. accepted = harness.timing_gate(
  913. {
  914. "fmax_mhz": 50.0,
  915. "worst_setup_slack_ns": 0.01,
  916. "worst_hold_slack_ns": 0.01,
  917. "error_count": 0,
  918. }
  919. )
  920. self.assertEqual(accepted["status"], "pass")
  921. for field in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
  922. with self.subTest(field=field):
  923. timing = {
  924. "fmax_mhz": 50.0,
  925. "worst_setup_slack_ns": 0.01,
  926. "worst_hold_slack_ns": 0.01,
  927. "error_count": 0,
  928. }
  929. timing[field] = 0
  930. self.assertEqual(harness.timing_gate(timing)["status"], "fail")
  931. def test_td_bitstream_binding_requires_existing_hash_matching_file(self) -> None:
  932. digest = "a" * 64
  933. receipt = {
  934. "bitstream_sha256": digest,
  935. "bitstream": {
  936. "path": str(ROOT.parent / "definitely-missing-final-gate.bit"),
  937. "sha256": digest,
  938. },
  939. }
  940. self.assertEqual(
  941. harness.td_receipt_bitstream_binding_status(receipt),
  942. "fail",
  943. )
  944. def test_final_td_semantic_recheck_rejects_forged_pass_fields(self) -> None:
  945. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  946. bitstream = Path(temporary) / "fw.bit"
  947. bitstream.write_bytes(b"minimal-final-gate")
  948. baseline = valid_td_receipt(bitstream)
  949. self.assertEqual(
  950. harness._td_final_failures(baseline, label="td", expected_commit="a" * 8),
  951. [],
  952. )
  953. for resource in ("bram", "bram32k", "bram128k", "bram256k", "dsp"):
  954. with self.subTest(resource=resource):
  955. forged = copy.deepcopy(baseline)
  956. forged["resources"]["utilization"][resource]["used"] = 1
  957. failures = harness._td_final_failures(
  958. forged,
  959. label="td",
  960. expected_commit="a" * 8,
  961. )
  962. self.assertFalse(any(f"resource:{resource}:" in item for item in failures))
  963. missing = copy.deepcopy(baseline)
  964. del missing["resources"]["utilization"][resource]
  965. failures = harness._td_final_failures(
  966. missing,
  967. label="td",
  968. expected_commit="a" * 8,
  969. )
  970. self.assertTrue(any(f"resource:{resource}:" in item for item in failures))
  971. forged = copy.deepcopy(baseline)
  972. forged["resources"]["utilization"]["pad"]["used"] = 41
  973. failures = harness._td_final_failures(
  974. forged,
  975. label="td",
  976. expected_commit="a" * 8,
  977. )
  978. self.assertTrue(any("resource:pad:" in item for item in failures))
  979. mutations = {
  980. "timing": lambda value: value["timing"].__setitem__("worst_setup_slack_ns", 0),
  981. "pins": lambda value: value["post_route_pin_gate"]["observed"]["y_limit_raw"].__setitem__("location", "A5"),
  982. "motor_pin": lambda value: value["post_route_pin_gate"]["observed"]["x_step"].__setitem__("location", "WRONG_BALL"),
  983. "source": lambda value: value["source_state"].__setitem__("clean", False),
  984. "phase": lambda value: value["phy"].__setitem__("status", "fail"),
  985. }
  986. for name, mutate in mutations.items():
  987. with self.subTest(name=name):
  988. forged = copy.deepcopy(baseline)
  989. mutate(forged)
  990. self.assertTrue(
  991. harness._td_final_failures(
  992. forged,
  993. label="td",
  994. expected_commit="a" * 8,
  995. )
  996. )
  997. bitstream.write_bytes(b"minimal-final-gatE")
  998. failures = harness._td_final_failures(
  999. baseline,
  1000. label="td",
  1001. expected_commit="a" * 8,
  1002. )
  1003. self.assertIn("td:bitstream_file_hash", failures)
  1004. def test_final_package_semantic_recheck_binds_info_and_firmware_hash(self) -> None:
  1005. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1006. package = Path(temporary) / "package"
  1007. receipt, _, _ = materialize_valid_package(package)
  1008. digest = str(receipt["bitstream_sha256"])
  1009. primary_sha = str(receipt["td_receipt_sha256"])
  1010. confirmation_sha = str(receipt["confirmation_td_receipt_sha256"])
  1011. self.assertEqual(
  1012. harness._package_final_failures(
  1013. receipt,
  1014. expected_commit="a" * 8,
  1015. expected_bitstream_sha256=digest,
  1016. expected_primary_td_receipt_sha256=primary_sha,
  1017. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1018. ),
  1019. [],
  1020. )
  1021. info_path = package / "package-info.json"
  1022. info = json.loads(info_path.read_text(encoding="utf-8"))
  1023. info["commit"] = "b" * 8
  1024. info_path.write_text(json.dumps(info), encoding="utf-8")
  1025. self.assertIn(
  1026. "package:info_binding",
  1027. harness._package_final_failures(
  1028. receipt,
  1029. expected_commit="a" * 8,
  1030. expected_bitstream_sha256=digest,
  1031. expected_primary_td_receipt_sha256=primary_sha,
  1032. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1033. ),
  1034. )
  1035. info["commit"] = "a" * 8
  1036. info_path.write_text(json.dumps(info), encoding="utf-8")
  1037. (package / "fw.bit").write_bytes(b"tampered")
  1038. self.assertIn(
  1039. "package:file_hash",
  1040. harness._package_final_failures(
  1041. receipt,
  1042. expected_commit="a" * 8,
  1043. expected_bitstream_sha256=digest,
  1044. expected_primary_td_receipt_sha256=primary_sha,
  1045. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1046. ),
  1047. )
  1048. incomplete = valid_package_receipt(package, digest=digest)
  1049. incomplete["verification_complete"] = False
  1050. self.assertIn(
  1051. "package:verification_incomplete",
  1052. harness._package_final_failures(
  1053. incomplete,
  1054. expected_commit="a" * 8,
  1055. expected_bitstream_sha256=digest,
  1056. expected_primary_td_receipt_sha256=primary_sha,
  1057. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1058. ),
  1059. )
  1060. def test_final_package_rechecks_closed_normal_package_and_external_td_bindings(self) -> None:
  1061. mutations = (
  1062. ("urgent_receipt", "package:delivery_mode", lambda package, receipt: receipt.__setitem__("delivery_mode", "urgent_single_td")),
  1063. ("urgent_info", "package:info_delivery_mode", lambda package, receipt: update_package_info(package, delivery_mode="urgent_single_td")),
  1064. ("false_info_verification", "package:info_verification_incomplete", lambda package, receipt: update_package_info(package, verification_complete=False)),
  1065. ("false_info_confirmation", "package:info_confirmation_td_missing", lambda package, receipt: update_package_info(package, confirmation_td_present=False)),
  1066. ("missing_confirmation", "package:required_file", lambda package, receipt: (package / "evidence" / "td-confirmation-receipt.json").unlink()),
  1067. ("missing_validation", "package:required_file", lambda package, receipt: (package / "evidence" / "validation-summary.json").unlink()),
  1068. ("missing_selftest", "package:required_file", lambda package, receipt: (package / "evidence" / "package-selftest-result.json").unlink()),
  1069. )
  1070. for name, expected, mutate in mutations:
  1071. with self.subTest(name=name), tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1072. package = Path(temporary) / "package"
  1073. receipt, _, _ = materialize_valid_package(package)
  1074. mutate(package, receipt)
  1075. failures = harness._package_final_failures(
  1076. receipt,
  1077. expected_commit="a" * 8,
  1078. expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
  1079. expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
  1080. expected_confirmation_td_receipt_sha256=str(
  1081. receipt["confirmation_td_receipt_sha256"]
  1082. ),
  1083. )
  1084. self.assertTrue(
  1085. any(item.startswith(expected) for item in failures),
  1086. failures,
  1087. )
  1088. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1089. package = Path(temporary) / "package"
  1090. receipt, _, _ = materialize_valid_package(package)
  1091. failures = harness._package_final_failures(
  1092. receipt,
  1093. expected_commit="a" * 8,
  1094. expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
  1095. expected_primary_td_receipt_sha256="0" * 64,
  1096. expected_confirmation_td_receipt_sha256="1" * 64,
  1097. )
  1098. self.assertIn("package:primary_td_external_binding", failures)
  1099. self.assertIn("package:confirmation_td_external_binding", failures)
  1100. def test_td_final_reopens_cdc_and_fsm_structure_contracts(self) -> None:
  1101. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1102. bitstream = Path(temporary) / "td.bit"
  1103. bitstream.write_bytes(b"td-structure-contract")
  1104. receipt = valid_td_receipt(bitstream)
  1105. receipt["structural_gate"]["cdc"]["retained_sync_registers"][
  1106. "used"
  1107. ] = 8
  1108. receipt["structural_gate"]["fsm_encoding"]["axes"] = {
  1109. "x": 3,
  1110. "y": 3,
  1111. }
  1112. failures = harness._td_final_failures(
  1113. receipt,
  1114. label="td",
  1115. expected_commit="a" * 8,
  1116. )
  1117. self.assertIn("td:structural_gate:cdc", failures)
  1118. self.assertIn("td:structural_gate:fsm_encoding", failures)
  1119. def test_package_selftest_rejects_a_different_verification_run(self) -> None:
  1120. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1121. package = Path(temporary) / "package"
  1122. materialize_valid_package(package)
  1123. completed = subprocess.CompletedProcess(
  1124. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1125. )
  1126. with mock.patch.object(
  1127. harness.subprocess,
  1128. "run",
  1129. return_value=completed,
  1130. ):
  1131. observed = harness.package_selftest_payload(
  1132. package,
  1133. verification_run_id="e" * 32,
  1134. )
  1135. self.assertEqual(observed["status"], "fail")
  1136. self.assertIn(
  1137. "verification_run_id_mismatch:package_info",
  1138. observed["failures"],
  1139. )
  1140. def test_package_selftest_rejects_every_non_sha8_commit_form(self) -> None:
  1141. invalid_commits = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
  1142. for commit in invalid_commits:
  1143. with self.subTest(commit=commit), tempfile.TemporaryDirectory(
  1144. dir=ROOT.parent
  1145. ) as temporary:
  1146. digest = hashlib.sha256(b"invalid-commit-package").hexdigest()
  1147. package = (
  1148. Path(temporary)
  1149. / commit
  1150. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1151. )
  1152. materialize_valid_package(
  1153. package,
  1154. bitstream_bytes=b"invalid-commit-package",
  1155. commit=commit,
  1156. )
  1157. completed = subprocess.CompletedProcess(
  1158. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1159. )
  1160. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1161. observed = harness.package_selftest_payload(
  1162. package,
  1163. verification_run_id=VERIFICATION_RUN_ID,
  1164. )
  1165. self.assertEqual(observed["status"], "fail")
  1166. self.assertIn("package_commit_invalid", observed["failures"])
  1167. def test_package_validator_preserves_running_but_final_gate_rejects_it(self) -> None:
  1168. bitstream_bytes = b"running-validation-package"
  1169. digest = hashlib.sha256(bitstream_bytes).hexdigest()
  1170. commit = "a" * 8
  1171. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1172. package = (
  1173. Path(temporary)
  1174. / commit
  1175. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1176. )
  1177. receipt, _, _ = materialize_valid_package(
  1178. package,
  1179. bitstream_bytes=bitstream_bytes,
  1180. commit=commit,
  1181. )
  1182. validation_path = package / "evidence" / "validation-summary.json"
  1183. validation = json.loads(validation_path.read_text(encoding="utf-8"))
  1184. validation["layers"]["td_confirmation"]["status"] = "running"
  1185. validation_path.write_text(json.dumps(validation), encoding="utf-8")
  1186. refresh_package_bindings(package, receipt)
  1187. completed = subprocess.CompletedProcess(
  1188. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1189. )
  1190. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1191. observed = harness.package_selftest_payload(
  1192. package,
  1193. verification_run_id=VERIFICATION_RUN_ID,
  1194. )
  1195. self.assertEqual(observed["status"], "pass", observed["failures"])
  1196. self.assertEqual(observed["validation_status"], "running")
  1197. receipt.update(observed)
  1198. failures = harness._package_final_failures(
  1199. receipt,
  1200. expected_commit=commit,
  1201. expected_bitstream_sha256=digest,
  1202. expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
  1203. expected_confirmation_td_receipt_sha256=str(
  1204. receipt["confirmation_td_receipt_sha256"]
  1205. ),
  1206. )
  1207. self.assertIn("package:validation_incomplete", failures)
  1208. def test_package_selftest_rejects_non_independent_td_receipts(self) -> None:
  1209. cases = (
  1210. ("run_id", "td_run_id_not_independent"),
  1211. ("work_root", "td_work_root_not_independent"),
  1212. )
  1213. for field, failure in cases:
  1214. with self.subTest(field=field), tempfile.TemporaryDirectory(
  1215. dir=ROOT.parent
  1216. ) as temporary:
  1217. commit = "a" * 8
  1218. digest = hashlib.sha256(b"independent-package-selftest").hexdigest()
  1219. package = (
  1220. Path(temporary)
  1221. / commit
  1222. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1223. )
  1224. receipt, primary, confirmation = materialize_valid_package(
  1225. package,
  1226. bitstream_bytes=b"independent-package-selftest",
  1227. commit=commit,
  1228. )
  1229. confirmation[field] = primary[field]
  1230. (package / "evidence" / "td-confirmation-receipt.json").write_text(
  1231. json.dumps(confirmation),
  1232. encoding="utf-8",
  1233. )
  1234. refresh_package_bindings(package, receipt)
  1235. completed = subprocess.CompletedProcess(
  1236. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1237. )
  1238. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1239. observed = harness.package_selftest_payload(
  1240. package,
  1241. verification_run_id=VERIFICATION_RUN_ID,
  1242. )
  1243. self.assertEqual(observed["status"], "fail")
  1244. self.assertIn(failure, observed["failures"])
  1245. def test_urgent_validator_allows_running_td_confirmation_only(self) -> None:
  1246. bitstream_bytes = b"urgent-running-confirmation"
  1247. digest = hashlib.sha256(bitstream_bytes).hexdigest()
  1248. commit = "a" * 8
  1249. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1250. package = (
  1251. Path(temporary)
  1252. / commit
  1253. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1254. )
  1255. receipt, _, _ = materialize_valid_package(
  1256. package,
  1257. bitstream_bytes=bitstream_bytes,
  1258. commit=commit,
  1259. )
  1260. (package / "evidence" / "td-confirmation-receipt.json").unlink()
  1261. info_path = package / "package-info.json"
  1262. info = json.loads(info_path.read_text(encoding="utf-8"))
  1263. info.update(
  1264. {
  1265. "delivery_mode": "urgent_single_td",
  1266. "verification_complete": False,
  1267. "confirmation_td_present": False,
  1268. "confirmation_bitstream_sha256": None,
  1269. "confirmation_synthesis_input_hash": None,
  1270. }
  1271. )
  1272. info_path.write_text(json.dumps(info), encoding="utf-8")
  1273. validation_path = package / "evidence" / "validation-summary.json"
  1274. validation = json.loads(validation_path.read_text(encoding="utf-8"))
  1275. validation.update(
  1276. {
  1277. "delivery_mode": "urgent_single_td",
  1278. "verification_complete": False,
  1279. "confirmation_td_present": False,
  1280. }
  1281. )
  1282. validation["layers"]["td_confirmation"]["status"] = "running"
  1283. for name in (
  1284. "td_confirmation_artifacts",
  1285. "td_confirmation_bitstream",
  1286. "td_confirmation_synthesis",
  1287. "td_confirmation_manifest",
  1288. "resource_confirmation",
  1289. ):
  1290. validation["layers"][name]["status"] = "not_run"
  1291. validation_path.write_text(json.dumps(validation), encoding="utf-8")
  1292. refresh_package_bindings(package, receipt)
  1293. completed = subprocess.CompletedProcess(
  1294. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1295. )
  1296. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1297. observed = harness.package_selftest_payload(
  1298. package,
  1299. verification_run_id=VERIFICATION_RUN_ID,
  1300. )
  1301. self.assertEqual(observed["status"], "pass", observed["failures"])
  1302. self.assertEqual(observed["validation_status"], "running")
  1303. def test_final_gate_rejects_two_td_receipts_from_same_run_or_work_root(self) -> None:
  1304. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1305. root = Path(temporary)
  1306. bitstream = root / "td.bit"
  1307. bitstream.write_bytes(b"two-build-final-gate")
  1308. digest = harness.sha256_file(bitstream)
  1309. package = root / "package"
  1310. package_receipt, packaged_primary, packaged_confirmation = (
  1311. materialize_valid_package(
  1312. package,
  1313. bitstream_bytes=bitstream.read_bytes(),
  1314. )
  1315. )
  1316. primary = packaged_primary
  1317. confirmation = copy.deepcopy(packaged_primary)
  1318. packaged_confirmation = confirmation
  1319. receipts = {
  1320. "offline": valid_offline_receipt(),
  1321. "td": primary,
  1322. "td_confirmation": confirmation,
  1323. "package": package_receipt,
  1324. }
  1325. paths = {}
  1326. for name, payload in receipts.items():
  1327. path = root / f"{name}.json"
  1328. path.write_text(json.dumps(payload), encoding="utf-8")
  1329. paths[name] = path
  1330. args = argparse.Namespace(
  1331. offline_receipt=paths["offline"],
  1332. td_receipt=paths["td"],
  1333. confirmation_td_receipt=paths["td_confirmation"],
  1334. package_receipt=paths["package"],
  1335. verification_run_id=VERIFICATION_RUN_ID,
  1336. report_file=None,
  1337. json=False,
  1338. )
  1339. with (
  1340. mock.patch.object(
  1341. harness,
  1342. "source_state",
  1343. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1344. ),
  1345. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1346. ):
  1347. rejected = harness.cmd_final_gate(args)
  1348. self.assertEqual(rejected["status"], "fail")
  1349. self.assertIn("td_run_id_not_independent", rejected["failures"])
  1350. self.assertIn("td_work_root_not_independent", rejected["failures"])
  1351. confirmation["run_id"] = "2" * 32
  1352. confirmation["work_root"] = "C:/td-b"
  1353. packaged_confirmation["run_id"] = confirmation["run_id"]
  1354. packaged_confirmation["work_root"] = confirmation["work_root"]
  1355. packaged_primary_path = package / "evidence" / "td-primary-receipt.json"
  1356. packaged_confirmation_path = (
  1357. package / "evidence" / "td-confirmation-receipt.json"
  1358. )
  1359. packaged_primary_path.write_text(
  1360. json.dumps(packaged_primary), encoding="utf-8"
  1361. )
  1362. packaged_confirmation_path.write_text(
  1363. json.dumps(packaged_confirmation), encoding="utf-8"
  1364. )
  1365. refresh_package_bindings(package, package_receipt)
  1366. paths["package"].write_text(json.dumps(package_receipt), encoding="utf-8")
  1367. paths["td_confirmation"].write_text(json.dumps(confirmation), encoding="utf-8")
  1368. with (
  1369. mock.patch.object(
  1370. harness,
  1371. "source_state",
  1372. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1373. ),
  1374. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1375. ):
  1376. accepted = harness.cmd_final_gate(args)
  1377. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  1378. confirmation["bitstream_sha256"] = "f" * 64
  1379. paths["td_confirmation"].write_text(
  1380. json.dumps(confirmation), encoding="utf-8"
  1381. )
  1382. with (
  1383. mock.patch.object(
  1384. harness,
  1385. "source_state",
  1386. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1387. ),
  1388. mock.patch.object(
  1389. harness,
  1390. "_emit",
  1391. side_effect=lambda payload, _args, _label: payload,
  1392. ),
  1393. ):
  1394. bitstream_mismatch = harness.cmd_final_gate(args)
  1395. self.assertEqual(bitstream_mismatch["status"], "fail")
  1396. self.assertIn(
  1397. "td_bitstream_sha256_mismatch",
  1398. bitstream_mismatch["failures"],
  1399. )
  1400. confirmation["bitstream_sha256"] = digest
  1401. paths["td_confirmation"].write_text(
  1402. json.dumps(confirmation), encoding="utf-8"
  1403. )
  1404. with (
  1405. mock.patch.object(
  1406. harness,
  1407. "source_state",
  1408. return_value={"status": "fail", "commit": "a" * 8, "clean": False},
  1409. ),
  1410. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1411. ):
  1412. dirty = harness.cmd_final_gate(args)
  1413. self.assertEqual(dirty["status"], "fail")
  1414. self.assertIn("final_source_state_not_clean", dirty["failures"])
  1415. if __name__ == "__main__":
  1416. unittest.main()