test_remote_scripts.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. #!/usr/bin/env python3
  2. """Remote collector and package tests for the converged CPLD project."""
  3. from __future__ import annotations
  4. import json
  5. import hashlib
  6. import shutil
  7. import subprocess
  8. import tempfile
  9. import unittest
  10. from pathlib import Path
  11. ROOT = Path(__file__).resolve().parents[2]
  12. class RemoteScriptTests(unittest.TestCase):
  13. def test_remote_tools_only_expose_latest_real_fan_ptc_collector(self) -> None:
  14. scripts = sorted(path.name for path in (ROOT / "tools" / "remote").glob("*.ps1"))
  15. self.assertEqual(scripts, ["collect-j6-host-sensor-real-fan-ptc.ps1"])
  16. self.assertFalse((ROOT / "tools" / "serial_debug_capture.py").exists())
  17. self.assertFalse((ROOT / "tools" / "windows_serial_validation.py").exists())
  18. def test_collect_j6_host_sensor_real_fan_ptc_is_static_allowlisted_host_writer_and_debug_reader(self) -> None:
  19. script = (ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1").read_text(
  20. encoding="utf-8"
  21. )
  22. for marker in [
  23. "System.IO.Ports.SerialPort",
  24. "[ValidatePattern('^COM[0-9]+$')]",
  25. "HostPort",
  26. "DebugPort",
  27. 'if (-not $SelfTest -and $HostPort -eq $DebugPort)',
  28. 'if (-not $SelfTest -and $HostPort -ne "COM8")',
  29. 'if (-not $SelfTest -and $DebugPort -ne "COM7")',
  30. "BaudRate = 115200",
  31. "DebugBaud = 921600",
  32. "DtrEnable = $false",
  33. "RtsEnable = $false",
  34. "host-port-raw.bin",
  35. "host-port-escaped.txt",
  36. "debug-uart-raw.bin",
  37. "debug-uart-escaped.txt",
  38. "bmc-raw-replay.bin",
  39. "host-sensor-report.json",
  40. "debug-frame-stream.json",
  41. "host-command-transcript.json",
  42. "j6-host-sensor-real-fan-ptc-capture-manifest.json",
  43. "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-draft.json",
  44. "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1",
  45. "J6CMD",
  46. "J6RAW",
  47. "J6EVT",
  48. "J6PWM",
  49. "J6MOD",
  50. "J6STAT",
  51. "J6MAP",
  52. "J6TEMP",
  53. "SENS",
  54. "DIMM",
  55. "PTCCH",
  56. "FANCH",
  57. "SET PTC 01 10",
  58. "SET PTC 24 20",
  59. "SET FAN 01 40",
  60. "SET FAN 04 30",
  61. "SET PID ENABLE",
  62. "GET STATUS",
  63. "GET MAP",
  64. "GET SENSOR",
  65. "SET PID DISABLE",
  66. "DISABLE",
  67. "host_port_writes_to_serial",
  68. "debug_port_writes_to_serial",
  69. "driver_install_attempted = $false",
  70. "enumerates_com_ports = $false",
  71. "opens_unknown_com_ports = $false",
  72. "AssumeManualSramProgrammed",
  73. "PROGRAM_SRAM",
  74. "JtagSpeedHz",
  75. "BoardPowerPresentBeforeProgram",
  76. "jtag_speed_hz",
  77. "board_power_present_before_program",
  78. "SelfTest",
  79. "startup-preflight.json",
  80. "READY",
  81. "J6READY",
  82. "preflight",
  83. "blocked_waiting_for_ready_epoch",
  84. ]:
  85. self.assertIn(marker, script)
  86. self.assertIn("$hostSerial.Write", script)
  87. self.assertNotIn("$debugSerial.Write", script)
  88. for forbidden in [
  89. "SET PTC 00",
  90. "SET FAN 00",
  91. "SET FAN 05",
  92. "SET FAN 06",
  93. "GetPortNames",
  94. "Win32_SerialPort",
  95. "Get-CimInstance",
  96. "Get-WmiObject",
  97. "pip install",
  98. "pyserial",
  99. "python",
  100. "pnputil",
  101. "devcon",
  102. "install-driver",
  103. "add-windowsdriver",
  104. "driverquery",
  105. "PROGRAM_FLASH",
  106. "ERASE_FLASH",
  107. "PROGRAM_SPIBIN",
  108. "DIRECT_FLASH_WRITE",
  109. "blocked_edit_required",
  110. ]:
  111. self.assertNotIn(forbidden.lower(), script.lower())
  112. def test_collect_j6_host_sensor_real_fan_ptc_has_startup_preflight_selftest(self) -> None:
  113. powershell = shutil.which("powershell")
  114. if powershell is None:
  115. self.skipTest("PowerShell is not available")
  116. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  117. result = subprocess.run(
  118. [
  119. powershell,
  120. "-NoProfile",
  121. "-ExecutionPolicy",
  122. "Bypass",
  123. "-File",
  124. str(script_path),
  125. "-SelfTest",
  126. ],
  127. cwd=ROOT,
  128. text=True,
  129. capture_output=True,
  130. check=False,
  131. )
  132. output = result.stderr + result.stdout
  133. self.assertEqual(result.returncode, 0, output)
  134. for marker in [
  135. "selftest=pass",
  136. "ready_line=READY profile=temp-uart-ptc-remap seq=00000000",
  137. "j6ready_line=J6READY profile=temp-uart-ptc-remap",
  138. "epoch_locked=pass",
  139. "pre_sram_noise=OK seq=0000000D cmd=STATUS",
  140. "post_j6ready_raw_replay=pass",
  141. "formal_ack=OK seq=00000001 cmd=PTCCH",
  142. "stale_ack_isolated=pass",
  143. "tail_drain=pass",
  144. "jtag_speed_hz=200000",
  145. "board_power_present_before_program=true",
  146. "post_j6stat_tail_bytes=04",
  147. "complete_unterminated_j6raw=pass",
  148. "incomplete_final_line=J6RAW s=0004",
  149. ]:
  150. self.assertIn(marker, output)
  151. def test_collect_j6_host_sensor_real_fan_ptc_accepts_native_bool_argument_shape(self) -> None:
  152. powershell = shutil.which("powershell")
  153. if powershell is None:
  154. self.skipTest("PowerShell is not available")
  155. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  156. result = subprocess.run(
  157. [
  158. powershell,
  159. "-NoProfile",
  160. "-ExecutionPolicy",
  161. "Bypass",
  162. "-File",
  163. str(script_path),
  164. "-SelfTest",
  165. "-AssumeManualSramProgrammed",
  166. "$true",
  167. ],
  168. cwd=ROOT,
  169. text=True,
  170. capture_output=True,
  171. check=False,
  172. )
  173. output = result.stderr + result.stdout
  174. self.assertEqual(result.returncode, 0, output)
  175. self.assertIn("selftest=pass", output)
  176. def test_collect_j6_host_sensor_real_fan_ptc_handles_discarded_ack_arrays(self) -> None:
  177. powershell = shutil.which("powershell")
  178. if powershell is None:
  179. self.skipTest("PowerShell is not available")
  180. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  181. script = script_path.read_text(encoding="utf-8-sig")
  182. helper_start = script.index("function Read-HostPortAvailableLines")
  183. helper_end = script.index("function Invoke-StartupPreflight")
  184. helpers = script[helper_start:helper_end]
  185. with tempfile.TemporaryDirectory() as tmp:
  186. probe_path = Path(tmp) / "probe.ps1"
  187. probe_path.write_text(
  188. helpers
  189. + """
  190. $hostRaw = New-Object System.Collections.Generic.List[byte]
  191. $hostWindow = New-Object System.Text.StringBuilder
  192. $hostReports = New-Object System.Collections.Generic.List[object]
  193. $queue = New-Object System.Collections.Generic.Queue[object]
  194. $queue.Enqueue([ordered]@{
  195. ack_line = "OK seq=00000001 cmd=STATUS"
  196. raw = "OK seq=00000001 cmd=STATUS"
  197. token = "OK seq=00000001 cmd=STATUS"
  198. class = "ok"
  199. seq = 1
  200. cmd = "STATUS"
  201. ack_offset = 1
  202. response_offset = 1
  203. delimiter = "CR"
  204. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  205. }) | Out-Null
  206. $queue.Enqueue([ordered]@{
  207. ack_line = "OK seq=00000001 cmd=PTCCH"
  208. raw = "OK seq=00000001 cmd=PTCCH"
  209. token = "OK seq=00000001 cmd=PTCCH"
  210. class = "ok"
  211. seq = 1
  212. cmd = "PTCCH"
  213. ack_offset = 10
  214. response_offset = 10
  215. delimiter = "CR"
  216. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  217. }) | Out-Null
  218. $serial = [pscustomobject]@{ BytesToRead = 0 }
  219. $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $queue 5 200 1 "PTCCH"
  220. if ($ack.ack_line -ne "OK seq=00000001 cmd=PTCCH") { throw "candidate ack not returned: $($ack.ack_line)" }
  221. if ($ack.discarded_acks.Count -ne 1) { throw "discarded ack count was $($ack.discarded_acks.Count)" }
  222. if (-not $ack.discarded_acks[0].stale) { throw "discarded ack was not marked stale" }
  223. """,
  224. encoding="utf-8",
  225. )
  226. result = subprocess.run(
  227. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  228. cwd=ROOT,
  229. text=True,
  230. capture_output=True,
  231. check=False,
  232. )
  233. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  234. def test_collect_j6_host_sensor_real_fan_ptc_epoch_lock_discards_pre_sram_ack_noise(self) -> None:
  235. powershell = shutil.which("powershell")
  236. if powershell is None:
  237. self.skipTest("PowerShell is not available")
  238. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  239. script = script_path.read_text(encoding="utf-8-sig")
  240. helper_start = script.index("function Read-HostPortAvailableLines")
  241. helper_end = script.index("function Invoke-CollectorSelfTest")
  242. helpers = script[helper_start:helper_end]
  243. with tempfile.TemporaryDirectory() as tmp:
  244. probe_path = Path(tmp) / "probe.ps1"
  245. probe_path.write_text(
  246. helpers
  247. + """
  248. $preflight = New-StartupPreflightRecord
  249. $ackQueue = New-Object System.Collections.Generic.Queue[object]
  250. $ackQueue.Enqueue([ordered]@{
  251. ack_line = "OK seq=0000000D cmd=STATUS"
  252. raw = "OK seq=0000000D cmd=STATUS"
  253. token = "OK seq=0000000D cmd=STATUS"
  254. class = "ok"
  255. seq = 13
  256. cmd = "STATUS"
  257. ack_offset = 25
  258. response_offset = 25
  259. delimiter = "CR"
  260. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  261. }) | Out-Null
  262. $preReadyDiscard = @(Clear-HostAckQueue $ackQueue)
  263. Add-PreSramNoise $preflight "ack" $preReadyDiscard[0]
  264. $hostReady = [ordered]@{ kind = "ready"; raw = "READY profile=temp-uart-ptc-remap seq=00000000"; fields = [ordered]@{} }
  265. $debugReady = [ordered]@{ kind = "j6ready"; raw = "J6READY profile=temp-uart-ptc-remap"; fields = [ordered]@{} }
  266. Update-PreflightEpochReady $preflight $hostReady 100 200
  267. Update-PreflightEpochReady $preflight $debugReady 300 400
  268. Complete-StartupPreflightRecord $preflight
  269. if ($preflight.status -ne "pass") { throw "preflight status was $($preflight.status)" }
  270. if (-not $preflight.epoch_locked) { throw "epoch was not locked" }
  271. if ($preflight.sync_ack_seen) { throw "preflight incorrectly accepted sync ack" }
  272. if ($preflight.pre_sram_noise_count -ne 1) { throw "pre_sram_noise_count was $($preflight.pre_sram_noise_count)" }
  273. if ($preflight.pre_sram_noise[0].ack_line -ne "OK seq=0000000D cmd=STATUS") { throw "wrong pre_sram noise ack" }
  274. if ($preflight.epoch_locked_at_host_offset -ne 100) { throw "wrong host epoch offset" }
  275. if ($preflight.epoch_locked_at_debug_offset -ne 400) { throw "wrong debug epoch offset" }
  276. $ackQueue.Enqueue([ordered]@{
  277. ack_line = "OK seq=00000001 cmd=PTCCH"
  278. raw = "OK seq=00000001 cmd=PTCCH"
  279. token = "OK seq=00000001 cmd=PTCCH"
  280. class = "ok"
  281. seq = 1
  282. cmd = "PTCCH"
  283. ack_offset = 150
  284. response_offset = 150
  285. delimiter = "CR"
  286. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  287. }) | Out-Null
  288. $serial = [pscustomobject]@{ BytesToRead = 0 }
  289. $hostRaw = New-Object System.Collections.Generic.List[byte]
  290. $hostWindow = New-Object System.Text.StringBuilder
  291. $hostReports = New-Object System.Collections.Generic.List[object]
  292. $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $ackQueue 120 200 1 "PTCCH"
  293. if ($ack.ack_line -ne "OK seq=00000001 cmd=PTCCH") { throw "formal ack not returned: $($ack.ack_line)" }
  294. if (-not $ack.seq_match -or -not $ack.cmd_match) { throw "formal ack mismatch" }
  295. """,
  296. encoding="utf-8",
  297. )
  298. result = subprocess.run(
  299. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  300. cwd=ROOT,
  301. text=True,
  302. capture_output=True,
  303. check=False,
  304. )
  305. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  306. def test_collect_j6_host_sensor_real_fan_ptc_marks_clear_queue_results_as_pre_sram_noise(self) -> None:
  307. powershell = shutil.which("powershell")
  308. if powershell is None:
  309. self.skipTest("PowerShell is not available")
  310. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  311. script = script_path.read_text(encoding="utf-8-sig")
  312. helper_start = script.index("function Clear-HostAckQueue")
  313. helper_end = script.index("function Update-PreflightEpochReady")
  314. helpers = script[helper_start:helper_end]
  315. with tempfile.TemporaryDirectory() as tmp:
  316. probe_path = Path(tmp) / "probe.ps1"
  317. probe_path.write_text(
  318. helpers
  319. + """
  320. $preflight = New-StartupPreflightRecord
  321. $ackQueue = New-Object System.Collections.Generic.Queue[object]
  322. $ackQueue.Enqueue([ordered]@{
  323. ack_line = "OK seq=0000000D cmd=STATUS"
  324. raw = "OK seq=0000000D cmd=STATUS"
  325. token = "OK seq=0000000D cmd=STATUS"
  326. class = "ok"
  327. seq = 13
  328. cmd = "STATUS"
  329. ack_offset = 25
  330. response_offset = 25
  331. delimiter = "CR"
  332. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  333. }) | Out-Null
  334. $moreStale = @(Clear-HostAckQueue $ackQueue)
  335. foreach ($ack in $moreStale) {
  336. Set-AckMetadata $ack "pre_sram_noise" $true
  337. Add-PreSramNoise $preflight "ack" $ack
  338. }
  339. if ($moreStale.Count -ne 1) { throw "unexpected stale count $($moreStale.Count)" }
  340. if ($moreStale[0] -is [array]) { throw "stale ack was nested array" }
  341. if (-not $moreStale[0].pre_sram_noise) { throw "pre_sram_noise was not set" }
  342. if ($preflight.pre_sram_noise_count -ne 1) { throw "preflight noise count was $($preflight.pre_sram_noise_count)" }
  343. if ($preflight.pre_sram_noise[0].ack_line -ne "OK seq=0000000D cmd=STATUS") { throw "wrong pre_sram noise ack" }
  344. """,
  345. encoding="utf-8",
  346. )
  347. result = subprocess.run(
  348. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  349. cwd=ROOT,
  350. text=True,
  351. capture_output=True,
  352. check=False,
  353. )
  354. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  355. def test_collect_j6_host_sensor_real_fan_ptc_handles_timeout_discarded_ack_arrays(self) -> None:
  356. powershell = shutil.which("powershell")
  357. if powershell is None:
  358. self.skipTest("PowerShell is not available")
  359. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  360. script = script_path.read_text(encoding="utf-8-sig")
  361. helper_start = script.index("function Read-HostPortAvailableLines")
  362. helper_end = script.index("function Invoke-StartupPreflight")
  363. helpers = script[helper_start:helper_end]
  364. with tempfile.TemporaryDirectory() as tmp:
  365. probe_path = Path(tmp) / "probe.ps1"
  366. probe_path.write_text(
  367. helpers
  368. + """
  369. $hostRaw = New-Object System.Collections.Generic.List[byte]
  370. $hostWindow = New-Object System.Text.StringBuilder
  371. $hostReports = New-Object System.Collections.Generic.List[object]
  372. $queue = New-Object System.Collections.Generic.Queue[object]
  373. $queue.Enqueue([ordered]@{
  374. ack_line = "OK seq=00000001 cmd=STATUS"
  375. raw = "OK seq=00000001 cmd=STATUS"
  376. token = "OK seq=00000001 cmd=STATUS"
  377. class = "ok"
  378. seq = 1
  379. cmd = "STATUS"
  380. ack_offset = 1
  381. response_offset = 1
  382. delimiter = "CR"
  383. timestamp = (Get-Date).ToUniversalTime().ToString("o")
  384. }) | Out-Null
  385. $serial = [pscustomobject]@{ BytesToRead = 0 }
  386. $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $queue 5 100 1 "PTCCH"
  387. if ($ack.class -ne "timeout") { throw "ack class was $($ack.class)" }
  388. if ($ack.discarded_acks.Count -ne 1) { throw "discarded ack count was $($ack.discarded_acks.Count)" }
  389. if (-not $ack.discarded_acks[0].stale) { throw "discarded ack was not marked stale" }
  390. """,
  391. encoding="utf-8",
  392. )
  393. result = subprocess.run(
  394. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  395. cwd=ROOT,
  396. text=True,
  397. capture_output=True,
  398. check=False,
  399. )
  400. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  401. def test_collect_j6_host_sensor_real_fan_ptc_preserves_empty_raw_replay_byte_array(self) -> None:
  402. powershell = shutil.which("powershell")
  403. if powershell is None:
  404. self.skipTest("PowerShell is not available")
  405. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  406. script = script_path.read_text(encoding="utf-8")
  407. helper_start = script.index("function Convert-HexToBytes")
  408. helper_end = script.index("$out =")
  409. helpers = script[helper_start:helper_end]
  410. with tempfile.TemporaryDirectory() as tmp:
  411. probe_path = Path(tmp) / "probe.ps1"
  412. out_path = Path(tmp) / "empty-replay.bin"
  413. probe_path.write_text(
  414. helpers
  415. + f"""
  416. $events = New-Object System.Collections.Generic.List[object]
  417. $rawReplayArray = New-BmcRawReplay $events
  418. if ($null -eq $rawReplayArray) {{
  419. throw "raw replay array was null"
  420. }}
  421. if ($rawReplayArray.GetType().FullName -ne "System.Byte[]") {{
  422. throw "raw replay array type was $($rawReplayArray.GetType().FullName)"
  423. }}
  424. if ($rawReplayArray.Length -ne 0) {{
  425. throw "raw replay array length was $($rawReplayArray.Length)"
  426. }}
  427. [System.IO.File]::WriteAllBytes("{out_path}", $rawReplayArray)
  428. """,
  429. encoding="utf-8",
  430. )
  431. result = subprocess.run(
  432. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  433. cwd=ROOT,
  434. text=True,
  435. capture_output=True,
  436. check=False,
  437. )
  438. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  439. self.assertTrue(out_path.exists())
  440. self.assertEqual(out_path.stat().st_size, 0)
  441. def test_collect_j6_host_sensor_real_fan_ptc_parses_hex_fields_without_losing_payload_width(self) -> None:
  442. powershell = shutil.which("powershell")
  443. if powershell is None:
  444. self.skipTest("PowerShell is not available")
  445. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  446. script = script_path.read_text(encoding="utf-8")
  447. helper_start = script.index("function Convert-TokenValue")
  448. helper_end = script.index("function Convert-BytesToEscapedText")
  449. replay_helper_start = script.index("function Convert-HexToBytes")
  450. replay_helper_end = script.index("function Get-LastFieldOrDefault")
  451. helpers = script[helper_start:helper_end] + script[replay_helper_start:replay_helper_end]
  452. with tempfile.TemporaryDirectory() as tmp:
  453. probe_path = Path(tmp) / "probe.ps1"
  454. probe_path.write_text(
  455. helpers
  456. + """
  457. $events = New-Object System.Collections.Generic.List[object]
  458. $events.Add((Convert-FrameLine "J6PWM seq=0000000A src=hm pid=disabled timeout=1 ptc01=00 ptc24=00 fan01=1E fan04=1E" @("J6PWM"))) | Out-Null
  459. $events.Add((Convert-FrameLine "J6TEMP seq=00000003 status=valid valid=1E missing=00 fault=0 host_report_drop=00000000" @("J6TEMP"))) | Out-Null
  460. $events.Add((Convert-FrameLine "J6RAW seq=00000001 off=00000000 len=02 sum=0031 data=0031" @("J6RAW"))) | Out-Null
  461. $events.Add((Convert-FrameLine "J6RAW s=002A o=00000100 l=04 u=000A d=01020304" @("J6RAW"))) | Out-Null
  462. $events.Add((Convert-FrameLine "J6EVT s=06 cmd=PID_E c=01 p=000 ok=1 e=0 to=0" @("J6EVT"))) | Out-Null
  463. $events.Add((Convert-FrameLine "DIMM i=10 t=00 m=1" @("DIMM"))) | Out-Null
  464. foreach ($probe in @(
  465. @($events[0].fields.fan01, "fan01"),
  466. @($events[0].fields.timeout, "timeout"),
  467. @($events[1].fields.valid, "valid"),
  468. @($events[1].fields.missing, "missing"),
  469. @($events[2].fields.len, "len"),
  470. @($events[2].fields.sum, "sum"),
  471. @($events[3].fields.seq, "compact_seq"),
  472. @($events[3].fields.off, "compact_off"),
  473. @($events[3].fields.len, "compact_len"),
  474. @($events[3].fields.sum, "compact_sum"),
  475. @($events[4].fields.ch, "compact_ch"),
  476. @($events[4].fields.pct, "compact_pct"),
  477. @($events[4].fields.err, "compact_err")
  478. )) {
  479. if ($probe[0].GetType().FullName -ne "System.Int64") {
  480. throw "$($probe[1]) parsed as $($probe[0].GetType().FullName)"
  481. }
  482. }
  483. if ([int64]$events[0].fields.fan01 -ne 30) { throw "fan01 was $($events[0].fields.fan01)" }
  484. if ([int64]$events[0].fields.timeout -ne 1) { throw "timeout was $($events[0].fields.timeout)" }
  485. if ([int64]$events[1].fields.valid -ne 30) { throw "valid was $($events[1].fields.valid)" }
  486. if ([int64]$events[1].fields.missing -ne 0) { throw "missing was $($events[1].fields.missing)" }
  487. if ([int64]$events[2].fields.len -ne 2) { throw "len was $($events[2].fields.len)" }
  488. if ([int64]$events[2].fields.sum -ne 49) { throw "sum was $($events[2].fields.sum)" }
  489. if ([int64]$events[3].fields.seq -ne 42) { throw "compact seq was $($events[3].fields.seq)" }
  490. if ([int64]$events[3].fields.off -ne 256) { throw "compact off was $($events[3].fields.off)" }
  491. if ([int64]$events[3].fields.len -ne 4) { throw "compact len was $($events[3].fields.len)" }
  492. if ([int64]$events[3].fields.sum -ne 10) { throw "compact sum was $($events[3].fields.sum)" }
  493. if ($events[2].fields.data.GetType().FullName -ne "System.String") { throw "data parsed as $($events[2].fields.data.GetType().FullName)" }
  494. if ($events[2].fields.data -ne "0031") { throw "data was $($events[2].fields.data)" }
  495. if ($events[3].fields.data -ne "01020304") { throw "compact data was $($events[3].fields.data)" }
  496. if ([int64]$events[4].fields.ch -ne 1) { throw "compact ch was $($events[4].fields.ch)" }
  497. if ([int64]$events[4].fields.pct -ne 0) { throw "compact pct was $($events[4].fields.pct)" }
  498. if ([int64]$events[4].fields.err -ne 0) { throw "compact err was $($events[4].fields.err)" }
  499. if ([int64]$events[5].fields.id -ne 16) { throw "dimm id was $($events[5].fields.id)" }
  500. $replay = New-BmcRawReplay $events
  501. $replayHex = (($replay | ForEach-Object { $_.ToString("X2") }) -join "")
  502. if ($replayHex -ne "003101020304") { throw "replay was $replayHex" }
  503. """,
  504. encoding="utf-8",
  505. )
  506. result = subprocess.run(
  507. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  508. cwd=ROOT,
  509. text=True,
  510. capture_output=True,
  511. check=False,
  512. )
  513. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  514. def test_collect_j6_host_sensor_real_fan_ptc_keeps_command_tokens_as_strings(self) -> None:
  515. powershell = shutil.which("powershell")
  516. if powershell is None:
  517. self.skipTest("PowerShell is not available")
  518. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  519. script = script_path.read_text(encoding="utf-8")
  520. helper_start = script.index("function Convert-TokenValue")
  521. helper_end = script.index("function Convert-BytesToEscapedText")
  522. helpers = script[helper_start:helper_end]
  523. with tempfile.TemporaryDirectory() as tmp:
  524. probe_path = Path(tmp) / "probe.ps1"
  525. probe_path.write_text(
  526. helpers
  527. + """
  528. $events = New-Object System.Collections.Generic.List[object]
  529. $events.Add((Convert-FrameLine "J6CMD seq=00000001 cmd=raw text=ipmitool" @("J6CMD"))) | Out-Null
  530. $events.Add((Convert-FrameLine "J6EVT seq=00000002 ok=1 err=0 type=PTCCH ch=01 pct=0A" @("J6EVT"))) | Out-Null
  531. $events.Add((Convert-FrameLine "OK seq=00000003 cmd=FANCH" @("OK"))) | Out-Null
  532. if ($events[0].fields.cmd -ne "raw") { throw "cmd was $($events[0].fields.cmd)" }
  533. if ($events[1].fields.type -ne "PTCCH") { throw "type was $($events[1].fields.type)" }
  534. if ($events[1].fields.ch.GetType().FullName -ne "System.Int64") { throw "ch type was $($events[1].fields.ch.GetType().FullName)" }
  535. if ([int64]$events[1].fields.ch -ne 1) { throw "ch was $($events[1].fields.ch)" }
  536. if ([int64]$events[1].fields.pct -ne 10) { throw "pct was $($events[1].fields.pct)" }
  537. if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.cmd)" }
  538. """,
  539. encoding="utf-8",
  540. )
  541. result = subprocess.run(
  542. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  543. cwd=ROOT,
  544. text=True,
  545. capture_output=True,
  546. check=False,
  547. )
  548. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  549. def test_j6_host_sensor_real_fan_ptc_package_script_creates_temp_profile_package(self) -> None:
  550. script = (ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1").read_text(
  551. encoding="utf-8"
  552. )
  553. for marker in [
  554. "START-HERE.zh-CN.md",
  555. "tools\\remote\\collect-j6-host-sensor-real-fan-ptc.ps1",
  556. "tools\\bmc_replay_uart.py",
  557. "bitstreams",
  558. "td-receipts",
  559. "commands",
  560. "bmc-replay",
  561. "pin_inventory.fcb_fpga_mcu0611.json",
  562. "sha256-inventory.json",
  563. "Compress-Archive",
  564. ".zip.sha256.txt",
  565. "j6-bmc-replay",
  566. "j6tmp.bit",
  567. "collect.ps1",
  568. "capture-bmc.ps1",
  569. "replay-bmc.ps1",
  570. "td.json",
  571. "debug-photo-uart-bmc-replay",
  572. "formal-uart1-bmc-replay",
  573. "pc_replay_from_real_bmc_capture",
  574. "startup-preflight.json",
  575. "collector first, then PROGRAM_SRAM",
  576. "tail drain",
  577. "ForceOverwrite",
  578. "FormalBlocked",
  579. "FORMAL-BLOCKED.zh-CN.md",
  580. "SET PTC 01 10",
  581. "SET PTC 24 20",
  582. "SET FAN 01 40",
  583. "SET FAN 04 30",
  584. "excluded_self_referential_file",
  585. ]:
  586. self.assertIn(marker, script)
  587. self.assertNotIn("Set-ExecutionPolicy", script)
  588. self.assertNotIn("-AssumeManualSramProgrammed $true", script)
  589. for marker in [
  590. "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix",
  591. "debug115",
  592. "swapped",
  593. "-ManualSramAttestation",
  594. "$att.status",
  595. "blocked_edit_required",
  596. "collect-com8-host-com7-debug.ps1",
  597. r"-Bitstream .\bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit",
  598. "SET PTC 00",
  599. "SET FAN 00",
  600. "SET FAN 05",
  601. "SET FAN 06",
  602. "pip install",
  603. "pyserial",
  604. ]:
  605. self.assertNotIn(marker.lower(), script.lower())
  606. def test_binary921_collector_selftest_and_static_safety_contract(self) -> None:
  607. script = ROOT / "tools" / "remote" / "collect_j6_binary921.py"
  608. self.assertTrue(script.is_file())
  609. text = script.read_text(encoding="utf-8")
  610. for marker in [
  611. "binary921",
  612. "explicit COM ports only",
  613. "serial.Serial",
  614. "HostPort",
  615. "DebugPort",
  616. "build_host_command",
  617. "decode_stream",
  618. "startup-preflight.json",
  619. "host-command-transcript.json",
  620. "debug-binary921-frames.json",
  621. "binary921-evidence-manifest.json",
  622. "real_fan_ptc_hardware_status",
  623. "pc_replay_from_real_bmc_capture",
  624. "SET_PTC",
  625. "SET_FAN",
  626. "SET_PID_REQUESTED",
  627. "DISABLE",
  628. ]:
  629. self.assertIn(marker, text)
  630. for forbidden in [
  631. "PROGRAM_FLASH",
  632. "ERASE_FLASH",
  633. "PROGRAM_SPIBIN",
  634. "DIRECT_FLASH_WRITE",
  635. "GetPortNames",
  636. "Win32_SerialPort",
  637. "Set-ExecutionPolicy",
  638. "pip install",
  639. "driver install",
  640. "debug_serial.write",
  641. ]:
  642. self.assertNotIn(forbidden.lower(), text.lower())
  643. result = subprocess.run(
  644. [str(ROOT / ".codex" / "venv" / "Scripts" / "python.exe"), str(script), "--selftest"],
  645. cwd=ROOT,
  646. text=True,
  647. capture_output=True,
  648. check=False,
  649. )
  650. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  651. self.assertIn("selftest=pass", result.stdout)
  652. def test_binary921_collector_sets_dtr_rts_low_before_opening_pyserial(self) -> None:
  653. import sys
  654. import types
  655. from unittest import mock
  656. sys.path.insert(0, str(ROOT / "tools" / "remote"))
  657. import collect_j6_binary921
  658. calls: list[tuple[str, object]] = []
  659. class FakeSerial:
  660. def __init__(self, *args: object, **kwargs: object) -> None:
  661. calls.append(("init", {"args": args, "kwargs": kwargs}))
  662. if args or kwargs:
  663. raise AssertionError("Serial must be constructed closed before setting DTR/RTS")
  664. self.port = None
  665. self.baudrate = None
  666. self.bytesize = None
  667. self.parity = None
  668. self.stopbits = None
  669. self.timeout = None
  670. self.write_timeout = None
  671. self.rtscts = None
  672. self.dsrdtr = None
  673. self.dtr = None
  674. self.rts = None
  675. self.is_open = False
  676. def open(self) -> None:
  677. calls.append(
  678. (
  679. "open",
  680. {
  681. "port": self.port,
  682. "baudrate": self.baudrate,
  683. "dtr": self.dtr,
  684. "rts": self.rts,
  685. "rtscts": self.rtscts,
  686. "dsrdtr": self.dsrdtr,
  687. },
  688. )
  689. )
  690. self.is_open = True
  691. with mock.patch.dict(sys.modules, {"serial": types.SimpleNamespace(Serial=FakeSerial)}):
  692. endpoint = collect_j6_binary921._open_serial("COM7", 921600)
  693. self.assertIs(endpoint.is_open, True)
  694. self.assertEqual(
  695. calls,
  696. [
  697. ("init", {"args": (), "kwargs": {}}),
  698. (
  699. "open",
  700. {
  701. "port": "COM7",
  702. "baudrate": 921600,
  703. "dtr": False,
  704. "rts": False,
  705. "rtscts": False,
  706. "dsrdtr": False,
  707. },
  708. ),
  709. ],
  710. )
  711. def test_binary921_collector_supports_production_combined_uart_profile(self) -> None:
  712. import sys
  713. from unittest import mock
  714. sys.path.insert(0, str(ROOT / "tools"))
  715. sys.path.insert(0, str(ROOT / "tools" / "remote"))
  716. from binary921 import CommandId, FrameType, decode_frame, encode_frame, frame_to_dict, profile_id_for_name
  717. from collect_j6_binary921 import (
  718. COMMAND_SEQUENCE,
  719. build_manifest_from_frames,
  720. collect_live,
  721. is_combined_uart_profile,
  722. )
  723. profile = "production-two-uart-bmc-replay-binary921"
  724. profile_id = profile_id_for_name(profile)
  725. self.assertTrue(is_combined_uart_profile(profile))
  726. commands = [
  727. {
  728. "seq": index,
  729. "name": name,
  730. "command_id": int(command),
  731. "channel": channel,
  732. "percent": percent,
  733. }
  734. for index, (name, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1)
  735. ]
  736. combined_frames = [
  737. frame_to_dict(
  738. decode_frame(
  739. encode_frame(
  740. profile_id=profile_id,
  741. frame_type=FrameType.READY,
  742. seq=0,
  743. timestamp_tick=0,
  744. payload=bytes([profile_id, 0, 0, 0]),
  745. )
  746. )
  747. )
  748. ]
  749. for row in commands:
  750. combined_frames.append(
  751. frame_to_dict(
  752. decode_frame(
  753. encode_frame(
  754. profile_id=profile_id,
  755. frame_type=FrameType.HOST_ACK,
  756. seq=row["seq"],
  757. timestamp_tick=0,
  758. payload=bytes([1, row["command_id"], 0, 0, 0x34, 0x12]),
  759. )
  760. )
  761. )
  762. )
  763. combined_frames.extend(
  764. [
  765. frame_to_dict(
  766. decode_frame(
  767. encode_frame(
  768. profile_id=profile_id,
  769. frame_type=FrameType.BMC_PAYLOAD,
  770. seq=50,
  771. timestamp_tick=0,
  772. payload=bytes([48, 48, 0, 1, 0x1E, 0xFF, 0x08, 0x14]),
  773. )
  774. )
  775. ),
  776. frame_to_dict(
  777. decode_frame(
  778. encode_frame(
  779. profile_id=profile_id,
  780. frame_type=FrameType.SENSOR_CACHE,
  781. seq=51,
  782. timestamp_tick=0,
  783. payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
  784. )
  785. )
  786. ),
  787. frame_to_dict(
  788. decode_frame(
  789. encode_frame(
  790. profile_id=profile_id,
  791. frame_type=FrameType.MODULE_SNAPSHOT,
  792. seq=52,
  793. timestamp_tick=0,
  794. payload=bytes(
  795. [
  796. profile_id,
  797. 0,
  798. len(COMMAND_SEQUENCE),
  799. 0,
  800. 0x1E,
  801. 0xFF,
  802. 0x08,
  803. 0x14,
  804. CommandId.DISABLE,
  805. 0,
  806. 0,
  807. 0,
  808. 0,
  809. 1,
  810. 2,
  811. 22,
  812. 0,
  813. 0,
  814. 30,
  815. 30,
  816. 0,
  817. 0x0F,
  818. 0,
  819. 0,
  820. ]
  821. ),
  822. )
  823. )
  824. ),
  825. ]
  826. )
  827. manifest = build_manifest_from_frames(
  828. profile=profile,
  829. startup_ready=combined_frames[0],
  830. host_commands=commands,
  831. host_frames=combined_frames,
  832. debug_frames=combined_frames,
  833. debug_raw=b"same-com-raw",
  834. host_raw=b"same-com-raw",
  835. combined_raw=b"same-com-raw",
  836. bmc_replay={
  837. "status": "pass",
  838. "bmc_source": "pc_replay_from_real_bmc_capture",
  839. "byte_count": 48,
  840. "valid_count": 2,
  841. "missing_count": 22,
  842. "reply_sha256": "06c173f91f8b6b0e56f9c381b49d5b127d2dbf3a09402843838a0ff2b812f1af",
  843. },
  844. )
  845. self.assertEqual(manifest["status"], "pass")
  846. self.assertEqual(manifest["profile"], profile)
  847. self.assertEqual(manifest["transport"], "combined_host_debug_uart")
  848. self.assertEqual(manifest["combined_uart_baud"], 921600)
  849. self.assertEqual(manifest["host_ack_matched_count"], len(COMMAND_SEQUENCE))
  850. self.assertIn("combined-uart-binary921.raw", manifest["artifact_hashes"])
  851. self.assertEqual(manifest["module_snapshot_count"], 1)
  852. self.assertEqual(manifest["pwm_logic_evidence"]["status"], "pass")
  853. self.assertEqual(manifest["pid_evidence"]["status"], "pass")
  854. self.assertEqual(manifest["timeout_fallback_evidence"]["status"], "pass")
  855. class ShouldNotOpenSerial:
  856. def __call__(self, port: str, baud: int) -> object:
  857. raise AssertionError(f"unexpected open {port} {baud}")
  858. with mock.patch("collect_j6_binary921._open_serial", ShouldNotOpenSerial()):
  859. with self.assertRaisesRegex(ValueError, "CombinedPort must be an explicit COM"):
  860. collect_live(
  861. type(
  862. "Args",
  863. (),
  864. {
  865. "profile": profile,
  866. "transport": "combined-single-com",
  867. "combined_port": "AUTO",
  868. "host_port": "",
  869. "debug_port": "",
  870. "output_dir": "unused",
  871. "duration_sec": 0,
  872. "ready_timeout_sec": 0,
  873. "ack_window_sec": 0,
  874. "bitstream": "",
  875. "td_receipt": "",
  876. "bmc_replay_receipt": "",
  877. },
  878. )()
  879. )
  880. def test_binary921_production_manifest_blocks_without_timeout_snapshot(self) -> None:
  881. import sys
  882. sys.path.insert(0, str(ROOT / "tools"))
  883. sys.path.insert(0, str(ROOT / "tools" / "remote"))
  884. from binary921 import CommandId, FrameType, decode_frame, encode_frame, frame_to_dict, profile_id_for_name
  885. from collect_j6_binary921 import COMMAND_SEQUENCE, build_manifest_from_frames
  886. profile = "production-two-uart-bmc-replay-binary921"
  887. profile_id = profile_id_for_name(profile)
  888. commands = [
  889. {
  890. "seq": index,
  891. "name": name,
  892. "command_id": int(command),
  893. "channel": channel,
  894. "percent": percent,
  895. }
  896. for index, (name, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1)
  897. ]
  898. frames = [
  899. frame_to_dict(
  900. decode_frame(
  901. encode_frame(
  902. profile_id=profile_id,
  903. frame_type=FrameType.READY,
  904. seq=0,
  905. timestamp_tick=0,
  906. payload=bytes([profile_id, 0, 0, 0]),
  907. )
  908. )
  909. )
  910. ]
  911. for row in commands:
  912. frames.append(
  913. frame_to_dict(
  914. decode_frame(
  915. encode_frame(
  916. profile_id=profile_id,
  917. frame_type=FrameType.HOST_ACK,
  918. seq=row["seq"],
  919. timestamp_tick=0,
  920. payload=bytes([1, row["command_id"], 0, 0, 0x34, 0x12]),
  921. )
  922. )
  923. )
  924. )
  925. frames.append(
  926. frame_to_dict(
  927. decode_frame(
  928. encode_frame(
  929. profile_id=profile_id,
  930. frame_type=FrameType.BMC_PAYLOAD,
  931. seq=50,
  932. timestamp_tick=0,
  933. payload=bytes([48, 48, 0, 1, 0x1E, 0xFF, 0x08, 0x14]),
  934. )
  935. )
  936. )
  937. )
  938. frames.append(
  939. frame_to_dict(
  940. decode_frame(
  941. encode_frame(
  942. profile_id=profile_id,
  943. frame_type=FrameType.SENSOR_CACHE,
  944. seq=51,
  945. timestamp_tick=0,
  946. payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
  947. )
  948. )
  949. )
  950. )
  951. manifest = build_manifest_from_frames(
  952. profile=profile,
  953. startup_ready=frames[0],
  954. host_commands=commands,
  955. host_frames=frames,
  956. debug_frames=frames,
  957. debug_raw=b"raw",
  958. host_raw=b"raw",
  959. combined_raw=b"raw",
  960. bmc_replay={
  961. "status": "pass",
  962. "source": "real_bmc_capture",
  963. "bmc_source": "pc_replay_from_real_bmc_capture",
  964. "byte_count": 48,
  965. "valid_count": 2,
  966. "missing_count": 22,
  967. "reply_sha256": "06c173f91f8b6b0e56f9c381b49d5b127d2dbf3a09402843838a0ff2b812f1af",
  968. "capture_text_sha256": "1" * 64,
  969. },
  970. )
  971. self.assertNotEqual(manifest["status"], "pass")
  972. self.assertIn("missing_module_snapshot", manifest["blockers"])
  973. self.assertIn("timeout_fallback_evidence_incomplete", manifest["blockers"])
  974. def test_binary921_collector_requires_exact_ack_and_bmc_payload_for_pass(self) -> None:
  975. import sys
  976. sys.path.insert(0, str(ROOT / "tools"))
  977. sys.path.insert(0, str(ROOT / "tools" / "remote"))
  978. from binary921 import CommandId, FrameType, decode_frame, encode_frame, frame_to_dict
  979. from collect_j6_binary921 import COMMAND_SEQUENCE, build_manifest_from_frames
  980. commands = [
  981. {
  982. "seq": index,
  983. "name": name,
  984. "command_id": int(command),
  985. "channel": channel,
  986. "percent": percent,
  987. }
  988. for index, (name, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1)
  989. ]
  990. wrong_acks = [
  991. frame_to_dict(
  992. decode_frame(
  993. encode_frame(
  994. profile_id=1,
  995. frame_type=FrameType.HOST_ACK,
  996. seq=index + 1,
  997. timestamp_tick=0,
  998. payload=bytes([1, int(CommandId.GET_STATUS), 0, 0, 0, 0]),
  999. )
  1000. )
  1001. )
  1002. for index in range(1, 13)
  1003. ]
  1004. ready = frame_to_dict(
  1005. decode_frame(
  1006. encode_frame(profile_id=1, frame_type=FrameType.READY, seq=1, timestamp_tick=0, payload=b"\x01\x00\x00\x00")
  1007. )
  1008. )
  1009. manifest = build_manifest_from_frames(
  1010. profile="debug-photo-bmc-replay-binary921",
  1011. startup_ready=ready,
  1012. host_commands=commands,
  1013. host_frames=wrong_acks,
  1014. debug_frames=[ready],
  1015. debug_raw=b"",
  1016. host_raw=b"",
  1017. )
  1018. self.assertEqual(manifest["status"], "blocked_host_ack")
  1019. self.assertEqual(manifest["host_ack_count"], 12)
  1020. self.assertEqual(manifest["host_ack_matched_count"], 0)
  1021. self.assertIn("missing_bmc_payload", manifest["blockers"])
  1022. def test_binary921_collector_writes_blocked_manifest_when_ready_is_missing(self) -> None:
  1023. import sys
  1024. sys.path.insert(0, str(ROOT / "tools" / "remote"))
  1025. from collect_j6_binary921 import write_blocked_manifest
  1026. with tempfile.TemporaryDirectory() as tmp:
  1027. manifest = write_blocked_manifest(
  1028. Path(tmp),
  1029. profile="debug-photo-bmc-replay-binary921",
  1030. status="blocked_waiting_for_binary921_ready",
  1031. startup_raw=b"old-noise",
  1032. startup_frames=[],
  1033. error="timeout",
  1034. )
  1035. manifest_path = Path(tmp) / "binary921-evidence-manifest.json"
  1036. self.assertTrue(manifest_path.is_file())
  1037. self.assertEqual(manifest["status"], "blocked_waiting_for_binary921_ready")
  1038. self.assertEqual(manifest["host_command_count"], 0)
  1039. self.assertEqual(manifest["startup_pre_sram_noise_sha256"], "2720ea258623d86efdb0d4c7767f6806839c402b231d2dacde75d9d2256a0d45")
  1040. def test_binary921_package_script_creates_debug_and_formal_packages(self) -> None:
  1041. powershell = shutil.which("powershell")
  1042. if powershell is None:
  1043. self.skipTest("PowerShell is not available")
  1044. script = ROOT / "tools" / "package_j6_binary921.ps1"
  1045. self.assertTrue(script.is_file())
  1046. static_text = script.read_text(encoding="utf-8")
  1047. for marker in [
  1048. "debug-photo-bmc-replay-binary921",
  1049. "formal-uart1-bmc-replay-binary921",
  1050. "collect_j6_binary921.py",
  1051. "binary921.py",
  1052. "bmc_replay_uart.py",
  1053. "j6bin.bit",
  1054. "collect-binary921.ps1",
  1055. "START-HERE.zh-CN.md",
  1056. "sha256-inventory.json",
  1057. "binary921-evidence-manifest.json",
  1058. "pc_replay_from_real_bmc_capture",
  1059. "PYTHONDONTWRITEBYTECODE",
  1060. "Remove-PythonCache",
  1061. "__pycache__",
  1062. ]:
  1063. self.assertIn(marker, static_text)
  1064. self.assertNotIn("Set-ExecutionPolicy", static_text)
  1065. self.assertNotIn("pip install", static_text.lower())
  1066. self.assertNotIn("PROGRAM_FLASH", static_text)
  1067. with tempfile.TemporaryDirectory() as tmp:
  1068. bitstream = Path(tmp) / "fake-binary921.bit"
  1069. td_receipt = Path(tmp) / "td-binary921.json"
  1070. bitstream.write_bytes(b"fake-binary921-sram-bitstream")
  1071. td_receipt.write_text(json.dumps({"schema": "td-build-receipt-v1", "status": "pass"}), encoding="utf-8")
  1072. for profile, package_name, expected_debug_rx, expected_debug_tx in [
  1073. ("debug-photo-bmc-replay-binary921", "j6bin-debug-test", "P10", "R10"),
  1074. ("formal-uart1-bmc-replay-binary921", "j6bin-formal-test", "M14", "M15"),
  1075. ]:
  1076. with self.subTest(profile=profile):
  1077. result = subprocess.run(
  1078. [
  1079. powershell,
  1080. "-NoProfile",
  1081. "-ExecutionPolicy",
  1082. "Bypass",
  1083. "-File",
  1084. str(script),
  1085. "-OutputDir",
  1086. tmp,
  1087. "-PackageName",
  1088. package_name,
  1089. "-Profile",
  1090. profile,
  1091. "-Bitstream",
  1092. str(bitstream),
  1093. "-TdReceipt",
  1094. str(td_receipt),
  1095. ],
  1096. cwd=ROOT,
  1097. text=True,
  1098. capture_output=True,
  1099. check=False,
  1100. )
  1101. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  1102. stage = Path(tmp) / package_name
  1103. self.assertTrue((stage / "j6bin.bit").is_file())
  1104. self.assertTrue((stage / "td.json").is_file())
  1105. self.assertTrue((stage / "collect-binary921.ps1").is_file())
  1106. self.assertTrue((stage / "tools" / "collect_j6_binary921.py").is_file())
  1107. self.assertTrue((stage / "tools" / "binary921.py").is_file())
  1108. self.assertTrue((stage / "tools" / "bmc_replay_uart.py").is_file())
  1109. self.assertTrue((stage / "START-HERE.zh-CN.md").is_file())
  1110. self.assertTrue((stage / "sha256-inventory.json").is_file())
  1111. self.assertTrue((Path(tmp) / f"{package_name}.zip").is_file())
  1112. self.assertTrue((Path(tmp) / f"{package_name}.zip.sha256.txt").is_file())
  1113. self.assertEqual((stage / "j6bin.bit").read_bytes(), bitstream.read_bytes())
  1114. start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig")
  1115. self.assertIn("collector first, then PROGRAM_SRAM", start_here)
  1116. self.assertIn("JTAG speed 200k", start_here)
  1117. self.assertIn("board power", start_here)
  1118. self.assertIn(".\\j6bin.bit", start_here)
  1119. self.assertIn("-File .\\collect-binary921.ps1", start_here)
  1120. self.assertIn("-BmcReplayReceipt .\\bmc-replay-session.json", start_here)
  1121. self.assertIn(profile, start_here)
  1122. self.assertIn("binary921", start_here)
  1123. self.assertIn("COM8", start_here)
  1124. self.assertIn("COM7", start_here)
  1125. self.assertIn("COM9", start_here)
  1126. self.assertNotIn("Set-ExecutionPolicy", start_here)
  1127. self.assertNotIn("pip install", start_here.lower())
  1128. manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig"))
  1129. expected_status = (
  1130. "pass"
  1131. if profile == "debug-photo-bmc-replay-binary921"
  1132. else "blocked_waiting_for_uart1_uart2_access"
  1133. )
  1134. self.assertEqual(manifest["status"], expected_status)
  1135. self.assertEqual(manifest["protocol"], "binary921")
  1136. self.assertEqual(manifest["pin_profile"], profile)
  1137. self.assertEqual(manifest["jtag_programming"]["jtag_speed_hz"], 200000)
  1138. self.assertEqual(manifest["jtag_programming"]["board_power_present_before_program"], True)
  1139. self.assertEqual(manifest["jtag_programming"]["program_mode"], "PROGRAM_SRAM")
  1140. self.assertEqual(manifest["bitstream"]["path"], "j6bin.bit")
  1141. self.assertEqual(manifest["bmc_source"], "pc_replay_from_real_bmc_capture")
  1142. self.assertEqual(manifest["collector"]["bmc_replay_receipt"], "bmc-replay-session.json")
  1143. self.assertEqual(manifest["real_fan_ptc_hardware_status"], "not_run")
  1144. self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_rx"]["fpga_ball"], expected_debug_rx)
  1145. self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_tx"]["fpga_ball"], expected_debug_tx)
  1146. inv = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig"))
  1147. paths = {item["path"] for item in inv["inventory"]}
  1148. self.assertIn("j6bin.bit", paths)
  1149. self.assertIn("collect-binary921.ps1", paths)
  1150. self.assertIn("tools/collect_j6_binary921.py", paths)
  1151. self.assertIn("tools/binary921.py", paths)
  1152. self.assertIn("tools/bmc_replay_uart.py", paths)
  1153. self.assertNotIn("sha256-inventory.json", paths)
  1154. self.assertFalse(any(part == "__pycache__" for path in stage.rglob("*") for part in path.parts))
  1155. self.assertFalse(any(path.suffix in {".pyc", ".pyo"} for path in stage.rglob("*")))
  1156. def test_binary921_package_script_creates_production_two_uart_package(self) -> None:
  1157. powershell = shutil.which("powershell")
  1158. if powershell is None:
  1159. self.skipTest("PowerShell is not available")
  1160. script = ROOT / "tools" / "package_j6_binary921.ps1"
  1161. with tempfile.TemporaryDirectory() as tmp:
  1162. bitstream = Path(tmp) / "fake-production-binary921.bit"
  1163. td_receipt = Path(tmp) / "td-production-binary921.json"
  1164. payload_path = Path(tmp) / "historical-bmc-payload.json"
  1165. bitstream_bytes = b"fake-production-two-uart-sram-bitstream"
  1166. bitstream.write_bytes(bitstream_bytes)
  1167. bit_sha = hashlib.sha256(bitstream_bytes).hexdigest()
  1168. td_receipt.write_text(
  1169. json.dumps(
  1170. {
  1171. "schema": "td-build-receipt-v1",
  1172. "status": "pass",
  1173. "top": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921",
  1174. "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top",
  1175. "mode": "implementation",
  1176. "pin_profile": "production-two-uart-bmc-replay-binary921",
  1177. "timing_gate": {"status": "pass"},
  1178. "bitstream": {"sha256": bit_sha},
  1179. }
  1180. ),
  1181. encoding="utf-8",
  1182. )
  1183. historical_reply = (
  1184. "1e 4b ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff "
  1185. "20 19 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff\r\n"
  1186. )
  1187. payload_path.write_text(
  1188. json.dumps(
  1189. {
  1190. "schema": "j6-bmc-replay-payload-v1",
  1191. "status": "pass",
  1192. "source": "real_bmc_capture",
  1193. "bmc_source": "pc_replay_from_real_bmc_capture",
  1194. "live_bmc_link_status": "not_used",
  1195. "reply_text": historical_reply,
  1196. "reply_sha256": "06c173f91f8b6b0e56f9c381b49d5b127d2dbf3a09402843838a0ff2b812f1af",
  1197. "capture_text_sha256": "1" * 64,
  1198. "byte_count": 48,
  1199. "valid_count": 2,
  1200. "missing_count": 22,
  1201. }
  1202. ),
  1203. encoding="utf-8",
  1204. )
  1205. result = subprocess.run(
  1206. [
  1207. powershell,
  1208. "-NoProfile",
  1209. "-ExecutionPolicy",
  1210. "Bypass",
  1211. "-File",
  1212. str(script),
  1213. "-OutputDir",
  1214. tmp,
  1215. "-PackageName",
  1216. "j6prod-2uart-bmc-replay-test",
  1217. "-Profile",
  1218. "production-two-uart-bmc-replay-binary921",
  1219. "-Bitstream",
  1220. str(bitstream),
  1221. "-TdReceipt",
  1222. str(td_receipt),
  1223. "-BmcReplayPayload",
  1224. str(payload_path),
  1225. ],
  1226. cwd=ROOT,
  1227. text=True,
  1228. capture_output=True,
  1229. check=False,
  1230. )
  1231. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  1232. stage = Path(tmp) / "j6prod-2uart-bmc-replay-test"
  1233. self.assertTrue((stage / "j6bin.bit").is_file())
  1234. self.assertTrue((stage / "td.json").is_file())
  1235. self.assertTrue((stage / "bmc-replay-payload.json").is_file())
  1236. self.assertTrue((stage / "collect-binary921.ps1").is_file())
  1237. self.assertTrue((Path(tmp) / "j6prod-2uart-bmc-replay-test.zip").is_file())
  1238. start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig")
  1239. for marker in [
  1240. "production-two-uart-bmc-replay-binary921",
  1241. "J3",
  1242. "1=TCK",
  1243. "2=GND",
  1244. "3=TDO",
  1245. "4=VREF",
  1246. "5=TMS",
  1247. "9=TDI",
  1248. "10=GND",
  1249. "UART1",
  1250. "L10",
  1251. "M9",
  1252. "UART2",
  1253. "M10",
  1254. "N11",
  1255. "-CombinedPort",
  1256. "不要求重新上电",
  1257. "-Iterations 3",
  1258. "-TimeoutSeconds 600",
  1259. "921600",
  1260. "115200",
  1261. ".\\bmc-replay-payload.json",
  1262. ]:
  1263. self.assertIn(marker, start_here)
  1264. self.assertNotIn("-HostPort COM8 -DebugPort COM7", start_here)
  1265. self.assertNotIn("Set-ExecutionPolicy", start_here)
  1266. self.assertNotIn("pip install", start_here.lower())
  1267. manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig"))
  1268. self.assertEqual(manifest["status"], "pass")
  1269. self.assertEqual(manifest["pin_profile"], "production-two-uart-bmc-replay-binary921")
  1270. self.assertEqual(manifest["transport"], "combined_host_debug_uart")
  1271. self.assertEqual(manifest["combined_uart_baud"], 921600)
  1272. self.assertEqual(manifest["bmc_replay_uart_baud"], 115200)
  1273. self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "L10")
  1274. self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "M9")
  1275. self.assertEqual(manifest["pin_map"]["uart_assignments"]["combined_debug_host_uart_tx"]["fpga_ball"], "M10")
  1276. self.assertEqual(manifest["pin_map"]["uart_assignments"]["combined_debug_host_uart_rx"]["fpga_ball"], "N11")
  1277. self.assertEqual(manifest["bmc_replay_payload"]["reply_sha256"], "06c173f91f8b6b0e56f9c381b49d5b127d2dbf3a09402843838a0ff2b812f1af")
  1278. self.assertEqual(manifest["bitstream"]["sha256"], bit_sha)
  1279. self.assertFalse(manifest["jtag_programming"]["power_cycle_required"])
  1280. self.assertEqual(manifest["bmc_replay_payload"]["valid_count"], 2)
  1281. self.assertEqual(manifest["bmc_replay_payload"]["missing_count"], 22)
  1282. self.assertEqual(manifest["real_fan_ptc_hardware_status"], "not_run")
  1283. paths = {item["path"] for item in json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig"))["inventory"]}
  1284. self.assertIn("bmc-replay-payload.json", paths)
  1285. self.assertIn("collect-binary921.ps1", paths)
  1286. self.assertIn("tools/collect_j6_binary921.py", paths)
  1287. def test_binary921_production_package_rejects_unbound_td_receipt_and_payload_hash(self) -> None:
  1288. powershell = shutil.which("powershell")
  1289. if powershell is None:
  1290. self.skipTest("PowerShell is not available")
  1291. script = ROOT / "tools" / "package_j6_binary921.ps1"
  1292. with tempfile.TemporaryDirectory() as tmp:
  1293. bitstream = Path(tmp) / "fake-production-binary921.bit"
  1294. td_receipt = Path(tmp) / "td-production-binary921.json"
  1295. payload_path = Path(tmp) / "historical-bmc-payload.json"
  1296. bitstream.write_bytes(b"fake-production-two-uart-sram-bitstream")
  1297. td_receipt.write_text(json.dumps({"schema": "td-build-receipt-v1", "status": "pass"}), encoding="utf-8")
  1298. payload_path.write_text(
  1299. json.dumps(
  1300. {
  1301. "schema": "j6-bmc-replay-payload-v1",
  1302. "status": "pass",
  1303. "source": "real_bmc_capture",
  1304. "bmc_source": "pc_replay_from_real_bmc_capture",
  1305. "reply_text": "1e 4b\r\n",
  1306. "reply_sha256": "0" * 64,
  1307. "capture_text_sha256": "1" * 64,
  1308. "byte_count": 48,
  1309. "valid_count": 2,
  1310. "missing_count": 22,
  1311. }
  1312. ),
  1313. encoding="utf-8",
  1314. )
  1315. result = subprocess.run(
  1316. [
  1317. powershell,
  1318. "-NoProfile",
  1319. "-ExecutionPolicy",
  1320. "Bypass",
  1321. "-File",
  1322. str(script),
  1323. "-OutputDir",
  1324. tmp,
  1325. "-PackageName",
  1326. "j6prod-2uart-bmc-replay-test",
  1327. "-Profile",
  1328. "production-two-uart-bmc-replay-binary921",
  1329. "-Bitstream",
  1330. str(bitstream),
  1331. "-TdReceipt",
  1332. str(td_receipt),
  1333. "-BmcReplayPayload",
  1334. str(payload_path),
  1335. ],
  1336. cwd=ROOT,
  1337. text=True,
  1338. capture_output=True,
  1339. check=False,
  1340. )
  1341. self.assertNotEqual(result.returncode, 0)
  1342. self.assertIn("TD receipt", result.stderr + result.stdout)
  1343. def test_j6_host_sensor_real_fan_ptc_package_output_contains_bmc_replay_profile_artifacts(self) -> None:
  1344. powershell = shutil.which("powershell")
  1345. if powershell is None:
  1346. self.skipTest("PowerShell is not available")
  1347. with tempfile.TemporaryDirectory() as tmp:
  1348. bitstream = Path(tmp) / "fake.bit"
  1349. td_receipt = Path(tmp) / "td-receipt.json"
  1350. bitstream.write_bytes(b"fake-sram-bitstream")
  1351. td_receipt.write_text(
  1352. json.dumps(
  1353. {
  1354. "schema": "td-build-receipt-v1",
  1355. "status": "pass",
  1356. "programming_mode": "SRAM-only",
  1357. "bitstream": {"sha256": "0" * 64},
  1358. }
  1359. ),
  1360. encoding="utf-8",
  1361. )
  1362. for profile, package_name, expected in [
  1363. (
  1364. "debug-photo-uart-bmc-replay",
  1365. "j6-bmc-replay-debug-test",
  1366. {
  1367. "host_ports": "-HostPort COM8 -DebugPort COM7 -BmcReplayPort COM9",
  1368. "bmc_tx": "T4",
  1369. "bmc_rx": "R5",
  1370. "hardware_access_status": "photo_visible_header",
  1371. "ptc_note": "PTC03/PTC04/PTC17/PTC18/PTC21/PTC22",
  1372. },
  1373. ),
  1374. (
  1375. "formal-uart1-bmc-replay",
  1376. "j6-bmc-replay-formal-test",
  1377. {
  1378. "host_ports": "-HostPort COM8 -DebugPort COM7 -BmcReplayPort COM9",
  1379. "bmc_tx": "L10",
  1380. "bmc_rx": "M9",
  1381. "hardware_access_status": "blocked_waiting_for_uart1_uart2_access",
  1382. "ptc_note": "HEAT/PTC/FAN",
  1383. },
  1384. ),
  1385. ]:
  1386. with self.subTest(profile=profile):
  1387. result = subprocess.run(
  1388. [
  1389. powershell,
  1390. "-NoProfile",
  1391. "-ExecutionPolicy",
  1392. "Bypass",
  1393. "-File",
  1394. str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"),
  1395. "-OutputDir",
  1396. tmp,
  1397. "-PackageName",
  1398. package_name,
  1399. "-Profile",
  1400. profile,
  1401. "-Bitstream",
  1402. str(bitstream),
  1403. "-TdReceipt",
  1404. str(td_receipt),
  1405. ],
  1406. cwd=ROOT,
  1407. capture_output=True,
  1408. check=False,
  1409. )
  1410. output = (result.stderr or b"").decode("utf-8", errors="replace") + (
  1411. result.stdout or b""
  1412. ).decode("utf-8", errors="replace")
  1413. self.assertEqual(result.returncode, 0, output)
  1414. stage = Path(tmp) / package_name
  1415. short_bit = stage / "j6tmp.bit"
  1416. short_collect = stage / "collect.ps1"
  1417. short_td = stage / "td.json"
  1418. self.assertTrue((stage / "START-HERE.zh-CN.md").is_file())
  1419. self.assertTrue(short_bit.is_file())
  1420. self.assertTrue(short_collect.is_file())
  1421. self.assertTrue(short_td.is_file())
  1422. self.assertTrue((stage / "collector" / "collect-j6-host-sensor-real-fan-ptc.ps1").is_file())
  1423. self.assertTrue((stage / "bmc-replay" / "bmc_replay_uart.py").is_file())
  1424. self.assertTrue((stage / "capture-bmc.ps1").is_file())
  1425. self.assertTrue((stage / "replay-bmc.ps1").is_file())
  1426. self.assertTrue((stage / "bmc-replay-payload.example.json").is_file())
  1427. self.assertTrue((stage / "commands" / "collect-template.ps1").is_file())
  1428. self.assertTrue((stage / "bitstreams" / bitstream.name).is_file())
  1429. self.assertTrue((stage / "td-receipts" / td_receipt.name).is_file())
  1430. self.assertEqual(short_bit.read_bytes(), bitstream.read_bytes())
  1431. self.assertEqual(json.loads(short_td.read_text(encoding="utf-8-sig"))["status"], "pass")
  1432. self.assertLess(len(str(short_bit)), 100)
  1433. self.assertTrue((stage / "config" / "pin_inventory.fcb_fpga_mcu0611.json").is_file())
  1434. self.assertTrue((stage / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").is_file())
  1435. self.assertFalse((stage / "blocked").exists())
  1436. self.assertTrue((Path(tmp) / f"{package_name}.zip").is_file())
  1437. self.assertTrue((Path(tmp) / f"{package_name}.zip.sha256.txt").is_file())
  1438. start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig")
  1439. self.assertIn("PROGRAM_SRAM", start_here)
  1440. self.assertIn("先准备并启动 BMC replay", start_here)
  1441. self.assertIn("再启动 collector", start_here)
  1442. self.assertIn("collector first, then PROGRAM_SRAM", start_here)
  1443. self.assertIn(f"-Profile {profile}", start_here)
  1444. self.assertIn(expected["host_ports"], start_here)
  1445. self.assertIn("pc_replay_from_real_bmc_capture", start_here)
  1446. self.assertIn("collector_protocol_profile=temp-uart-ptc-remap", start_here)
  1447. self.assertIn("JTAG speed 200k", start_here)
  1448. self.assertIn("board power", start_here)
  1449. self.assertIn(expected["bmc_tx"], start_here)
  1450. self.assertIn(expected["bmc_rx"], start_here)
  1451. self.assertIn("capture-bmc.ps1", start_here)
  1452. self.assertIn("replay-bmc.ps1", start_here)
  1453. self.assertLess(start_here.index("replay-bmc.ps1"), start_here.index("collect.ps1"))
  1454. self.assertLess(start_here.index("collect.ps1"), start_here.index("PROGRAM_SRAM"))
  1455. self.assertIn("bmc-replay-payload.example.json", start_here)
  1456. self.assertIn("Python", start_here)
  1457. self.assertIn("does not install Python/pip/driver", start_here)
  1458. self.assertIn(expected["ptc_note"], start_here)
  1459. if profile == "formal-uart1-bmc-replay":
  1460. self.assertNotIn("PTC03/PTC04/PTC17/PTC18/PTC21/PTC22 使用临时", start_here)
  1461. self.assertIn(".\\j6tmp.bit", start_here)
  1462. self.assertIn(".\\td.json", start_here)
  1463. self.assertIn("-File .\\collect.ps1", start_here)
  1464. self.assertIn("Cannot open file", start_here)
  1465. self.assertIn("bitstreams", start_here)
  1466. self.assertNotIn(f".\\bitstreams\\{bitstream.name}", start_here)
  1467. self.assertNotIn(f".\\td-receipts\\{td_receipt.name}", start_here)
  1468. self.assertIn("powershell.exe -NoProfile -ExecutionPolicy Bypass -File", start_here)
  1469. self.assertIn("-HostPort COM8 -DebugPort COM7", start_here)
  1470. self.assertIn("tail drain", start_here)
  1471. self.assertIn("[中文 runbook](docs/j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md)", start_here)
  1472. self.assertIn("[collector 脚本](collector/collect-j6-host-sensor-real-fan-ptc.ps1)", start_here)
  1473. self.assertIn("[SHA256 inventory](sha256-inventory.json)", start_here)
  1474. self.assertNotIn("Set-ExecutionPolicy", start_here)
  1475. self.assertNotIn("-AssumeManualSramProgrammed", start_here)
  1476. self.assertNotIn("先手动刷 SRAM", start_here)
  1477. self.assertNotIn("刷完 SRAM 后采集", start_here)
  1478. collect_template = (stage / "commands" / "collect-template.ps1").read_text(
  1479. encoding="utf-8-sig"
  1480. )
  1481. self.assertNotIn("Set-ExecutionPolicy", collect_template)
  1482. self.assertNotIn("-AssumeManualSramProgrammed", collect_template)
  1483. self.assertIn("-NoProfile", collect_template)
  1484. self.assertIn("-ExecutionPolicy Bypass", collect_template)
  1485. self.assertIn("-File .\\collect.ps1", collect_template)
  1486. shortcut = short_collect.read_text(encoding="utf-8-sig")
  1487. self.assertIn("$PSHOME", shortcut)
  1488. self.assertIn("$PSScriptRoot", shortcut)
  1489. self.assertIn('"-File"', shortcut)
  1490. self.assertIn('Join-Path $packageRoot "collector\\collect-j6-host-sensor-real-fan-ptc.ps1"', shortcut)
  1491. self.assertIn('[string]$Bitstream = ".\\j6tmp.bit"', shortcut)
  1492. self.assertIn('[string]$TdReceipt = ".\\td.json"', shortcut)
  1493. self.assertIn('"-Bitstream"', shortcut)
  1494. self.assertIn('"-TdReceipt"', shortcut)
  1495. self.assertIn("[switch]$SelfTest", shortcut)
  1496. self.assertNotIn("Set-ExecutionPolicy", shortcut)
  1497. self.assertNotIn("-AssumeManualSramProgrammed", shortcut)
  1498. self.assertNotIn("blocked_pin_conflict_with_locked_debug_uart", start_here)
  1499. manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig"))
  1500. self.assertEqual(manifest["status"], "pass")
  1501. self.assertEqual(manifest["pin_profile"], profile)
  1502. self.assertIn("j6-bmc-replay", manifest["package_name"])
  1503. self.assertEqual(manifest["collector"]["user_profile_argument"], profile)
  1504. self.assertEqual(manifest["collector"]["collector_protocol_profile"], "temp-uart-ptc-remap")
  1505. self.assertEqual(manifest["collector"]["ready_profile_string"], "temp-uart-ptc-remap")
  1506. self.assertEqual(manifest["bmc_source"], "pc_replay_from_real_bmc_capture")
  1507. self.assertEqual(manifest["live_bmc_link_status"], "not_used")
  1508. self.assertIn("Python", manifest["remote_dependencies"])
  1509. self.assertIn("no pip setup", manifest["remote_dependencies"])
  1510. self.assertIn("no driver", manifest["remote_dependencies"])
  1511. self.assertEqual(manifest["pin_map"]["hardware_access_status"], expected["hardware_access_status"])
  1512. self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], expected["bmc_tx"])
  1513. self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], expected["bmc_rx"])
  1514. self.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM")
  1515. self.assertEqual(manifest["jtag_programming"]["jtag_speed_hz"], 200000)
  1516. self.assertEqual(manifest["jtag_programming"]["board_power_present_before_program"], True)
  1517. self.assertEqual(manifest["jtag_programming"]["program_mode"], "PROGRAM_SRAM")
  1518. self.assertEqual(manifest["bitstream"]["path"], "j6tmp.bit")
  1519. self.assertEqual(manifest["td_receipt"]["path"], "td.json")
  1520. self.assertEqual(manifest["short_path_aliases"]["bitstream"]["source"], f"bitstreams/{bitstream.name}")
  1521. self.assertEqual(manifest["short_path_aliases"]["td_receipt"]["source"], f"td-receipts/{td_receipt.name}")
  1522. self.assertIn("host_control_commands", manifest)
  1523. self.assertIn("pin_map", manifest)
  1524. self.assertIn("bmc_replay", manifest)
  1525. self.assertIn("tail_drain", manifest)
  1526. self.assertNotIn("pin_conflicts", manifest)
  1527. inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig"))
  1528. self.assertEqual(inventory["self_hash_policy"], "excluded_self_referential_file")
  1529. inventory_paths = {item["path"] for item in inventory["inventory"]}
  1530. self.assertIn("manifest.json", inventory_paths)
  1531. self.assertIn("START-HERE.zh-CN.md", inventory_paths)
  1532. self.assertIn("j6tmp.bit", inventory_paths)
  1533. self.assertIn("collect.ps1", inventory_paths)
  1534. self.assertIn("td.json", inventory_paths)
  1535. self.assertIn("collector/collect-j6-host-sensor-real-fan-ptc.ps1", inventory_paths)
  1536. self.assertIn("bmc-replay/bmc_replay_uart.py", inventory_paths)
  1537. self.assertIn("capture-bmc.ps1", inventory_paths)
  1538. self.assertIn("replay-bmc.ps1", inventory_paths)
  1539. self.assertIn("bmc-replay-payload.example.json", inventory_paths)
  1540. self.assertIn("commands/collect-template.ps1", inventory_paths)
  1541. self.assertNotIn("sha256-inventory.json", inventory_paths)
  1542. def test_j6_host_sensor_real_fan_ptc_package_script_creates_formal_blocked_package_without_bitstream(self) -> None:
  1543. powershell = shutil.which("powershell")
  1544. if powershell is None:
  1545. self.skipTest("PowerShell is not available")
  1546. with tempfile.TemporaryDirectory() as tmp:
  1547. td_receipt = Path(tmp) / "td-formal-fail.json"
  1548. td_receipt.write_text(
  1549. json.dumps(
  1550. {
  1551. "schema": "td-build-receipt-v1",
  1552. "status": "fail",
  1553. "top": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921",
  1554. "pin_profile": "formal-uart1-bmc-replay",
  1555. "phy": {"log_has_error": True},
  1556. "bitstream": None,
  1557. }
  1558. ),
  1559. encoding="utf-8",
  1560. )
  1561. result = subprocess.run(
  1562. [
  1563. powershell,
  1564. "-NoProfile",
  1565. "-ExecutionPolicy",
  1566. "Bypass",
  1567. "-File",
  1568. str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"),
  1569. "-OutputDir",
  1570. tmp,
  1571. "-PackageName",
  1572. "j6-bmc-replay-formal-blocked-test",
  1573. "-Profile",
  1574. "formal-uart1-bmc-replay",
  1575. "-TdReceipt",
  1576. str(td_receipt),
  1577. "-FormalBlocked",
  1578. ],
  1579. cwd=ROOT,
  1580. capture_output=True,
  1581. check=False,
  1582. )
  1583. output = (result.stderr or b"").decode("utf-8", errors="replace") + (
  1584. result.stdout or b""
  1585. ).decode("utf-8", errors="replace")
  1586. self.assertEqual(result.returncode, 0, output)
  1587. stage = Path(tmp) / "j6-bmc-replay-formal-blocked-test"
  1588. self.assertTrue(stage.is_dir())
  1589. self.assertFalse((stage / "j6tmp.bit").exists())
  1590. self.assertFalse((stage / "collect.ps1").exists())
  1591. self.assertTrue((stage / "FORMAL-BLOCKED.zh-CN.md").is_file())
  1592. self.assertTrue((stage / "START-HERE.zh-CN.md").is_file())
  1593. self.assertTrue((stage / "td.json").is_file())
  1594. self.assertTrue((Path(tmp) / "j6-bmc-replay-formal-blocked-test.zip").is_file())
  1595. start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig")
  1596. self.assertIn("blocked_td_mslice_over_limit", start_here)
  1597. self.assertIn("1137", start_here)
  1598. self.assertIn("1131", start_here)
  1599. self.assertIn("1120", start_here)
  1600. self.assertIn("不能刷机", start_here)
  1601. self.assertNotIn("PROGRAM_SRAM", start_here)
  1602. self.assertNotIn("j6tmp.bit", start_here)
  1603. manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig"))
  1604. self.assertEqual(manifest["status"], "blocked_td_mslice_over_limit")
  1605. self.assertEqual(manifest["pin_profile"], "formal-uart1-bmc-replay")
  1606. self.assertEqual(manifest["bitstream"], None)
  1607. self.assertEqual(manifest["real_fan_ptc_hardware_status"], "not_run")
  1608. self.assertEqual(manifest["bmc_source"], "pc_replay_from_real_bmc_capture")
  1609. self.assertEqual(manifest["blocked_reason"]["latest_attempt_mslices"], 1137)
  1610. self.assertEqual(manifest["blocked_reason"]["best_observed_mslices"], 1131)
  1611. self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "N14")
  1612. self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P15")
  1613. inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig"))
  1614. inventory_paths = {item["path"] for item in inventory["inventory"]}
  1615. self.assertIn("FORMAL-BLOCKED.zh-CN.md", inventory_paths)
  1616. self.assertIn("td.json", inventory_paths)
  1617. self.assertNotIn("j6tmp.bit", inventory_paths)
  1618. def test_j6_host_sensor_real_fan_ptc_runbook_is_chinese_copy_paste_ready_with_english_paths(self) -> None:
  1619. runbook = (ROOT / "docs" / "j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md").read_text(
  1620. encoding="utf-8"
  1621. )
  1622. for marker in [
  1623. "J6 Host Sensor Real FAN/PTC Debug921",
  1624. "START-HERE.zh-CN.md",
  1625. "temp-uart-ptc-remap",
  1626. "PROGRAM_SRAM",
  1627. "JTAG speed 200k",
  1628. "board_power_present_before_program",
  1629. "collector first, then PROGRAM_SRAM",
  1630. "COM8",
  1631. "COM7",
  1632. "PTC03",
  1633. "PTC04",
  1634. "PTC17",
  1635. "PTC18",
  1636. "PTC21",
  1637. "PTC22",
  1638. "SET PTC 01 10",
  1639. "SET PTC 24 20",
  1640. "SET FAN 01 40",
  1641. "SET FAN 04 30",
  1642. "SET PID ENABLE",
  1643. "GET SENSOR",
  1644. "SET PID DISABLE",
  1645. "DISABLE",
  1646. "PTCCH",
  1647. "FANCH",
  1648. "1-based",
  1649. "SENS",
  1650. "DIMM",
  1651. "J6TEMP",
  1652. "J6RAW",
  1653. "host-port-escaped.txt",
  1654. "debug-uart-escaped.txt",
  1655. "host-sensor-report.json",
  1656. "bmc-raw-replay.bin",
  1657. "不安装驱动",
  1658. "不枚举未知 COM",
  1659. "不写 DebugPort",
  1660. "blocked_pin_conflict_with_locked_debug_uart",
  1661. ]:
  1662. self.assertIn(marker, runbook)
  1663. for forbidden in [
  1664. "debug115",
  1665. "Manual SRAM attestation status must be pass",
  1666. "blocked_edit_required",
  1667. "当前不要刷机",
  1668. "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force",
  1669. "先手动刷 SRAM",
  1670. "确认 SRAM 下载完成后",
  1671. r".\commands\collect-com8-host-com7-debug.ps1",
  1672. r"bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit",
  1673. "collector/collect-j6-host-sensor-real-fan-ptc.ps1",
  1674. "SET PTC 00",
  1675. "SET FAN 00",
  1676. "SET FAN 05",
  1677. "SET FAN 06",
  1678. r".\collector\采集",
  1679. ]:
  1680. self.assertNotIn(forbidden, runbook)
  1681. def test_j6_host_sensor_real_fan_ptc_schema_requires_sensor_pwm_pid_pinmap_and_debug_artifacts(self) -> None:
  1682. schema = json.loads(
  1683. (ROOT / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").read_text(
  1684. encoding="utf-8"
  1685. )
  1686. )
  1687. layers = schema["properties"]["layers"]["properties"]
  1688. self.assertEqual(schema["properties"]["diagnostic_scope"], {"const": "host_sensor_real_fan_ptc_debug921"})
  1689. programming_props = schema["properties"]["programming"]["properties"]
  1690. self.assertEqual(programming_props["jtag_speed_hz"], {"const": 200000})
  1691. self.assertEqual(programming_props["board_power_present_before_program"], {"const": True})
  1692. manual_props = layers["manual_sram_programming"]["properties"]
  1693. self.assertEqual(manual_props["jtag_speed_hz"], {"const": 200000})
  1694. self.assertEqual(manual_props["board_power_present_before_program"], {"const": True})
  1695. for layer in [
  1696. "host_command_sequence",
  1697. "host_control_transcript",
  1698. "host_sensor_reports",
  1699. "debug_frame_capture",
  1700. "bmc_raw_sampling",
  1701. "pid_boundary",
  1702. "timeout_evidence",
  1703. "pin_map",
  1704. "real_fan_ptc_hardware_status",
  1705. "artifact_hashes",
  1706. ]:
  1707. self.assertIn(layer, layers)
  1708. commands = layers["host_command_sequence"]["properties"]["commands"]["prefixItems"]
  1709. self.assertEqual(commands[0], {"const": "SET PTC 01 10"})
  1710. self.assertEqual(commands[1], {"const": "SET PTC 24 20"})
  1711. self.assertEqual(commands[2], {"const": "SET FAN 01 40"})
  1712. self.assertEqual(commands[3], {"const": "SET FAN 04 30"})
  1713. self.assertIn("host_sensor_report", layers["host_sensor_reports"]["required"])
  1714. self.assertIn("debug_frame_stream", layers["debug_frame_capture"]["required"])
  1715. self.assertIn("raw_replay", layers["debug_frame_capture"]["required"])
  1716. self.assertEqual(layers["pin_map"]["properties"]["ptc_count"], {"const": 24})
  1717. self.assertEqual(layers["pin_map"]["properties"]["fan_count"], {"const": 4})
  1718. if __name__ == "__main__":
  1719. unittest.main()