test_prod2u_p4_harness.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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(41 - 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": 41,
  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": 41,
  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"], 41)
  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), 41)
  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:40", missing_row["failures"])
  890. def test_structural_resource_gate_requires_all_bram_zero_dsp_zero_io_41(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. rejected = harness.structural_resource_gate(changed)
  898. self.assertEqual(rejected["status"], "fail")
  899. def test_timing_gate_requires_positive_setup_hold_fmax_and_zero_errors(self) -> None:
  900. accepted = harness.timing_gate(
  901. {
  902. "fmax_mhz": 50.0,
  903. "worst_setup_slack_ns": 0.01,
  904. "worst_hold_slack_ns": 0.01,
  905. "error_count": 0,
  906. }
  907. )
  908. self.assertEqual(accepted["status"], "pass")
  909. for field in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
  910. with self.subTest(field=field):
  911. timing = {
  912. "fmax_mhz": 50.0,
  913. "worst_setup_slack_ns": 0.01,
  914. "worst_hold_slack_ns": 0.01,
  915. "error_count": 0,
  916. }
  917. timing[field] = 0
  918. self.assertEqual(harness.timing_gate(timing)["status"], "fail")
  919. def test_td_bitstream_binding_requires_existing_hash_matching_file(self) -> None:
  920. digest = "a" * 64
  921. receipt = {
  922. "bitstream_sha256": digest,
  923. "bitstream": {
  924. "path": str(ROOT.parent / "definitely-missing-final-gate.bit"),
  925. "sha256": digest,
  926. },
  927. }
  928. self.assertEqual(
  929. harness.td_receipt_bitstream_binding_status(receipt),
  930. "fail",
  931. )
  932. def test_final_td_semantic_recheck_rejects_forged_pass_fields(self) -> None:
  933. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  934. bitstream = Path(temporary) / "fw.bit"
  935. bitstream.write_bytes(b"minimal-final-gate")
  936. baseline = valid_td_receipt(bitstream)
  937. self.assertEqual(
  938. harness._td_final_failures(baseline, label="td", expected_commit="a" * 8),
  939. [],
  940. )
  941. for resource in ("bram", "bram32k", "bram128k", "bram256k", "dsp", "pad"):
  942. with self.subTest(resource=resource):
  943. forged = copy.deepcopy(baseline)
  944. forged["resources"]["utilization"][resource]["used"] = 1
  945. failures = harness._td_final_failures(
  946. forged,
  947. label="td",
  948. expected_commit="a" * 8,
  949. )
  950. self.assertTrue(any(f"resource:{resource}:" in item for item in failures))
  951. mutations = {
  952. "timing": lambda value: value["timing"].__setitem__("worst_setup_slack_ns", 0),
  953. "pins": lambda value: value["post_route_pin_gate"]["observed"]["y_limit_raw"].__setitem__("location", "A5"),
  954. "motor_pin": lambda value: value["post_route_pin_gate"]["observed"]["x_step"].__setitem__("location", "WRONG_BALL"),
  955. "source": lambda value: value["source_state"].__setitem__("clean", False),
  956. "phase": lambda value: value["phy"].__setitem__("status", "fail"),
  957. }
  958. for name, mutate in mutations.items():
  959. with self.subTest(name=name):
  960. forged = copy.deepcopy(baseline)
  961. mutate(forged)
  962. self.assertTrue(
  963. harness._td_final_failures(
  964. forged,
  965. label="td",
  966. expected_commit="a" * 8,
  967. )
  968. )
  969. bitstream.write_bytes(b"minimal-final-gatE")
  970. failures = harness._td_final_failures(
  971. baseline,
  972. label="td",
  973. expected_commit="a" * 8,
  974. )
  975. self.assertIn("td:bitstream_file_hash", failures)
  976. def test_final_package_semantic_recheck_binds_info_and_firmware_hash(self) -> None:
  977. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  978. package = Path(temporary) / "package"
  979. receipt, _, _ = materialize_valid_package(package)
  980. digest = str(receipt["bitstream_sha256"])
  981. primary_sha = str(receipt["td_receipt_sha256"])
  982. confirmation_sha = str(receipt["confirmation_td_receipt_sha256"])
  983. self.assertEqual(
  984. harness._package_final_failures(
  985. receipt,
  986. expected_commit="a" * 8,
  987. expected_bitstream_sha256=digest,
  988. expected_primary_td_receipt_sha256=primary_sha,
  989. expected_confirmation_td_receipt_sha256=confirmation_sha,
  990. ),
  991. [],
  992. )
  993. info_path = package / "package-info.json"
  994. info = json.loads(info_path.read_text(encoding="utf-8"))
  995. info["commit"] = "b" * 8
  996. info_path.write_text(json.dumps(info), encoding="utf-8")
  997. self.assertIn(
  998. "package:info_binding",
  999. harness._package_final_failures(
  1000. receipt,
  1001. expected_commit="a" * 8,
  1002. expected_bitstream_sha256=digest,
  1003. expected_primary_td_receipt_sha256=primary_sha,
  1004. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1005. ),
  1006. )
  1007. info["commit"] = "a" * 8
  1008. info_path.write_text(json.dumps(info), encoding="utf-8")
  1009. (package / "fw.bit").write_bytes(b"tampered")
  1010. self.assertIn(
  1011. "package:file_hash",
  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. incomplete = valid_package_receipt(package, digest=digest)
  1021. incomplete["verification_complete"] = False
  1022. self.assertIn(
  1023. "package:verification_incomplete",
  1024. harness._package_final_failures(
  1025. incomplete,
  1026. expected_commit="a" * 8,
  1027. expected_bitstream_sha256=digest,
  1028. expected_primary_td_receipt_sha256=primary_sha,
  1029. expected_confirmation_td_receipt_sha256=confirmation_sha,
  1030. ),
  1031. )
  1032. def test_final_package_rechecks_closed_normal_package_and_external_td_bindings(self) -> None:
  1033. mutations = (
  1034. ("urgent_receipt", "package:delivery_mode", lambda package, receipt: receipt.__setitem__("delivery_mode", "urgent_single_td")),
  1035. ("urgent_info", "package:info_delivery_mode", lambda package, receipt: update_package_info(package, delivery_mode="urgent_single_td")),
  1036. ("false_info_verification", "package:info_verification_incomplete", lambda package, receipt: update_package_info(package, verification_complete=False)),
  1037. ("false_info_confirmation", "package:info_confirmation_td_missing", lambda package, receipt: update_package_info(package, confirmation_td_present=False)),
  1038. ("missing_confirmation", "package:required_file", lambda package, receipt: (package / "evidence" / "td-confirmation-receipt.json").unlink()),
  1039. ("missing_validation", "package:required_file", lambda package, receipt: (package / "evidence" / "validation-summary.json").unlink()),
  1040. ("missing_selftest", "package:required_file", lambda package, receipt: (package / "evidence" / "package-selftest-result.json").unlink()),
  1041. )
  1042. for name, expected, mutate in mutations:
  1043. with self.subTest(name=name), tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1044. package = Path(temporary) / "package"
  1045. receipt, _, _ = materialize_valid_package(package)
  1046. mutate(package, receipt)
  1047. failures = harness._package_final_failures(
  1048. receipt,
  1049. expected_commit="a" * 8,
  1050. expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
  1051. expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
  1052. expected_confirmation_td_receipt_sha256=str(
  1053. receipt["confirmation_td_receipt_sha256"]
  1054. ),
  1055. )
  1056. self.assertTrue(
  1057. any(item.startswith(expected) for item in failures),
  1058. failures,
  1059. )
  1060. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1061. package = Path(temporary) / "package"
  1062. receipt, _, _ = materialize_valid_package(package)
  1063. failures = harness._package_final_failures(
  1064. receipt,
  1065. expected_commit="a" * 8,
  1066. expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
  1067. expected_primary_td_receipt_sha256="0" * 64,
  1068. expected_confirmation_td_receipt_sha256="1" * 64,
  1069. )
  1070. self.assertIn("package:primary_td_external_binding", failures)
  1071. self.assertIn("package:confirmation_td_external_binding", failures)
  1072. def test_td_final_reopens_cdc_and_fsm_structure_contracts(self) -> None:
  1073. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1074. bitstream = Path(temporary) / "td.bit"
  1075. bitstream.write_bytes(b"td-structure-contract")
  1076. receipt = valid_td_receipt(bitstream)
  1077. receipt["structural_gate"]["cdc"]["retained_sync_registers"][
  1078. "used"
  1079. ] = 8
  1080. receipt["structural_gate"]["fsm_encoding"]["axes"] = {
  1081. "x": 3,
  1082. "y": 3,
  1083. }
  1084. failures = harness._td_final_failures(
  1085. receipt,
  1086. label="td",
  1087. expected_commit="a" * 8,
  1088. )
  1089. self.assertIn("td:structural_gate:cdc", failures)
  1090. self.assertIn("td:structural_gate:fsm_encoding", failures)
  1091. def test_package_selftest_rejects_a_different_verification_run(self) -> None:
  1092. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1093. package = Path(temporary) / "package"
  1094. materialize_valid_package(package)
  1095. completed = subprocess.CompletedProcess(
  1096. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1097. )
  1098. with mock.patch.object(
  1099. harness.subprocess,
  1100. "run",
  1101. return_value=completed,
  1102. ):
  1103. observed = harness.package_selftest_payload(
  1104. package,
  1105. verification_run_id="e" * 32,
  1106. )
  1107. self.assertEqual(observed["status"], "fail")
  1108. self.assertIn(
  1109. "verification_run_id_mismatch:package_info",
  1110. observed["failures"],
  1111. )
  1112. def test_package_selftest_rejects_every_non_sha8_commit_form(self) -> None:
  1113. invalid_commits = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
  1114. for commit in invalid_commits:
  1115. with self.subTest(commit=commit), tempfile.TemporaryDirectory(
  1116. dir=ROOT.parent
  1117. ) as temporary:
  1118. digest = hashlib.sha256(b"invalid-commit-package").hexdigest()
  1119. package = (
  1120. Path(temporary)
  1121. / commit
  1122. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1123. )
  1124. materialize_valid_package(
  1125. package,
  1126. bitstream_bytes=b"invalid-commit-package",
  1127. commit=commit,
  1128. )
  1129. completed = subprocess.CompletedProcess(
  1130. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1131. )
  1132. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1133. observed = harness.package_selftest_payload(
  1134. package,
  1135. verification_run_id=VERIFICATION_RUN_ID,
  1136. )
  1137. self.assertEqual(observed["status"], "fail")
  1138. self.assertIn("package_commit_invalid", observed["failures"])
  1139. def test_package_validator_preserves_running_but_final_gate_rejects_it(self) -> None:
  1140. bitstream_bytes = b"running-validation-package"
  1141. digest = hashlib.sha256(bitstream_bytes).hexdigest()
  1142. commit = "a" * 8
  1143. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1144. package = (
  1145. Path(temporary)
  1146. / commit
  1147. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1148. )
  1149. receipt, _, _ = materialize_valid_package(
  1150. package,
  1151. bitstream_bytes=bitstream_bytes,
  1152. commit=commit,
  1153. )
  1154. validation_path = package / "evidence" / "validation-summary.json"
  1155. validation = json.loads(validation_path.read_text(encoding="utf-8"))
  1156. validation["layers"]["td_confirmation"]["status"] = "running"
  1157. validation_path.write_text(json.dumps(validation), encoding="utf-8")
  1158. refresh_package_bindings(package, receipt)
  1159. completed = subprocess.CompletedProcess(
  1160. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1161. )
  1162. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1163. observed = harness.package_selftest_payload(
  1164. package,
  1165. verification_run_id=VERIFICATION_RUN_ID,
  1166. )
  1167. self.assertEqual(observed["status"], "pass", observed["failures"])
  1168. self.assertEqual(observed["validation_status"], "running")
  1169. receipt.update(observed)
  1170. failures = harness._package_final_failures(
  1171. receipt,
  1172. expected_commit=commit,
  1173. expected_bitstream_sha256=digest,
  1174. expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
  1175. expected_confirmation_td_receipt_sha256=str(
  1176. receipt["confirmation_td_receipt_sha256"]
  1177. ),
  1178. )
  1179. self.assertIn("package:validation_incomplete", failures)
  1180. def test_package_selftest_rejects_non_independent_td_receipts(self) -> None:
  1181. cases = (
  1182. ("run_id", "td_run_id_not_independent"),
  1183. ("work_root", "td_work_root_not_independent"),
  1184. )
  1185. for field, failure in cases:
  1186. with self.subTest(field=field), tempfile.TemporaryDirectory(
  1187. dir=ROOT.parent
  1188. ) as temporary:
  1189. commit = "a" * 8
  1190. digest = hashlib.sha256(b"independent-package-selftest").hexdigest()
  1191. package = (
  1192. Path(temporary)
  1193. / commit
  1194. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1195. )
  1196. receipt, primary, confirmation = materialize_valid_package(
  1197. package,
  1198. bitstream_bytes=b"independent-package-selftest",
  1199. commit=commit,
  1200. )
  1201. confirmation[field] = primary[field]
  1202. (package / "evidence" / "td-confirmation-receipt.json").write_text(
  1203. json.dumps(confirmation),
  1204. encoding="utf-8",
  1205. )
  1206. refresh_package_bindings(package, receipt)
  1207. completed = subprocess.CompletedProcess(
  1208. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1209. )
  1210. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1211. observed = harness.package_selftest_payload(
  1212. package,
  1213. verification_run_id=VERIFICATION_RUN_ID,
  1214. )
  1215. self.assertEqual(observed["status"], "fail")
  1216. self.assertIn(failure, observed["failures"])
  1217. def test_urgent_validator_allows_running_td_confirmation_only(self) -> None:
  1218. bitstream_bytes = b"urgent-running-confirmation"
  1219. digest = hashlib.sha256(bitstream_bytes).hexdigest()
  1220. commit = "a" * 8
  1221. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1222. package = (
  1223. Path(temporary)
  1224. / commit
  1225. / f"prod2u-p4-normal-{commit}-{digest[:16]}"
  1226. )
  1227. receipt, _, _ = materialize_valid_package(
  1228. package,
  1229. bitstream_bytes=bitstream_bytes,
  1230. commit=commit,
  1231. )
  1232. (package / "evidence" / "td-confirmation-receipt.json").unlink()
  1233. info_path = package / "package-info.json"
  1234. info = json.loads(info_path.read_text(encoding="utf-8"))
  1235. info.update(
  1236. {
  1237. "delivery_mode": "urgent_single_td",
  1238. "verification_complete": False,
  1239. "confirmation_td_present": False,
  1240. "confirmation_bitstream_sha256": None,
  1241. "confirmation_synthesis_input_hash": None,
  1242. }
  1243. )
  1244. info_path.write_text(json.dumps(info), encoding="utf-8")
  1245. validation_path = package / "evidence" / "validation-summary.json"
  1246. validation = json.loads(validation_path.read_text(encoding="utf-8"))
  1247. validation.update(
  1248. {
  1249. "delivery_mode": "urgent_single_td",
  1250. "verification_complete": False,
  1251. "confirmation_td_present": False,
  1252. }
  1253. )
  1254. validation["layers"]["td_confirmation"]["status"] = "running"
  1255. for name in (
  1256. "td_confirmation_artifacts",
  1257. "td_confirmation_bitstream",
  1258. "td_confirmation_synthesis",
  1259. "td_confirmation_manifest",
  1260. "resource_confirmation",
  1261. ):
  1262. validation["layers"][name]["status"] = "not_run"
  1263. validation_path.write_text(json.dumps(validation), encoding="utf-8")
  1264. refresh_package_bindings(package, receipt)
  1265. completed = subprocess.CompletedProcess(
  1266. ["powershell.exe"], 0, stdout="selftest pass", stderr=""
  1267. )
  1268. with mock.patch.object(harness.subprocess, "run", return_value=completed):
  1269. observed = harness.package_selftest_payload(
  1270. package,
  1271. verification_run_id=VERIFICATION_RUN_ID,
  1272. )
  1273. self.assertEqual(observed["status"], "pass", observed["failures"])
  1274. self.assertEqual(observed["validation_status"], "running")
  1275. def test_final_gate_rejects_two_td_receipts_from_same_run_or_work_root(self) -> None:
  1276. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  1277. root = Path(temporary)
  1278. bitstream = root / "td.bit"
  1279. bitstream.write_bytes(b"two-build-final-gate")
  1280. digest = harness.sha256_file(bitstream)
  1281. package = root / "package"
  1282. package_receipt, packaged_primary, packaged_confirmation = (
  1283. materialize_valid_package(
  1284. package,
  1285. bitstream_bytes=bitstream.read_bytes(),
  1286. )
  1287. )
  1288. primary = packaged_primary
  1289. confirmation = copy.deepcopy(packaged_primary)
  1290. packaged_confirmation = confirmation
  1291. receipts = {
  1292. "offline": valid_offline_receipt(),
  1293. "td": primary,
  1294. "td_confirmation": confirmation,
  1295. "package": package_receipt,
  1296. }
  1297. paths = {}
  1298. for name, payload in receipts.items():
  1299. path = root / f"{name}.json"
  1300. path.write_text(json.dumps(payload), encoding="utf-8")
  1301. paths[name] = path
  1302. args = argparse.Namespace(
  1303. offline_receipt=paths["offline"],
  1304. td_receipt=paths["td"],
  1305. confirmation_td_receipt=paths["td_confirmation"],
  1306. package_receipt=paths["package"],
  1307. verification_run_id=VERIFICATION_RUN_ID,
  1308. report_file=None,
  1309. json=False,
  1310. )
  1311. with (
  1312. mock.patch.object(
  1313. harness,
  1314. "source_state",
  1315. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1316. ),
  1317. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1318. ):
  1319. rejected = harness.cmd_final_gate(args)
  1320. self.assertEqual(rejected["status"], "fail")
  1321. self.assertIn("td_run_id_not_independent", rejected["failures"])
  1322. self.assertIn("td_work_root_not_independent", rejected["failures"])
  1323. confirmation["run_id"] = "2" * 32
  1324. confirmation["work_root"] = "C:/td-b"
  1325. packaged_confirmation["run_id"] = confirmation["run_id"]
  1326. packaged_confirmation["work_root"] = confirmation["work_root"]
  1327. packaged_primary_path = package / "evidence" / "td-primary-receipt.json"
  1328. packaged_confirmation_path = (
  1329. package / "evidence" / "td-confirmation-receipt.json"
  1330. )
  1331. packaged_primary_path.write_text(
  1332. json.dumps(packaged_primary), encoding="utf-8"
  1333. )
  1334. packaged_confirmation_path.write_text(
  1335. json.dumps(packaged_confirmation), encoding="utf-8"
  1336. )
  1337. refresh_package_bindings(package, package_receipt)
  1338. paths["package"].write_text(json.dumps(package_receipt), encoding="utf-8")
  1339. paths["td_confirmation"].write_text(json.dumps(confirmation), encoding="utf-8")
  1340. with (
  1341. mock.patch.object(
  1342. harness,
  1343. "source_state",
  1344. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1345. ),
  1346. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1347. ):
  1348. accepted = harness.cmd_final_gate(args)
  1349. self.assertEqual(accepted["status"], "pass", accepted["failures"])
  1350. confirmation["bitstream_sha256"] = "f" * 64
  1351. paths["td_confirmation"].write_text(
  1352. json.dumps(confirmation), encoding="utf-8"
  1353. )
  1354. with (
  1355. mock.patch.object(
  1356. harness,
  1357. "source_state",
  1358. return_value={"status": "pass", "commit": "a" * 8, "clean": True},
  1359. ),
  1360. mock.patch.object(
  1361. harness,
  1362. "_emit",
  1363. side_effect=lambda payload, _args, _label: payload,
  1364. ),
  1365. ):
  1366. bitstream_mismatch = harness.cmd_final_gate(args)
  1367. self.assertEqual(bitstream_mismatch["status"], "fail")
  1368. self.assertIn(
  1369. "td_bitstream_sha256_mismatch",
  1370. bitstream_mismatch["failures"],
  1371. )
  1372. confirmation["bitstream_sha256"] = digest
  1373. paths["td_confirmation"].write_text(
  1374. json.dumps(confirmation), encoding="utf-8"
  1375. )
  1376. with (
  1377. mock.patch.object(
  1378. harness,
  1379. "source_state",
  1380. return_value={"status": "fail", "commit": "a" * 8, "clean": False},
  1381. ),
  1382. mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
  1383. ):
  1384. dirty = harness.cmd_final_gate(args)
  1385. self.assertEqual(dirty["status"], "fail")
  1386. self.assertIn("final_source_state_not_clean", dirty["failures"])
  1387. if __name__ == "__main__":
  1388. unittest.main()