test_prod2u_p4_harness.py 63 KB

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