test_tier2_hil_e2e.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #!/usr/bin/env python3
  2. """
  3. test_tier2_hil_e2e.py — Tier 2 Multi-Station Hardware-in-the-Loop (HIL) Full-Stack Verification
  4. Executes 8 end-to-end real-process scenarios against unmodified `build/native/stl_native_server`
  5. wired over real IPMI v2.0 RMCP+ (`:623`), SSHv2 (`:2200`), UDP TFTP (`:19069`), and `/dev/pts/*`
  6. 6400 High-Temperature Hood controllers.
  7. """
  8. import asyncio
  9. import json
  10. import os
  11. from pathlib import Path
  12. import subprocess
  13. import sys
  14. import time
  15. from typing import Any, Callable, Dict
  16. sys.path.insert(0, str(Path(__file__).resolve().parent))
  17. from cluster_harness import HilClusterStack, ROOT_DIR # noqa: E402
  18. async def wait_until(
  19. pred: Callable[[], Any],
  20. timeout_s: float = 25.0,
  21. interval_s: float = 0.2,
  22. desc: str = "condition",
  23. ) -> Any:
  24. deadline = time.monotonic() + timeout_s
  25. last_val = None
  26. while time.monotonic() < deadline:
  27. res = pred()
  28. if asyncio.iscoroutine(res):
  29. res = await res
  30. last_val = res
  31. if res:
  32. return res
  33. await asyncio.sleep(interval_s)
  34. raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
  35. def auto_all_stages_plan(mt_enabled: bool = True, run_rmt: bool = True, run_amt: bool = True) -> Dict[str, Any]:
  36. return {
  37. "preset": "auto",
  38. "mt_enabled": mt_enabled,
  39. "run_rmt": run_rmt,
  40. "stages": {
  41. "uip1": "auto",
  42. "amt": "auto",
  43. "uip2": "auto",
  44. "uefi": "auto",
  45. },
  46. "amt_action": "run" if run_amt else "skip",
  47. }
  48. async def configure_station_auto(
  49. stack: HilClusterStack,
  50. station_id: str,
  51. *,
  52. mt_enabled: bool = True,
  53. run_rmt: bool = True,
  54. run_amt: bool = True,
  55. watchdog: Dict[str, Any] | None = None,
  56. ) -> None:
  57. await stack.enqueue_cmd(
  58. station_id,
  59. "SaveBootPlan",
  60. {
  61. "plan": auto_all_stages_plan(mt_enabled=mt_enabled, run_rmt=run_rmt, run_amt=run_amt),
  62. **({"watchdog": watchdog} if watchdog else {}),
  63. },
  64. )
  65. if not run_amt:
  66. await stack.enqueue_cmd(
  67. station_id,
  68. "SaveAmtSettings",
  69. {"settings": {"action": "skip", "exit_after": True}},
  70. )
  71. else:
  72. await stack.enqueue_cmd(
  73. station_id,
  74. "SaveAmtSettings",
  75. {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}},
  76. )
  77. if watchdog:
  78. await stack.enqueue_cmd(station_id, "ConfigureWatchdog", {"watchdog": watchdog})
  79. async def run_tier2_suite() -> Dict[str, Any]:
  80. results = []
  81. t_suite0 = time.monotonic()
  82. async with HilClusterStack(
  83. web_port=18980,
  84. tftp_port=19069,
  85. bmc_ctrl_port=19199,
  86. hil_http_port=19198,
  87. uart_base=19200,
  88. web_password="disabled",
  89. speed_scale=0.18,
  90. ) as stack:
  91. assert stack.admin_ws is not None
  92. print("[Tier2] Waiting for all 4 HIL stations (RMCP+ :623 & SSH :2200) to come online...", flush=True)
  93. for sid in ("S1", "S2", "S3", "S4"):
  94. await stack.wait_station_online(sid, timeout_s=15.0)
  95. # ====================================================================
  96. # Scenario 1: Full 7-Stage Automated PASS + 24-ch SDR Temps + TFTP HTML
  97. # ====================================================================
  98. print("[Tier2][1/8] Running full 7-stage automated PASS + 24-DIMM SDR + TFTP HTML report on S1...", flush=True)
  99. await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
  100. await configure_station_auto(
  101. stack,
  102. "S1",
  103. mt_enabled=True,
  104. watchdog={"dense_stage_silence_timeout_ms": 15000, "amt_silence_timeout_ms": 15000, "mt_silence_timeout_ms": 15000},
  105. )
  106. await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
  107. async def _s1_done():
  108. st = await stack.admin_ws.call("GetStation", {"station_id": "S1"})
  109. return st if st.get("task_status") in ("completed", "failed") else None
  110. st_s1 = await wait_until(_s1_done, timeout_s=35.0, desc="S1 full 7-stage completion")
  111. assert st_s1["task_status"] == "completed", f"Expected S1 completed, got {st_s1}"
  112. assert st_s1["verdict"] == "pass", f"Expected S1 pass, got {st_s1}"
  113. comps = st_s1.get("stage_completions") or {}
  114. for k in ("ict_stage1_complete", "training_complete", "rmt_complete", "amt_complete", "ict_stage2_complete", "uefi_complete", "mt_pass_complete"):
  115. assert comps.get(k) is True, f"Missing stage completion {k} in {comps}"
  116. # Verify 24-ch BMC SDR temperatures + Full BMC system sensors (Voltage/Fan/Power/Current) + TFTP HTML report + HTTP Boot
  117. ctrl_s1 = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
  118. dimms_s1 = ctrl_s1.get("dimms") or []
  119. assert len(dimms_s1) == 24, f"Expected 24 DIMMs, got {len(dimms_s1)}"
  120. valid_temps = [
  121. (d.get("temperature") or {}).get("value_c")
  122. for d in dimms_s1
  123. if isinstance((d.get("temperature") or {}).get("value_c"), (int, float))
  124. ]
  125. assert len(valid_temps) == 24, f"Expected 24 valid SDR/RMT DIMM temps, got {len(valid_temps)}"
  126. bmc_sensors_s1 = ctrl_s1.get("bmc_sensors") or []
  127. sensor_cats = {s.get("category") for s in bmc_sensors_s1}
  128. assert len(bmc_sensors_s1) >= 30, f"Expected >= 30 full BMC sensors (24 DIMM + 6 system), got {len(bmc_sensors_s1)}"
  129. for expected_cat in ("temp", "voltage", "fan", "power", "current"):
  130. assert expected_cat in sensor_cats, f"Missing BMC sensor category {expected_cat} in {sensor_cats}"
  131. # Verify bmc_sensors.jsonl archived in task-runs/
  132. archived_sensor_files = list((stack.data_dir / "task-runs").rglob("bmc_sensors.jsonl"))
  133. assert archived_sensor_files, "Expected bmc_sensors.jsonl archived inside task-runs/"
  134. # Verify unauthenticated UEFI HTTP Boot /pxe/118.efi & /pxe/mt86.cfg endpoints
  135. assert stack.http_session is not None
  136. async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/118.efi") as r_efi:
  137. assert r_efi.status == 200 and (await r_efi.read()).startswith(b"MZ"), "HTTP Boot /pxe/118.efi failed"
  138. async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/mt86.cfg") as r_cfg:
  139. assert r_cfg.status == 200 and b"TSTLIST=" in (await r_cfg.read()), "HTTP Boot /pxe/mt86.cfg failed"
  140. # Verify TEMP-2: GetDimmCurve returns BMC SDR fallback points on S2 even with NO hood connected!
  141. curve_s2 = await stack.admin_ws.call("GetDimmCurve", {"station_id": "S2", "slot": 0})
  142. assert len(curve_s2.get("points") or []) >= 1, f"Expected BMC SDR fallback curve points on S2, got {curve_s2}"
  143. pxe_rpts = ((ctrl_s1.get("pxe_control") or {}).get("recent_reports")) or []
  144. assert len(pxe_rpts) >= 1, "Expected TFTP WRQ MemTest86 HTML report in recent_reports"
  145. results.append({"scenario": "1_full_7stage_pass_full_bmc_sensors_tftp_httpboot", "status": "PASS", "bmc_sensor_count": len(bmc_sensors_s1)})
  146. print(f" -> PASS (bmc_sensors={len(bmc_sensors_s1)})", flush=True)
  147. # ====================================================================
  148. # Scenario 2: Single-Link Drop (<no reset>) + >5s Dual-Disconnect (`link_offline_waiting`)
  149. # + Reconnect Silent Prompt `\r` Re-Probe + `serial_gap_detected`
  150. # ====================================================================
  151. print("[Tier2][2/8] Testing single-link drop + >5s dual-disconnect + reconnect `\\r` prompt probe on S2...", flush=True)
  152. await stack.configure_dut(1, speed_scale=0.18)
  153. # 2a. Pause S2 deterministically at ICT Stage 2 (`uip2: manual`) so active run cannot race to completion
  154. await stack.enqueue_cmd(
  155. "S2",
  156. "SaveBootPlan",
  157. {
  158. "plan": {
  159. "preset": "custom",
  160. "mt_enabled": True,
  161. "run_rmt": True,
  162. "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
  163. },
  164. "watchdog": {"link_lost_timeout_ms": 30000, "dense_stage_silence_timeout_ms": 25000},
  165. },
  166. )
  167. await stack.enqueue_cmd(
  168. "S2",
  169. "SaveAmtSettings",
  170. {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}},
  171. )
  172. await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "restart"})
  173. async def _s2_at_uip2_manual():
  174. st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
  175. return st if (st.get("stage_completions") or {}).get("amt_complete") is True and st.get("task_status") == "running" else None
  176. await wait_until(_s2_at_uip2_manual, timeout_s=25.0, desc="S2 active run waiting at manual uip2")
  177. # Drop ONLY BMC (`bmc_up=False, serial_up=True`) until `bmc_state == 'offline'`, hold 2s -> NO reset & NO link_offline_waiting!
  178. await stack.set_link(1, bmc_up=False, serial_up=True)
  179. await wait_until(
  180. lambda: _check_bmc_state(stack, "S2", "offline"),
  181. timeout_s=20.0,
  182. desc="S2 single-link BMC offline",
  183. )
  184. await asyncio.sleep(2.0)
  185. st_single = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
  186. assert st_single.get("observed_detail") != "link_offline_waiting", (
  187. f"Single-link BMC drop must not trigger link_offline_waiting: {st_single}"
  188. )
  189. assert st_single.get("task_status") == "running", f"Expected S2 still running, got {st_single}"
  190. await stack.set_link(1, bmc_up=True, serial_up=True)
  191. await stack.wait_station_online("S2", timeout_s=20.0)
  192. # 2b. Switch S2 to full auto, start active run, then drop BOTH BMC + :2200 (`bmc_up=False, serial_up=False`).
  193. # While disconnected, reboot DUT so ICT Stage 1 prompt is emitted into the void and missed!
  194. await configure_station_auto(
  195. stack,
  196. "S2",
  197. mt_enabled=True,
  198. watchdog={
  199. "link_lost_timeout_ms": 30000,
  200. "dense_stage_silence_timeout_ms": 25000,
  201. "amt_silence_timeout_ms": 25000,
  202. "mt_silence_timeout_ms": 25000,
  203. "reconnect_prompt_probe_delay_ms": 800,
  204. },
  205. )
  206. await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "start"})
  207. await stack.set_link(1, bmc_up=False, serial_up=False)
  208. await asyncio.sleep(0.5)
  209. await stack.trigger_dut_boot(1, reason="missed_prompt_during_outage")
  210. async def _s2_link_waiting():
  211. st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
  212. return st if st.get("observed_detail") == "link_offline_waiting" else None
  213. st_wait = await wait_until(_s2_link_waiting, timeout_s=35.0, desc="S2 link_offline_waiting (>5s dual drop)")
  214. assert st_wait["task_status"] == "running", "Active test must NOT clear or fail during >5s grace window"
  215. # Restore BMC + :2200! `stl_native_server` reconnects to silent prompt, marks `serial_gap_detected=True`,
  216. # fires automatic `\r` probe after 800ms, receives re-echoed prompt, and completes all 7 stages!
  217. await stack.set_link(1, bmc_up=True, serial_up=True)
  218. async def _s2_recovered_and_done():
  219. st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
  220. return st if st.get("task_status") in ("completed", "failed") else None
  221. st_s2_done = await wait_until(_s2_recovered_and_done, timeout_s=35.0, desc="S2 recovery via CR probe & completion")
  222. if st_s2_done["task_status"] != "completed":
  223. hs_dbg = await stack.hil_status()
  224. uart_dbg = await stack.admin_ws.call("ReadCleanedUart", {"station_id": "S2", "offset": 0, "max_bytes": 8192})
  225. raise AssertionError(
  226. f"Expected S2 completed, got {st_s2_done}\nDUT={hs_dbg['duts'][1]}\nUART_TAIL={uart_dbg.get('text', '')[-1500:]}"
  227. )
  228. assert st_s2_done["serial_gap_detected"] is True, f"Expected serial_gap_detected=True on S2, got {st_s2_done}"
  229. # Check archived task history / GetTaskStatus also carries `serial_gap_detected: true`
  230. ts_s2 = await stack.admin_ws.call("GetTaskStatus", {"station_id": "S2"})
  231. latest_s2 = ts_s2.get("latest_run") or {}
  232. assert ts_s2.get("serial_gap_detected") is True and latest_s2.get("serial_gap_detected") is True, (
  233. f"Archived summary must record serial_gap_detected: {ts_s2}"
  234. )
  235. results.append({"scenario": "2_dual_drop_grace_serial_gap_and_cr_probe", "status": "PASS"})
  236. print(" -> PASS", flush=True)
  237. # ====================================================================
  238. # Scenario 3: Post-Reconnect `server_power == "off"` Verification + Hood Purge
  239. # ====================================================================
  240. print("[Tier2][3/8] Testing dual-disconnect + AC power loss -> `reconnect_power_off` FAIL + 6400 Hood 0x08 00 purge on S3...", flush=True)
  241. await stack.clear_hood_history(2)
  242. await stack.configure_dut(2, speed_scale=1.0)
  243. await stack.connect_and_heat_backend_hood("S3", 2, target_c=70)
  244. await stack.enqueue_cmd(
  245. "S3",
  246. "SaveBootPlan",
  247. {
  248. "plan": {
  249. "preset": "custom",
  250. "mt_enabled": True,
  251. "run_rmt": True,
  252. "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
  253. },
  254. "watchdog": {"link_lost_timeout_ms": 40000},
  255. },
  256. )
  257. await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"})
  258. await stack.trigger_dut_boot(2, reason="reset")
  259. await asyncio.sleep(0.5)
  260. # Unplug network AND cut server power (`power_on=False`) while S3 is actively running
  261. await stack.set_link(2, bmc_up=False, serial_up=False)
  262. await stack.set_power(2, power_on=False)
  263. try:
  264. await wait_until(
  265. lambda: _check_detail(stack, "S3", "link_offline_waiting"),
  266. timeout_s=35.0,
  267. desc="S3 link_offline_waiting",
  268. )
  269. except AssertionError:
  270. st_dbg = await stack.admin_ws.call("GetStation", {"station_id": "S3"})
  271. hs_dbg = await stack.hil_status()
  272. raise AssertionError(f"S3 link_offline_waiting timed out! S3={st_dbg}\nBMC={hs_dbg['bmc'][2]}")
  273. # Restore network while server remains powered OFF!
  274. await stack.set_link(2, bmc_up=True, serial_up=True)
  275. st_s3_fail = await wait_until(
  276. lambda: _check_failed(stack, "S3"),
  277. timeout_s=20.0,
  278. desc="S3 reconnect_power_off failure",
  279. )
  280. assert st_s3_fail.get("fault_code") == "reconnect_power_off", f"Expected reconnect_power_off, got {st_s3_fail}"
  281. assert int(st_s3_fail.get("ended_unix_ms") or "0") > 0, "Timer must be frozen on reconnect_power_off"
  282. await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 cooling purge")
  283. await stack.set_power(2, power_on=True)
  284. await stack.wait_station_online("S3", timeout_s=20.0)
  285. results.append({"scenario": "3_reconnect_power_off_and_hood_purge", "status": "PASS"})
  286. print(" -> PASS", flush=True)
  287. # ====================================================================
  288. # Scenario 4: Dual-Disconnect Timeout Ceiling (`link_lost_timeout`) + Hood Purge
  289. # ====================================================================
  290. print("[Tier2][4/8] Testing prolonged dual-disconnect -> `link_lost_timeout` FAIL + timer freeze + Hood purge on S3...", flush=True)
  291. await stack.clear_hood_history(2)
  292. await stack.configure_dut(2, speed_scale=1.0)
  293. await stack.connect_and_heat_backend_hood("S3", 2, target_c=70)
  294. await stack.enqueue_cmd(
  295. "S3",
  296. "SaveBootPlan",
  297. {
  298. "plan": {
  299. "preset": "custom",
  300. "mt_enabled": True,
  301. "run_rmt": True,
  302. "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
  303. },
  304. "watchdog": {"link_lost_timeout_ms": 9500},
  305. },
  306. )
  307. await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"})
  308. await stack.trigger_dut_boot(2, reason="reset")
  309. await asyncio.sleep(0.5)
  310. await stack.set_link(2, bmc_up=False, serial_up=False)
  311. await wait_until(lambda: _check_detail(stack, "S3", "link_offline_waiting"), timeout_s=35.0, desc="S3 link_offline_waiting")
  312. st_s3_to = await wait_until(lambda: _check_failed(stack, "S3"), timeout_s=20.0, desc="S3 link_lost_timeout")
  313. assert st_s3_to.get("fault_code") == "link_lost_timeout", f"Expected link_lost_timeout, got {st_s3_to}"
  314. elapsed_1 = st_s3_to.get("elapsed_ms")
  315. await asyncio.sleep(0.8)
  316. st_s3_to2 = await stack.admin_ws.call("GetStation", {"station_id": "S3"})
  317. assert st_s3_to2.get("elapsed_ms") == elapsed_1, f"Stopwatch must freeze on link_lost_timeout ({elapsed_1} vs {st_s3_to2.get('elapsed_ms')})"
  318. await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 purge after link_lost_timeout")
  319. # Restore S3 links
  320. await stack.set_link(2, bmc_up=True, serial_up=True)
  321. await stack.wait_station_online("S3", timeout_s=20.0)
  322. results.append({"scenario": "4_dual_disconnect_link_lost_timeout", "status": "PASS"})
  323. print(" -> PASS", flush=True)
  324. # ====================================================================
  325. # Scenario 5: Level-1 Hard Hang in RMT (`reboot_on_hang=False` default)
  326. # -> FAIL + Timer Freeze + Hood Purge + ZERO BMC Resets (Scene Preserved!)
  327. # ====================================================================
  328. print("[Tier2][5/8] Testing Level-1 RMT hard hang -> `stage_hang_timeout` + 0 BMC resets (scene preserved) + Hood purge on S1...", flush=True)
  329. await stack.clear_hood_history(0)
  330. await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
  331. await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15)
  332. await stack.enqueue_cmd(
  333. "S1",
  334. "SubmitTaskBatch",
  335. {
  336. "stop_on_fail": False,
  337. "reboot_on_hang": False, # Level-1 default: preserve hang scene even in multi-run batch!
  338. "watchdog": {"dense_stage_silence_timeout_ms": 2500},
  339. "profiles": [{"name": "Level1-RMT-Hang", "repeat": 3, "run_rmt": True, "run_amt": False, "run_mt": False}],
  340. },
  341. )
  342. # Wait until DUT enters `rmt` and freezes (`hung_now == True`)
  343. async def _s1_hung_in_rmt():
  344. hs = await stack.hil_status()
  345. d0 = hs["duts"][0]
  346. return hs if d0.get("hung_now") is True and d0.get("stage") == "rmt" else None
  347. hs_at_hang = await wait_until(_s1_hung_in_rmt, timeout_s=20.0, desc="S1 DUT frozen in RMT")
  348. bmc_before = hs_at_hang["bmc"][0]
  349. off_before = bmc_before["off_count"]
  350. rst_before = bmc_before["reset_count"]
  351. cyc_before = bmc_before["cycle_count"]
  352. boot_before = hs_at_hang["duts"][0]["hw_boot_count"]
  353. st_s1_hang = await wait_until(lambda: _check_failed(stack, "S1"), timeout_s=10.0, desc="S1 stage_hang_timeout")
  354. assert st_s1_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_s1_hang}"
  355. assert st_s1_hang.get("hang_scene_preserved") is True, f"Expected hang_scene_preserved=True, got {st_s1_hang}"
  356. # Wait 1.5s to ensure NO delayed BMC reset is issued!
  357. await asyncio.sleep(1.5)
  358. hs_after = await stack.hil_status()
  359. bmc_after = hs_after["bmc"][0]
  360. assert bmc_after["off_count"] == off_before, f"Level-1 hang MUST NOT power-off BMC ({off_before} -> {bmc_after['off_count']})"
  361. assert bmc_after["reset_count"] == rst_before, f"Level-1 hang MUST NOT reset BMC ({rst_before} -> {bmc_after['reset_count']})"
  362. assert bmc_after["cycle_count"] == cyc_before, "Level-1 hang MUST NOT power-cycle BMC"
  363. assert hs_after["duts"][0]["hw_boot_count"] == boot_before, "DUT must remain in exact hung boot scene"
  364. assert hs_after["bmc"][0]["ssh_active"] is True, "SSH :2200 console must remain open so R&D can inspect last line"
  365. batch_s1_resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
  366. batch_s1 = batch_s1_resp.get("task_batch") or {}
  367. assert batch_s1.get("halt_reason") == "hang_scene_preserved", f"Expected halt_reason=hang_scene_preserved, got {batch_s1}"
  368. assert len(batch_s1.get("runs") or []) == 1, "Batch must halt immediately after Run 1 without rebooting into Run 2"
  369. await wait_until(lambda: _check_hood_purged(stack, 0), timeout_s=5.0, desc="S1 hood 0x08 00 purge on RMT hang")
  370. await stack.configure_dut(0, hang_stage="", hang_remaining_boots=0)
  371. results.append({"scenario": "5_level1_hang_preserve_scene_and_hood_purge", "status": "PASS"})
  372. print(" -> PASS", flush=True)
  373. # ====================================================================
  374. # Scenario 6: MemTest86 Infinite ANSI Clock Redraw Caught by `mt_max_duration_ms`
  375. # ====================================================================
  376. print("[Tier2][6/8] Testing non-silent MT ANSI clock-redraw infinite loop caught by `mt_duration_timeout` on S4...", flush=True)
  377. await stack.clear_hood_history(3)
  378. await stack.connect_and_heat_backend_hood("S4", 3, target_c=70)
  379. await stack.configure_dut(3, hang_stage="mt_clock_loop", hang_remaining_boots=1, speed_scale=0.12)
  380. await configure_station_auto(
  381. stack,
  382. "S4",
  383. mt_enabled=True,
  384. run_rmt=False,
  385. run_amt=False,
  386. watchdog={
  387. "dense_stage_silence_timeout_ms": 20000,
  388. "mt_silence_timeout_ms": 60000, # Silence threshold high (ANSI clock keeps sending bytes!)
  389. "mt_max_duration_ms": 2500, # Stage duration cap catches infinite clock loop!
  390. },
  391. )
  392. await stack.enqueue_cmd("S4", "ControlBootPlan", {"action": "restart"})
  393. st_s4_mt = await wait_until(lambda: _check_failed(stack, "S4"), timeout_s=25.0, desc="S4 mt_duration_timeout")
  394. assert st_s4_mt.get("fault_code") == "mt_duration_timeout", f"Expected mt_duration_timeout, got {st_s4_mt}"
  395. await wait_until(lambda: _check_hood_purged(stack, 3), timeout_s=5.0, desc="S4 hood purge on mt_duration_timeout")
  396. await stack.configure_dut(3, hang_stage="", hang_remaining_boots=0)
  397. results.append({"scenario": "6_mt_ansi_clock_loop_duration_watchdog", "status": "PASS"})
  398. print(" -> PASS", flush=True)
  399. # ====================================================================
  400. # Scenario 7: 3-Mode Hang Recovery (`retry_current_task` + `restart_full_plan`) & Circuit Breaker
  401. # ====================================================================
  402. print("[Tier2][7/8] Testing 3-mode hang recovery: retry_current_task (S1) + restart_full_plan (S4) + max_consecutive_hangs breaker (S2)...", flush=True)
  403. # 7a: S1 hangs ONCE in RMT (`hang_remaining_boots=1`), `retry_current_task` REDOES unfinished Round 1 (PASS) AND runs Round 2 (PASS)!
  404. await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
  405. await stack.enqueue_cmd(
  406. "S1",
  407. "SubmitTaskBatch",
  408. {
  409. "stop_on_fail": False,
  410. "hang_action": "retry_current_task",
  411. "reboot_on_hang": True,
  412. "max_consecutive_hangs": 2,
  413. "watchdog": {"dense_stage_silence_timeout_ms": 2200},
  414. "profiles": [{"name": "RetryCurrentTask-2R", "repeat": 2, "run_rmt": True, "run_amt": False, "run_mt": False}],
  415. },
  416. )
  417. async def _s1_batch_done():
  418. resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
  419. b = resp.get("task_batch") or {}
  420. return b if b.get("state") in ("completed", "failed") else None
  421. b_s1_rec = await wait_until(_s1_batch_done, timeout_s=45.0, desc="S1 retry_current_task 2-round batch completion")
  422. runs_s1 = b_s1_rec.get("runs") or []
  423. assert len(runs_s1) == 3, f"Expected 3 runs (R1 hang -> SmartRestart redoes R1 pass -> R2 pass), got {b_s1_rec}"
  424. assert runs_s1[0].get("verdict") == "fail" and runs_s1[0].get("repeat_index") == 1, f"Expected R1 fail, got {runs_s1[0]}"
  425. assert runs_s1[1].get("verdict") == "pass" and runs_s1[1].get("repeat_index") == 1, f"Expected R1 redone PASS, got {runs_s1[1]}"
  426. assert runs_s1[2].get("verdict") == "pass" and runs_s1[2].get("repeat_index") == 2, f"Expected R2 PASS, got {runs_s1[2]}"
  427. # 7b: S4 `restart_full_plan`: Profile 1 (no RMT) PASS -> Profile 2 (with RMT) hangs ONCE -> restarts FULL PLAN back to Profile 1 -> both PASS!
  428. await stack.configure_dut(3, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
  429. await stack.enqueue_cmd(
  430. "S4",
  431. "SubmitTaskBatch",
  432. {
  433. "stop_on_fail": False,
  434. "hang_action": "restart_full_plan",
  435. "reboot_on_hang": True,
  436. "max_consecutive_hangs": 2,
  437. "watchdog": {"dense_stage_silence_timeout_ms": 2200},
  438. "profiles": [
  439. {"name": "Plan-Step1-NoRMT", "repeat": 1, "run_rmt": False, "run_amt": False, "run_mt": False},
  440. {"name": "Plan-Step2-RMT", "repeat": 1, "run_rmt": True, "run_amt": False, "run_mt": False},
  441. ],
  442. },
  443. )
  444. async def _s4_batch_done():
  445. resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S4"})
  446. b = resp.get("task_batch") or {}
  447. return b if b.get("state") in ("completed", "failed") else None
  448. b_s4_full = await wait_until(_s4_batch_done, timeout_s=50.0, desc="S4 restart_full_plan completion")
  449. runs_s4 = b_s4_full.get("runs") or []
  450. assert b_s4_full.get("state") == "completed", f"Expected S4 restart_full_plan completed, got {b_s4_full}"
  451. assert len(runs_s4) == 4, f"Expected 4 runs (P1 pass, P2 fail -> restart -> P1 pass, P2 pass), got {runs_s4}"
  452. assert [r.get("profile_name") for r in runs_s4] == ["Plan-Step1-NoRMT", "Plan-Step2-RMT", "Plan-Step1-NoRMT", "Plan-Step2-RMT"]
  453. assert [r.get("verdict") for r in runs_s4] == ["pass", "fail", "pass", "pass"]
  454. # 7c: S2 permanently dead board (`hang_remaining_boots=99`, `repeat=4`, `max_consecutive_hangs=2`)
  455. # -> hangs in R1, auto-reboots to redo R1, hangs again -> trips `consecutive_hang_limit_exceeded` & cools hood!
  456. await stack.clear_hood_history(1)
  457. await stack.connect_and_heat_backend_hood("S2", 1, target_c=70)
  458. await stack.configure_dut(1, hang_stage="rmt", hang_remaining_boots=99, speed_scale=0.12)
  459. await stack.enqueue_cmd(
  460. "S2",
  461. "SubmitTaskBatch",
  462. {
  463. "stop_on_fail": False,
  464. "reboot_on_hang": True,
  465. "max_consecutive_hangs": 2,
  466. "watchdog": {"dense_stage_silence_timeout_ms": 2200},
  467. "profiles": [{"name": "Level2-DeadBoard-Breaker", "repeat": 4, "run_rmt": True, "run_amt": False, "run_mt": False}],
  468. },
  469. )
  470. async def _s2_batch_done():
  471. resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S2"})
  472. b = resp.get("task_batch") or {}
  473. return b if b.get("state") in ("completed", "failed") else None
  474. b_s2_brk = await wait_until(_s2_batch_done, timeout_s=45.0, desc="S2 Level-2 circuit breaker halt")
  475. runs_s2 = b_s2_brk.get("runs") or []
  476. assert len(runs_s2) == 2, f"Circuit breaker must stop at 2 consecutive hangs (not run all 4!), got {len(runs_s2)}"
  477. assert b_s2_brk.get("halt_reason") == "consecutive_hang_limit_exceeded", f"Unexpected halt_reason: {b_s2_brk}"
  478. st_s2_brk = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
  479. assert st_s2_brk.get("hang_scene_preserved") is True, "Circuit breaker halt must preserve final hang scene"
  480. await wait_until(lambda: _check_hood_purged(stack, 1), timeout_s=5.0, desc="S2 hood purge on circuit breaker")
  481. await stack.configure_dut(1, hang_stage="", hang_remaining_boots=0)
  482. results.append({"scenario": "7_level2_smart_restart_recovery_and_circuit_breaker", "status": "PASS"})
  483. print(" -> PASS", flush=True)
  484. # ====================================================================
  485. # Scenario 8: Web-Only Closed-Loop Thermal Auto-Heat + Cool Purge + Dynamic Stations + XLSX Export
  486. # ====================================================================
  487. print("[Tier2][8/8] Testing Web-only closed-loop 6400 thermal auto-heat/cool, dynamic stations & .xlsx export...", flush=True)
  488. add_res = await stack.admin_ws.call("AddStation", {"station_id": "S5", "name": "HIL动态工位5", "cpu_count": 2})
  489. assert len(add_res.get("stations") or []) == 5, f"Expected 5 stations after AddStation, got {add_res}"
  490. rem_res = await stack.admin_ws.call("RemoveStation", {"station_id": "S5"})
  491. assert len(rem_res.get("stations") or []) == 4, f"Expected 4 stations after RemoveStation, got {rem_res}"
  492. # Verify `.xlsx` alarm export endpoint returns valid ZIP/OpenXML workbook
  493. assert stack.http_session is not None
  494. async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/api/stations/S1/alarms.xlsx") as resp:
  495. assert resp.status == 200, f"alarms.xlsx HTTP status {resp.status}"
  496. xlsx_bytes = await resp.read()
  497. assert xlsx_bytes[:4] == b"PK\x03\x04", "alarms.xlsx must be a valid ZIP/OpenXML workbook"
  498. assert b"xl/worksheets/sheet1.xml" in xlsx_bytes
  499. results.append({"scenario": "8_web_only_dynamic_stations_and_xlsx_export", "status": "PASS"})
  500. print(" -> PASS", flush=True)
  501. elapsed_s = round(time.monotonic() - t_suite0, 2)
  502. summary = {"tier": "Tier2_MultiStation_HIL_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
  503. print("\n[Tier2] ALL 8 MULTI-STATION HIL SCENARIOS PASSED in " + f"{elapsed_s}s!", flush=True)
  504. return summary
  505. async def _check_bmc_state(stack: HilClusterStack, sid: str, expected: str) -> Any:
  506. assert stack.admin_ws is not None
  507. st = await stack.admin_ws.call("GetStation", {"station_id": sid})
  508. return st if st.get("bmc_state") == expected else None
  509. async def _check_detail(stack: HilClusterStack, sid: str, expected_detail: str) -> Any:
  510. assert stack.admin_ws is not None
  511. st = await stack.admin_ws.call("GetStation", {"station_id": sid})
  512. if st.get("observed_detail") == expected_detail:
  513. return st
  514. return False
  515. async def _check_failed(stack: HilClusterStack, sid: str) -> Any:
  516. assert stack.admin_ws is not None
  517. st = await stack.admin_ws.call("GetStation", {"station_id": sid})
  518. return st if st.get("task_status") == "failed" else None
  519. async def _check_hood_purged(stack: HilClusterStack, idx: int) -> Any:
  520. hs = await stack.hil_status()
  521. hood = hs["backend_hoods"][idx]
  522. return hood if hood.get("purge_cool_count", 0) >= 1 and hood.get("cooling_purge") is True else None
  523. if __name__ == "__main__":
  524. res = asyncio.run(run_tier2_suite())
  525. out_file = ROOT_DIR / "build" / "sim" / "tier2_hil_report.json"
  526. out_file.parent.mkdir(parents=True, exist_ok=True)
  527. out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")