#!/usr/bin/env python3 """ test_tier2_hil_e2e.py — Tier 2 Multi-Station Hardware-in-the-Loop (HIL) Full-Stack Verification Executes 8 end-to-end real-process scenarios against unmodified `build/native/stl_native_server` wired over real IPMI v2.0 RMCP+ (`:623`), SSHv2 (`:2200`), UDP TFTP (`:19069`), and `/dev/pts/*` 6400 High-Temperature Hood controllers. """ import asyncio import json import os from pathlib import Path import subprocess import sys import time from typing import Any, Callable, Dict sys.path.insert(0, str(Path(__file__).resolve().parent)) from cluster_harness import HilClusterStack, ROOT_DIR # noqa: E402 async def wait_until( pred: Callable[[], Any], timeout_s: float = 25.0, interval_s: float = 0.2, desc: str = "condition", ) -> Any: deadline = time.monotonic() + timeout_s last_val = None while time.monotonic() < deadline: res = pred() if asyncio.iscoroutine(res): res = await res last_val = res if res: return res await asyncio.sleep(interval_s) raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}") def auto_all_stages_plan(mt_enabled: bool = True, run_rmt: bool = True, run_amt: bool = True) -> Dict[str, Any]: return { "preset": "auto", "mt_enabled": mt_enabled, "run_rmt": run_rmt, "stages": { "uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto", }, "amt_action": "run" if run_amt else "skip", } async def configure_station_auto( stack: HilClusterStack, station_id: str, *, mt_enabled: bool = True, run_rmt: bool = True, run_amt: bool = True, watchdog: Dict[str, Any] | None = None, ) -> None: await stack.enqueue_cmd( station_id, "SaveBootPlan", { "plan": auto_all_stages_plan(mt_enabled=mt_enabled, run_rmt=run_rmt, run_amt=run_amt), **({"watchdog": watchdog} if watchdog else {}), }, ) if not run_amt: await stack.enqueue_cmd( station_id, "SaveAmtSettings", {"settings": {"action": "skip", "exit_after": True}}, ) else: await stack.enqueue_cmd( station_id, "SaveAmtSettings", {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}}, ) if watchdog: await stack.enqueue_cmd(station_id, "ConfigureWatchdog", {"watchdog": watchdog}) async def run_tier2_suite() -> Dict[str, Any]: results = [] t_suite0 = time.monotonic() async with HilClusterStack( web_port=18980, tftp_port=19069, bmc_ctrl_port=19199, hil_http_port=19198, uart_base=19200, web_password="disabled", speed_scale=0.18, ) as stack: assert stack.admin_ws is not None print("[Tier2] Waiting for all 4 HIL stations (RMCP+ :623 & SSH :2200) to come online...", flush=True) for sid in ("S1", "S2", "S3", "S4"): await stack.wait_station_online(sid, timeout_s=15.0) # ==================================================================== # Scenario 1: Full 7-Stage Automated PASS + 24-ch SDR Temps + TFTP HTML # ==================================================================== print("[Tier2][1/8] Running full 7-stage automated PASS + 24-DIMM SDR + TFTP HTML report on S1...", flush=True) await stack.connect_and_heat_backend_hood("S1", 0, target_c=70) await configure_station_auto( stack, "S1", mt_enabled=True, watchdog={"dense_stage_silence_timeout_ms": 15000, "amt_silence_timeout_ms": 15000, "mt_silence_timeout_ms": 15000}, ) await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"}) async def _s1_done(): st = await stack.admin_ws.call("GetStation", {"station_id": "S1"}) return st if st.get("task_status") in ("completed", "failed") else None st_s1 = await wait_until(_s1_done, timeout_s=35.0, desc="S1 full 7-stage completion") assert st_s1["task_status"] == "completed", f"Expected S1 completed, got {st_s1}" assert st_s1["verdict"] == "pass", f"Expected S1 pass, got {st_s1}" comps = st_s1.get("stage_completions") or {} for k in ("ict_stage1_complete", "training_complete", "rmt_complete", "amt_complete", "ict_stage2_complete", "uefi_complete", "mt_pass_complete"): assert comps.get(k) is True, f"Missing stage completion {k} in {comps}" # Verify 24-ch BMC SDR temperatures + Full BMC system sensors (Voltage/Fan/Power/Current) + TFTP HTML report + HTTP Boot ctrl_s1 = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"}) dimms_s1 = ctrl_s1.get("dimms") or [] assert len(dimms_s1) == 24, f"Expected 24 DIMMs, got {len(dimms_s1)}" valid_temps = [ (d.get("temperature") or {}).get("value_c") for d in dimms_s1 if isinstance((d.get("temperature") or {}).get("value_c"), (int, float)) ] assert len(valid_temps) == 24, f"Expected 24 valid SDR/RMT DIMM temps, got {len(valid_temps)}" bmc_sensors_s1 = ctrl_s1.get("bmc_sensors") or [] sensor_cats = {s.get("category") for s in bmc_sensors_s1} assert len(bmc_sensors_s1) >= 30, f"Expected >= 30 full BMC sensors (24 DIMM + 6 system), got {len(bmc_sensors_s1)}" for expected_cat in ("temp", "voltage", "fan", "power", "current"): assert expected_cat in sensor_cats, f"Missing BMC sensor category {expected_cat} in {sensor_cats}" # Verify bmc_sensors.jsonl archived in task-runs/ archived_sensor_files = list((stack.data_dir / "task-runs").rglob("bmc_sensors.jsonl")) assert archived_sensor_files, "Expected bmc_sensors.jsonl archived inside task-runs/" # Verify unauthenticated UEFI HTTP Boot /pxe/118.efi & /pxe/mt86.cfg endpoints assert stack.http_session is not None async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/118.efi") as r_efi: assert r_efi.status == 200 and (await r_efi.read()).startswith(b"MZ"), "HTTP Boot /pxe/118.efi failed" async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/mt86.cfg") as r_cfg: assert r_cfg.status == 200 and b"TSTLIST=" in (await r_cfg.read()), "HTTP Boot /pxe/mt86.cfg failed" # Verify TEMP-2: GetDimmCurve returns BMC SDR fallback points on S2 even with NO hood connected! curve_s2 = await stack.admin_ws.call("GetDimmCurve", {"station_id": "S2", "slot": 0}) assert len(curve_s2.get("points") or []) >= 1, f"Expected BMC SDR fallback curve points on S2, got {curve_s2}" pxe_rpts = ((ctrl_s1.get("pxe_control") or {}).get("recent_reports")) or [] assert len(pxe_rpts) >= 1, "Expected TFTP WRQ MemTest86 HTML report in recent_reports" results.append({"scenario": "1_full_7stage_pass_full_bmc_sensors_tftp_httpboot", "status": "PASS", "bmc_sensor_count": len(bmc_sensors_s1)}) print(f" -> PASS (bmc_sensors={len(bmc_sensors_s1)})", flush=True) # ==================================================================== # Scenario 2: Single-Link Drop () + >5s Dual-Disconnect (`link_offline_waiting`) # + Reconnect Silent Prompt `\r` Re-Probe + `serial_gap_detected` # ==================================================================== print("[Tier2][2/8] Testing single-link drop + >5s dual-disconnect + reconnect `\\r` prompt probe on S2...", flush=True) await stack.configure_dut(1, speed_scale=0.18) # 2a. Pause S2 deterministically at ICT Stage 2 (`uip2: manual`) so active run cannot race to completion await stack.enqueue_cmd( "S2", "SaveBootPlan", { "plan": { "preset": "custom", "mt_enabled": True, "run_rmt": True, "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"}, }, "watchdog": {"link_lost_timeout_ms": 30000, "dense_stage_silence_timeout_ms": 25000}, }, ) await stack.enqueue_cmd( "S2", "SaveAmtSettings", {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}}, ) await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "restart"}) async def _s2_at_uip2_manual(): st = await stack.admin_ws.call("GetStation", {"station_id": "S2"}) return st if (st.get("stage_completions") or {}).get("amt_complete") is True and st.get("task_status") == "running" else None await wait_until(_s2_at_uip2_manual, timeout_s=25.0, desc="S2 active run waiting at manual uip2") # Drop ONLY BMC (`bmc_up=False, serial_up=True`) until `bmc_state == 'offline'`, hold 2s -> NO reset & NO link_offline_waiting! await stack.set_link(1, bmc_up=False, serial_up=True) await wait_until( lambda: _check_bmc_state(stack, "S2", "offline"), timeout_s=20.0, desc="S2 single-link BMC offline", ) await asyncio.sleep(2.0) st_single = await stack.admin_ws.call("GetStation", {"station_id": "S2"}) assert st_single.get("observed_detail") != "link_offline_waiting", ( f"Single-link BMC drop must not trigger link_offline_waiting: {st_single}" ) assert st_single.get("task_status") == "running", f"Expected S2 still running, got {st_single}" await stack.set_link(1, bmc_up=True, serial_up=True) await stack.wait_station_online("S2", timeout_s=20.0) # 2b. Switch S2 to full auto, start active run, then drop BOTH BMC + :2200 (`bmc_up=False, serial_up=False`). # While disconnected, reboot DUT so ICT Stage 1 prompt is emitted into the void and missed! await configure_station_auto( stack, "S2", mt_enabled=True, watchdog={ "link_lost_timeout_ms": 30000, "dense_stage_silence_timeout_ms": 25000, "amt_silence_timeout_ms": 25000, "mt_silence_timeout_ms": 25000, "reconnect_prompt_probe_delay_ms": 800, }, ) await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "start"}) await stack.set_link(1, bmc_up=False, serial_up=False) await asyncio.sleep(0.5) await stack.trigger_dut_boot(1, reason="missed_prompt_during_outage") async def _s2_link_waiting(): st = await stack.admin_ws.call("GetStation", {"station_id": "S2"}) return st if st.get("observed_detail") == "link_offline_waiting" else None st_wait = await wait_until(_s2_link_waiting, timeout_s=35.0, desc="S2 link_offline_waiting (>5s dual drop)") assert st_wait["task_status"] == "running", "Active test must NOT clear or fail during >5s grace window" # Restore BMC + :2200! `stl_native_server` reconnects to silent prompt, marks `serial_gap_detected=True`, # fires automatic `\r` probe after 800ms, receives re-echoed prompt, and completes all 7 stages! await stack.set_link(1, bmc_up=True, serial_up=True) async def _s2_recovered_and_done(): st = await stack.admin_ws.call("GetStation", {"station_id": "S2"}) return st if st.get("task_status") in ("completed", "failed") else None st_s2_done = await wait_until(_s2_recovered_and_done, timeout_s=35.0, desc="S2 recovery via CR probe & completion") if st_s2_done["task_status"] != "completed": hs_dbg = await stack.hil_status() uart_dbg = await stack.admin_ws.call("ReadCleanedUart", {"station_id": "S2", "offset": 0, "max_bytes": 8192}) raise AssertionError( f"Expected S2 completed, got {st_s2_done}\nDUT={hs_dbg['duts'][1]}\nUART_TAIL={uart_dbg.get('text', '')[-1500:]}" ) assert st_s2_done["serial_gap_detected"] is True, f"Expected serial_gap_detected=True on S2, got {st_s2_done}" # Check archived task history / GetTaskStatus also carries `serial_gap_detected: true` ts_s2 = await stack.admin_ws.call("GetTaskStatus", {"station_id": "S2"}) latest_s2 = ts_s2.get("latest_run") or {} assert ts_s2.get("serial_gap_detected") is True and latest_s2.get("serial_gap_detected") is True, ( f"Archived summary must record serial_gap_detected: {ts_s2}" ) results.append({"scenario": "2_dual_drop_grace_serial_gap_and_cr_probe", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 3: Post-Reconnect `server_power == "off"` Verification + Hood Purge # ==================================================================== print("[Tier2][3/8] Testing dual-disconnect + AC power loss -> `reconnect_power_off` FAIL + 6400 Hood 0x08 00 purge on S3...", flush=True) await stack.clear_hood_history(2) await stack.configure_dut(2, speed_scale=1.0) await stack.connect_and_heat_backend_hood("S3", 2, target_c=70) await stack.enqueue_cmd( "S3", "SaveBootPlan", { "plan": { "preset": "custom", "mt_enabled": True, "run_rmt": True, "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"}, }, "watchdog": {"link_lost_timeout_ms": 40000}, }, ) await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"}) await stack.trigger_dut_boot(2, reason="reset") await asyncio.sleep(0.5) # Unplug network AND cut server power (`power_on=False`) while S3 is actively running await stack.set_link(2, bmc_up=False, serial_up=False) await stack.set_power(2, power_on=False) try: await wait_until( lambda: _check_detail(stack, "S3", "link_offline_waiting"), timeout_s=35.0, desc="S3 link_offline_waiting", ) except AssertionError: st_dbg = await stack.admin_ws.call("GetStation", {"station_id": "S3"}) hs_dbg = await stack.hil_status() raise AssertionError(f"S3 link_offline_waiting timed out! S3={st_dbg}\nBMC={hs_dbg['bmc'][2]}") # Restore network while server remains powered OFF! await stack.set_link(2, bmc_up=True, serial_up=True) st_s3_fail = await wait_until( lambda: _check_failed(stack, "S3"), timeout_s=20.0, desc="S3 reconnect_power_off failure", ) assert st_s3_fail.get("fault_code") == "reconnect_power_off", f"Expected reconnect_power_off, got {st_s3_fail}" assert int(st_s3_fail.get("ended_unix_ms") or "0") > 0, "Timer must be frozen on reconnect_power_off" await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 cooling purge") await stack.set_power(2, power_on=True) await stack.wait_station_online("S3", timeout_s=20.0) results.append({"scenario": "3_reconnect_power_off_and_hood_purge", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 4: Dual-Disconnect Timeout Ceiling (`link_lost_timeout`) + Hood Purge # ==================================================================== print("[Tier2][4/8] Testing prolonged dual-disconnect -> `link_lost_timeout` FAIL + timer freeze + Hood purge on S3...", flush=True) await stack.clear_hood_history(2) await stack.configure_dut(2, speed_scale=1.0) await stack.connect_and_heat_backend_hood("S3", 2, target_c=70) await stack.enqueue_cmd( "S3", "SaveBootPlan", { "plan": { "preset": "custom", "mt_enabled": True, "run_rmt": True, "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"}, }, "watchdog": {"link_lost_timeout_ms": 9500}, }, ) await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"}) await stack.trigger_dut_boot(2, reason="reset") await asyncio.sleep(0.5) await stack.set_link(2, bmc_up=False, serial_up=False) await wait_until(lambda: _check_detail(stack, "S3", "link_offline_waiting"), timeout_s=35.0, desc="S3 link_offline_waiting") st_s3_to = await wait_until(lambda: _check_failed(stack, "S3"), timeout_s=20.0, desc="S3 link_lost_timeout") assert st_s3_to.get("fault_code") == "link_lost_timeout", f"Expected link_lost_timeout, got {st_s3_to}" elapsed_1 = st_s3_to.get("elapsed_ms") await asyncio.sleep(0.8) st_s3_to2 = await stack.admin_ws.call("GetStation", {"station_id": "S3"}) 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')})" await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 purge after link_lost_timeout") # Restore S3 links await stack.set_link(2, bmc_up=True, serial_up=True) await stack.wait_station_online("S3", timeout_s=20.0) results.append({"scenario": "4_dual_disconnect_link_lost_timeout", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 5: Level-1 Hard Hang in RMT (`reboot_on_hang=False` default) # -> FAIL + Timer Freeze + Hood Purge + ZERO BMC Resets (Scene Preserved!) # ==================================================================== print("[Tier2][5/8] Testing Level-1 RMT hard hang -> `stage_hang_timeout` + 0 BMC resets (scene preserved) + Hood purge on S1...", flush=True) await stack.clear_hood_history(0) await stack.connect_and_heat_backend_hood("S1", 0, target_c=70) await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15) await stack.enqueue_cmd( "S1", "SubmitTaskBatch", { "stop_on_fail": False, "reboot_on_hang": False, # Level-1 default: preserve hang scene even in multi-run batch! "watchdog": {"dense_stage_silence_timeout_ms": 2500}, "profiles": [{"name": "Level1-RMT-Hang", "repeat": 3, "run_rmt": True, "run_amt": False, "run_mt": False}], }, ) # Wait until DUT enters `rmt` and freezes (`hung_now == True`) async def _s1_hung_in_rmt(): hs = await stack.hil_status() d0 = hs["duts"][0] return hs if d0.get("hung_now") is True and d0.get("stage") == "rmt" else None hs_at_hang = await wait_until(_s1_hung_in_rmt, timeout_s=20.0, desc="S1 DUT frozen in RMT") bmc_before = hs_at_hang["bmc"][0] off_before = bmc_before["off_count"] rst_before = bmc_before["reset_count"] cyc_before = bmc_before["cycle_count"] boot_before = hs_at_hang["duts"][0]["hw_boot_count"] st_s1_hang = await wait_until(lambda: _check_failed(stack, "S1"), timeout_s=10.0, desc="S1 stage_hang_timeout") assert st_s1_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_s1_hang}" assert st_s1_hang.get("hang_scene_preserved") is True, f"Expected hang_scene_preserved=True, got {st_s1_hang}" # Wait 1.5s to ensure NO delayed BMC reset is issued! await asyncio.sleep(1.5) hs_after = await stack.hil_status() bmc_after = hs_after["bmc"][0] assert bmc_after["off_count"] == off_before, f"Level-1 hang MUST NOT power-off BMC ({off_before} -> {bmc_after['off_count']})" assert bmc_after["reset_count"] == rst_before, f"Level-1 hang MUST NOT reset BMC ({rst_before} -> {bmc_after['reset_count']})" assert bmc_after["cycle_count"] == cyc_before, "Level-1 hang MUST NOT power-cycle BMC" assert hs_after["duts"][0]["hw_boot_count"] == boot_before, "DUT must remain in exact hung boot scene" assert hs_after["bmc"][0]["ssh_active"] is True, "SSH :2200 console must remain open so R&D can inspect last line" batch_s1_resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"}) batch_s1 = batch_s1_resp.get("task_batch") or {} assert batch_s1.get("halt_reason") == "hang_scene_preserved", f"Expected halt_reason=hang_scene_preserved, got {batch_s1}" assert len(batch_s1.get("runs") or []) == 1, "Batch must halt immediately after Run 1 without rebooting into Run 2" await wait_until(lambda: _check_hood_purged(stack, 0), timeout_s=5.0, desc="S1 hood 0x08 00 purge on RMT hang") await stack.configure_dut(0, hang_stage="", hang_remaining_boots=0) results.append({"scenario": "5_level1_hang_preserve_scene_and_hood_purge", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 6: MemTest86 Infinite ANSI Clock Redraw Caught by `mt_max_duration_ms` # ==================================================================== print("[Tier2][6/8] Testing non-silent MT ANSI clock-redraw infinite loop caught by `mt_duration_timeout` on S4...", flush=True) await stack.clear_hood_history(3) await stack.connect_and_heat_backend_hood("S4", 3, target_c=70) await stack.configure_dut(3, hang_stage="mt_clock_loop", hang_remaining_boots=1, speed_scale=0.12) await configure_station_auto( stack, "S4", mt_enabled=True, run_rmt=False, run_amt=False, watchdog={ "dense_stage_silence_timeout_ms": 20000, "mt_silence_timeout_ms": 60000, # Silence threshold high (ANSI clock keeps sending bytes!) "mt_max_duration_ms": 2500, # Stage duration cap catches infinite clock loop! }, ) await stack.enqueue_cmd("S4", "ControlBootPlan", {"action": "restart"}) st_s4_mt = await wait_until(lambda: _check_failed(stack, "S4"), timeout_s=25.0, desc="S4 mt_duration_timeout") assert st_s4_mt.get("fault_code") == "mt_duration_timeout", f"Expected mt_duration_timeout, got {st_s4_mt}" await wait_until(lambda: _check_hood_purged(stack, 3), timeout_s=5.0, desc="S4 hood purge on mt_duration_timeout") await stack.configure_dut(3, hang_stage="", hang_remaining_boots=0) results.append({"scenario": "6_mt_ansi_clock_loop_duration_watchdog", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 7: 3-Mode Hang Recovery (`retry_current_task` + `restart_full_plan`) & Circuit Breaker # ==================================================================== print("[Tier2][7/8] Testing 3-mode hang recovery: retry_current_task (S1) + restart_full_plan (S4) + max_consecutive_hangs breaker (S2)...", flush=True) # 7a: S1 hangs ONCE in RMT (`hang_remaining_boots=1`), `retry_current_task` REDOES unfinished Round 1 (PASS) AND runs Round 2 (PASS)! await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12) await stack.enqueue_cmd( "S1", "SubmitTaskBatch", { "stop_on_fail": False, "hang_action": "retry_current_task", "reboot_on_hang": True, "max_consecutive_hangs": 2, "watchdog": {"dense_stage_silence_timeout_ms": 2200}, "profiles": [{"name": "RetryCurrentTask-2R", "repeat": 2, "run_rmt": True, "run_amt": False, "run_mt": False}], }, ) async def _s1_batch_done(): resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"}) b = resp.get("task_batch") or {} return b if b.get("state") in ("completed", "failed") else None b_s1_rec = await wait_until(_s1_batch_done, timeout_s=45.0, desc="S1 retry_current_task 2-round batch completion") runs_s1 = b_s1_rec.get("runs") or [] assert len(runs_s1) == 3, f"Expected 3 runs (R1 hang -> SmartRestart redoes R1 pass -> R2 pass), got {b_s1_rec}" assert runs_s1[0].get("verdict") == "fail" and runs_s1[0].get("repeat_index") == 1, f"Expected R1 fail, got {runs_s1[0]}" assert runs_s1[1].get("verdict") == "pass" and runs_s1[1].get("repeat_index") == 1, f"Expected R1 redone PASS, got {runs_s1[1]}" assert runs_s1[2].get("verdict") == "pass" and runs_s1[2].get("repeat_index") == 2, f"Expected R2 PASS, got {runs_s1[2]}" # 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! await stack.configure_dut(3, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12) await stack.enqueue_cmd( "S4", "SubmitTaskBatch", { "stop_on_fail": False, "hang_action": "restart_full_plan", "reboot_on_hang": True, "max_consecutive_hangs": 2, "watchdog": {"dense_stage_silence_timeout_ms": 2200}, "profiles": [ {"name": "Plan-Step1-NoRMT", "repeat": 1, "run_rmt": False, "run_amt": False, "run_mt": False}, {"name": "Plan-Step2-RMT", "repeat": 1, "run_rmt": True, "run_amt": False, "run_mt": False}, ], }, ) async def _s4_batch_done(): resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S4"}) b = resp.get("task_batch") or {} return b if b.get("state") in ("completed", "failed") else None b_s4_full = await wait_until(_s4_batch_done, timeout_s=50.0, desc="S4 restart_full_plan completion") runs_s4 = b_s4_full.get("runs") or [] assert b_s4_full.get("state") == "completed", f"Expected S4 restart_full_plan completed, got {b_s4_full}" assert len(runs_s4) == 4, f"Expected 4 runs (P1 pass, P2 fail -> restart -> P1 pass, P2 pass), got {runs_s4}" assert [r.get("profile_name") for r in runs_s4] == ["Plan-Step1-NoRMT", "Plan-Step2-RMT", "Plan-Step1-NoRMT", "Plan-Step2-RMT"] assert [r.get("verdict") for r in runs_s4] == ["pass", "fail", "pass", "pass"] # 7c: S2 permanently dead board (`hang_remaining_boots=99`, `repeat=4`, `max_consecutive_hangs=2`) # -> hangs in R1, auto-reboots to redo R1, hangs again -> trips `consecutive_hang_limit_exceeded` & cools hood! await stack.clear_hood_history(1) await stack.connect_and_heat_backend_hood("S2", 1, target_c=70) await stack.configure_dut(1, hang_stage="rmt", hang_remaining_boots=99, speed_scale=0.12) await stack.enqueue_cmd( "S2", "SubmitTaskBatch", { "stop_on_fail": False, "reboot_on_hang": True, "max_consecutive_hangs": 2, "watchdog": {"dense_stage_silence_timeout_ms": 2200}, "profiles": [{"name": "Level2-DeadBoard-Breaker", "repeat": 4, "run_rmt": True, "run_amt": False, "run_mt": False}], }, ) async def _s2_batch_done(): resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S2"}) b = resp.get("task_batch") or {} return b if b.get("state") in ("completed", "failed") else None b_s2_brk = await wait_until(_s2_batch_done, timeout_s=45.0, desc="S2 Level-2 circuit breaker halt") runs_s2 = b_s2_brk.get("runs") or [] assert len(runs_s2) == 2, f"Circuit breaker must stop at 2 consecutive hangs (not run all 4!), got {len(runs_s2)}" assert b_s2_brk.get("halt_reason") == "consecutive_hang_limit_exceeded", f"Unexpected halt_reason: {b_s2_brk}" st_s2_brk = await stack.admin_ws.call("GetStation", {"station_id": "S2"}) assert st_s2_brk.get("hang_scene_preserved") is True, "Circuit breaker halt must preserve final hang scene" await wait_until(lambda: _check_hood_purged(stack, 1), timeout_s=5.0, desc="S2 hood purge on circuit breaker") await stack.configure_dut(1, hang_stage="", hang_remaining_boots=0) results.append({"scenario": "7_level2_smart_restart_recovery_and_circuit_breaker", "status": "PASS"}) print(" -> PASS", flush=True) # ==================================================================== # Scenario 8: Web-Only Closed-Loop Thermal Auto-Heat + Cool Purge + Dynamic Stations + XLSX Export # ==================================================================== print("[Tier2][8/8] Testing Web-only closed-loop 6400 thermal auto-heat/cool, dynamic stations & .xlsx export...", flush=True) add_res = await stack.admin_ws.call("AddStation", {"station_id": "S5", "name": "HIL动态工位5", "cpu_count": 2}) assert len(add_res.get("stations") or []) == 5, f"Expected 5 stations after AddStation, got {add_res}" rem_res = await stack.admin_ws.call("RemoveStation", {"station_id": "S5"}) assert len(rem_res.get("stations") or []) == 4, f"Expected 4 stations after RemoveStation, got {rem_res}" # Verify `.xlsx` alarm export endpoint returns valid ZIP/OpenXML workbook assert stack.http_session is not None async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/api/stations/S1/alarms.xlsx") as resp: assert resp.status == 200, f"alarms.xlsx HTTP status {resp.status}" xlsx_bytes = await resp.read() assert xlsx_bytes[:4] == b"PK\x03\x04", "alarms.xlsx must be a valid ZIP/OpenXML workbook" assert b"xl/worksheets/sheet1.xml" in xlsx_bytes results.append({"scenario": "8_web_only_dynamic_stations_and_xlsx_export", "status": "PASS"}) print(" -> PASS", flush=True) elapsed_s = round(time.monotonic() - t_suite0, 2) summary = {"tier": "Tier2_MultiStation_HIL_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results} print("\n[Tier2] ALL 8 MULTI-STATION HIL SCENARIOS PASSED in " + f"{elapsed_s}s!", flush=True) return summary async def _check_bmc_state(stack: HilClusterStack, sid: str, expected: str) -> Any: assert stack.admin_ws is not None st = await stack.admin_ws.call("GetStation", {"station_id": sid}) return st if st.get("bmc_state") == expected else None async def _check_detail(stack: HilClusterStack, sid: str, expected_detail: str) -> Any: assert stack.admin_ws is not None st = await stack.admin_ws.call("GetStation", {"station_id": sid}) if st.get("observed_detail") == expected_detail: return st return False async def _check_failed(stack: HilClusterStack, sid: str) -> Any: assert stack.admin_ws is not None st = await stack.admin_ws.call("GetStation", {"station_id": sid}) return st if st.get("task_status") == "failed" else None async def _check_hood_purged(stack: HilClusterStack, idx: int) -> Any: hs = await stack.hil_status() hood = hs["backend_hoods"][idx] return hood if hood.get("purge_cool_count", 0) >= 1 and hood.get("cooling_purge") is True else None if __name__ == "__main__": res = asyncio.run(run_tier2_suite()) out_file = ROOT_DIR / "build" / "sim" / "tier2_hil_report.json" out_file.parent.mkdir(parents=True, exist_ok=True) out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")