| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463 |
- """Workflow integration tests: local simulated devices and durable SQLite only."""
- from __future__ import annotations
- import asyncio
- import copy
- import json
- import os
- from pathlib import Path
- import sys
- import tempfile
- import unittest
- from unittest.mock import patch
- import uuid
- from stl_backend.config import load_settings
- from stl_backend.devices import ManualActionRequired, SimulatedDevice
- from stl_backend.engine import Bench
- from stl_backend.errors import BenchError
- ROOT = Path(__file__).resolve().parents[1]
- class ColdDevice(SimulatedDevice):
- async def read_telemetry(self):
- data = await super().read_telemetry()
- data["air_c"] = 20.0
- return data
- class UnknownOffDevice(SimulatedDevice):
- simulated = False
- async def supply_set(self, on):
- if not on:
- return "unknown"
- return await super().supply_set(on)
- class SlowTargetDevice(SimulatedDevice):
- def __init__(self, config):
- super().__init__(config)
- self.target_calls = 0
- self.target_started = asyncio.Event()
- self.target_release = asyncio.Event()
- self.target_cancelled = False
- self.off_attempts = 0
- async def set_target(self, c):
- self.target_calls += 1
- if self.target_calls > 1:
- self.target_started.set()
- try:
- await self.target_release.wait()
- except asyncio.CancelledError:
- self.target_cancelled = True
- raise
- return await super().set_target(c)
- async def supply_set(self, on):
- if not on:
- self.off_attempts += 1
- return await super().supply_set(on)
- class ManualOffDevice(SimulatedDevice):
- simulated = False
- def __init__(self, config):
- super().__init__(config)
- self.supply = "on" # Operator has already confirmed the initial supply.
- self.tail_draining = asyncio.Event()
- self.allow_close = asyncio.Event()
- async def supply_set(self, on):
- if on:
- return "on"
- raise ManualActionRequired(False)
- async def confirm_supply(self, on):
- self.supply = "on" if on else "off"
- if not on:
- self.host = "off"
- await self._cancel_tasks()
- async def sol_close(self):
- self.tail_draining.set()
- await self.allow_close.wait()
- await super().sol_close()
- class EarlyCpu1Device(SimulatedDevice):
- """Both CPU prompts may be printed before CPU0's command round completes."""
- def __init__(self, config):
- super().__init__(config)
- self._cpu1_printed = False
- def _emit(self, text):
- if "[1][CxmtDdrTest]Current stage is 1" in text:
- if self._cpu1_printed:
- return
- self._cpu1_printed = True
- super()._emit(text)
- async def _boot(self):
- await super()._boot()
- self._emit("[1][CxmtDdrTest]Current stage is 1\r\n")
- class EngineTests(unittest.IsolatedAsyncioTestCase):
- async def asyncSetUp(self):
- self.tmp = tempfile.TemporaryDirectory()
- self.settings = load_settings(ROOT / "config/simulated.json")
- self.settings["data_dir"] = str(Path(self.tmp.name) / "data")
- self.settings["telemetry_interval_s"] = 0.03
- recipe = self.settings["recipes"][0]
- recipe.update(preheat_hold_s=0, preheat_timeout_s=4, phase_timeout_s=3, finish_timeout_s=1)
- for station in self.settings["stations"]:
- station["simulation"] = {"step_delay_s": 0.005, "mt_duration_s": 0.08}
- for step in self.settings["profiles"]["sim-cxmt"]["steps"]:
- step["interval_s"] = 0
- self.bench = None
- self.manual_devices = []
- async def asyncTearDown(self):
- for device in self.manual_devices:
- device.allow_close.set()
- if self.bench is not None:
- await asyncio.wait_for(self.bench.close(), 10)
- self.tmp.cleanup()
- async def make_bench(self, factory=None):
- self.bench = Bench(copy.deepcopy(self.settings))
- if factory:
- with patch("stl_backend.engine.create_device", factory):
- await self.bench.initialize()
- else:
- await self.bench.initialize()
- return self.bench
- def request(self, station="S1"):
- return {"command_id": "start-" + uuid.uuid4().hex, "operator": "test-operator",
- "station_id": station, "recipe_id": "DEMO-80", "work_order": "WO-test", "batch_no": "B-test",
- "dimms": [{"sn": station + "-SN", "slot": "A1", "cpu": 0, "channel": "A"}]}
- async def start(self, station="S1"):
- return await self.bench.start_run(self.request(station))
- async def until(self, condition, timeout=5):
- async with asyncio.timeout(timeout):
- while not condition():
- await asyncio.sleep(0.005)
- async def completed(self, command, timeout=6):
- rt = self.bench.station(command["station_id"])
- await asyncio.wait_for(asyncio.shield(rt.task), timeout)
- return await self.bench.store.get_run(command["run_id"])
- async def command_done(self, command_id):
- async with asyncio.timeout(5):
- while True:
- command = await self.bench.store.get_command(command_id)
- if command["state"] not in ("accepted", "running"):
- return command
- await asyncio.sleep(0.005)
- async def test_firmware_inventory_preserves_registered_sn_and_history_index(self):
- await self.make_bench(ColdDevice)
- request = self.request()
- # The old implementation treated this accepted literal SN as an
- # instruction to overwrite identity, but never updated the SN index.
- request["dimms"][0]["sn"] = "auto"
- command = await self.bench.start_run(request)
- rt = self.bench.station("S1")
- await self.until(lambda: rt.snapshot["phase"] == "preheating")
- await self.bench._parsed_event(rt, {
- "kind": "dimm_info", "message": "Firmware inventory", "severity": "info",
- "details": {"cpu": 0, "channel": 0, "dimm": 0, "serial": "FIRMWARE-OTHER-SN"},
- })
- await self.bench._save_run(rt.run)
- run = await self.bench.store.get_run(command["run_id"])
- self.assertEqual(run["dimms"][0]["sn"], "auto")
- indexed = await self.bench.store.list_runs({"sn": "auto"})
- self.assertEqual([item["run_id"] for item in indexed], [command["run_id"]])
- self.assertEqual(await self.bench.store.list_runs({"sn": "FIRMWARE-OTHER-SN"}), [])
- snapshot = await self.bench.snapshot("S1")
- self.assertEqual(snapshot["channels"][0]["sns"], ["auto"])
- events = await self.bench.store.list_events({"run_id": command["run_id"]})
- inventory = [event for event in events if event["kind"] == "dimm_info"]
- self.assertEqual(inventory[0]["details"]["serial"], "FIRMWARE-OTHER-SN")
- async def test_four_stations_independent_stop_during_preheat(self):
- await self.make_bench(lambda cfg: ColdDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
- commands = await asyncio.gather(*(self.start(f"S{i}") for i in range(1, 5)))
- await self.until(lambda: self.bench.station("S1").snapshot["phase"] == "preheating")
- stop = await self.bench.stop_run({"command_id": "stop-cold", "operator": "test-operator", "run_id": commands[0]["run_id"]})
- # This checks station isolation and outcomes, not host throughput.
- # Four workflows share SQLite/the event loop; their sequential phases
- # and capture drains legitimately exceed the single-run 6 s watchdog
- # on a contended host. Keep the device/phase deadlines unchanged.
- results = await asyncio.gather(*(self.completed(c, timeout=30) for c in commands))
- self.assertEqual(results[0]["state"], "stopped")
- self.assertEqual(results[0]["end_reason"], "operator_stopped")
- self.assertFalse(results[0]["evidence"]["preheat_met"])
- self.assertEqual((await self.command_done(stop["command_id"]))["state"], "succeeded")
- for command, result in zip(commands, results):
- self.assertEqual(result["run_id"], command["run_id"])
- self.assertEqual(result["station_id"], command["station_id"])
- self.assertEqual(result["supply_state"], "off")
- for result in results[1:]:
- self.assertEqual(result["state"], "completed")
- self.assertEqual(result["end_reason"], "completed")
- self.assertTrue(result["workflow_complete"])
- self.assertEqual(result["verdict"], "pending") # USB/result JSON still required.
- raw = (await self.bench.read_sol(result["run_id"]))["data"]
- self.assertIn(b"STL_SIM TEST_RESULT PASS", raw)
- self.assertEqual(self.bench.station("S1").device.sent_commands, [])
- async def test_workflow_phase_change_clears_previous_tool_progress(self):
- await self.make_bench()
- rt = self.bench.station("S1")
- await self.bench._phase(rt, "rmt")
- rt.snapshot.update(progress_percent=100, progress_phase="rmt", progress_observed_unix_ms=1234)
- await self.bench._phase(rt, "rmt")
- self.assertEqual((await self.bench.snapshot("S1"))["progress_percent"], 100)
- await self.bench._phase(rt, "mt")
- snapshot = await self.bench.snapshot("S1")
- self.assertNotIn("progress_percent", snapshot)
- self.assertEqual(snapshot["progress_phase"], "")
- self.assertEqual(snapshot["progress_observed_unix_ms"], 0)
- saved = (await self.bench.store.load_stations())["S1"]
- self.assertNotIn("progress_percent", saved)
- async def test_stage1_is_reset_for_each_run_and_each_cpu(self):
- # Overrides are now opt-in; this test explicitly exercises one.
- self.settings["recipes"][0]["stage1_commands"] = ["actm tCL 44"]
- await self.make_bench()
- run_ids = []
- for _ in range(2):
- command = await self.start()
- result = await self.completed(command)
- self.assertEqual(result["state"], "completed")
- run_ids.append(result["run_id"])
- raw = (await self.bench.read_sol(result["run_id"]))["data"]
- for cpu in (0, 1):
- token = f"[{cpu}][CxmtDdrTest]User input command is actm tCL 44".encode()
- self.assertEqual(raw.count(token), 1)
- self.assertNotEqual(run_ids[0], run_ids[1])
- async def test_fail_result_triggers_cutoff_and_preserves_fail(self):
- self.settings["stations"][0]["simulation"]["fail_mt"] = True
- await self.make_bench()
- request = self.request()
- # The same slot label on another CPU must not inherit CPU0's failure.
- request["dimms"].append({"sn": "S1-OTHER-CPU", "cpu": 1, "channel": "A", "slot": "A1"})
- result = await self.completed(await self.bench.start_run(request))
- self.assertEqual(result["verdict"], "fail")
- self.assertEqual(result["end_reason"], "test_failed")
- self.assertEqual(result["supply_state"], "off")
- self.assertGreater(result["error_count"], 0)
- self.assertEqual(await self.bench.station("S1").device.supply_read(), "off")
- snapshot = await self.bench.snapshot("S1")
- channels = {(c["cpu"], c["channel"]): c for c in snapshot["channels"]}
- self.assertEqual(channels[0, "0"]["state"], "fail")
- self.assertGreater(channels[0, "0"]["error_count"], 0)
- self.assertNotEqual(channels[1, "0"]["state"], "fail")
- events = await self.bench.store.list_events({"run_id": result["run_id"], "limit": 1000})
- attributed = [e for e in events if e.get("details", {}).get("test_failure") and e["details"].get("slot") == "A1"]
- self.assertTrue(attributed)
- for event in attributed:
- self.assertEqual(event["details"].get("sn"), "S1-SN")
- async def test_disabled_rmt_amt_are_skipped_in_execution_and_log(self):
- self.settings["recipes"][0].update(run_rmt=False, run_amt=False)
- await self.make_bench()
- result = await self.completed(await self.start())
- self.assertEqual(result["state"], "completed")
- self.assertEqual(result["tests"]["rmt"], "skipped_by_recipe")
- self.assertEqual(result["tests"]["amt"], "skipped_by_recipe")
- self.assertEqual(result["tests"]["mt"], "completed")
- raw = (await self.bench.read_sol(result["run_id"]))["data"]
- self.assertNotIn(b"STL_SIM RMT_START", raw)
- self.assertNotIn(b"STL_SIM AMT_START", raw)
- self.assertIn(b"STL_SIM TEST_START MT", raw)
- async def test_stale_stop_cannot_affect_next_run(self):
- await self.make_bench()
- previous = await self.completed(await self.start())
- command = await self.start()
- with self.assertRaises(BenchError) as caught:
- await self.bench.stop_run({"command_id": "stale-stop", "operator": "test-operator", "run_id": previous["run_id"]})
- self.assertEqual(caught.exception.code, "FAILED_PRECONDITION")
- current = await self.completed(command)
- self.assertEqual(current["state"], "completed")
- self.assertEqual(current["end_reason"], "completed")
- async def test_manual_mode_can_resume_while_automatic_sender_is_paused(self):
- # Delay CPU0 sending long enough to enter manual mode with a live SOL.
- self.settings["profiles"]["sim-cxmt"]["steps"][0]["initial_delay_s"] = 0.2
- await self.make_bench()
- command = await self.start()
- rt = self.bench.station("S1")
- await self.until(lambda: rt.snapshot["sol_state"] == "online")
- manual = await self.bench.set_sol_mode({"command_id": "mode-manual", "operator": "test-operator", "run_id": command["run_id"], "mode": "manual"})
- self.assertEqual((await self.command_done(manual["command_id"]))["state"], "succeeded")
- before = len(rt.device.sent_commands)
- await asyncio.sleep(0.3)
- self.assertEqual(len(rt.device.sent_commands), before)
- auto = await self.bench.set_sol_mode({"command_id": "mode-auto", "operator": "test-operator", "run_id": command["run_id"], "mode": "auto"})
- self.assertEqual((await self.command_done(auto["command_id"]))["state"], "succeeded")
- self.assertEqual((await self.completed(command))["state"], "completed")
- async def test_unknown_supply_off_keeps_station_reserved_for_reconciliation(self):
- await self.make_bench(lambda cfg: UnknownOffDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
- result = await self.completed(await self.start())
- self.assertEqual(result["supply_state"], "unknown")
- self.assertEqual(result["state"], "recovery_required")
- self.assertEqual(self.bench.station("S1").run["run_id"], result["run_id"])
- with self.assertRaises(BenchError):
- await self.start()
- async def test_manual_off_confirmation_during_tail_drain_is_not_overwritten(self):
- self.settings["stations"][0]["supply_mode"] = "manual"
- def factory(cfg):
- if cfg["station_id"] != "S1":
- return SimulatedDevice(cfg)
- device = ManualOffDevice(cfg)
- self.manual_devices.append(device)
- return device
- await self.make_bench(factory)
- command = await self.start()
- rt = self.bench.station("S1")
- device = rt.device
- await asyncio.wait_for(device.tail_draining.wait(), 5)
- self.assertIs(rt.pending_supply, False)
- confirmation = await self.bench.confirm_power({"command_id": "manual-off", "operator": "test-operator",
- "station_id": "S1", "expected_run_id": command["run_id"], "supply_on": False})
- self.assertEqual((await self.command_done(confirmation["command_id"]))["state"], "succeeded")
- device.allow_close.set()
- result = await self.completed(command)
- self.assertEqual(result["state"], "completed")
- self.assertEqual(result["supply_state"], "off")
- self.assertEqual(result["supply_confirmation"], "operator_confirmed")
- self.assertIsNone(rt.run)
- async def test_early_cpu1_stage_marker_is_not_lost_while_cpu0_is_configured(self):
- self.settings["recipes"][0]["stage1_commands"] = ["actm tCL 44"]
- await self.make_bench(lambda cfg: EarlyCpu1Device(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
- result = await self.completed(await self.start())
- self.assertEqual(result["state"], "completed", result["end_reason"])
- raw = (await self.bench.read_sol(result["run_id"]))["data"]
- self.assertEqual(raw.count(b"[1][CxmtDdrTest]Current stage is 1"), 1)
- self.assertIn(b"[1][CxmtDdrTest]User input command is actm tCL 44", raw)
- async def test_manual_off_confirmation_after_finalization_releases_station(self):
- self.settings["stations"][0]["supply_mode"] = "manual"
- def factory(cfg):
- if cfg["station_id"] != "S1":
- return SimulatedDevice(cfg)
- device = ManualOffDevice(cfg)
- device.allow_close.set()
- self.manual_devices.append(device)
- return device
- await self.make_bench(factory)
- command = await self.start()
- result = await self.completed(command)
- self.assertEqual(result["state"], "recovery_required")
- self.assertEqual(result["supply_state"], "unknown")
- with self.assertRaises(BenchError):
- await self.start()
- confirmation = await self.bench.confirm_power({"command_id": "late-manual-off", "operator": "test-operator",
- "station_id": "S1", "expected_run_id": command["run_id"], "supply_on": False})
- self.assertEqual((await self.command_done(confirmation["command_id"]))["state"], "succeeded")
- result = await self.bench.store.get_run(command["run_id"])
- self.assertEqual(result["state"], "completed")
- self.assertEqual(result["supply_state"], "off")
- self.assertEqual(result["supply_confirmation"], "operator_confirmed")
- self.assertIsNone(self.bench.station("S1").run)
- self.assertIsNone(self.bench.station("S1").pending_supply)
- async def test_stop_cancels_slow_target_write_and_still_attempts_supply_off(self):
- self.settings["stations"][0]["simulation"]["mt_duration_s"] = 10
- await self.make_bench(lambda cfg: SlowTargetDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
- command = await self.start()
- rt = self.bench.station("S1")
- await self.until(lambda: rt.snapshot["phase"] == "mt")
- target = await self.bench.set_target({"command_id": "slow-target", "operator": "test-operator",
- "run_id": command["run_id"], "target_c": 81.0})
- await asyncio.wait_for(rt.device.target_started.wait(), 1)
- try:
- stopped = await self.bench.stop_run({"command_id": "stop-slow-target", "operator": "test-operator",
- "run_id": command["run_id"]})
- result = await self.completed(command, timeout=3)
- self.assertEqual(result["state"], "stopped")
- self.assertEqual(result["supply_state"], "off")
- self.assertGreaterEqual(rt.device.off_attempts, 1)
- self.assertTrue(rt.device.target_cancelled)
- self.assertEqual((await self.command_done(stopped["command_id"]))["state"], "succeeded")
- finally:
- rt.device.target_release.set()
- await self.command_done(target["command_id"])
- async def test_process_crash_recovers_records_without_replaying_device_writes(self):
- # An actual killed process establishes that cleanup cannot manufacture a
- # completed run; the next process must retain an interrupted run.
- settings = copy.deepcopy(self.settings)
- settings["stations"][0]["simulation"]["mt_duration_s"] = 30
- path = Path(self.tmp.name) / "crash-settings.json"
- path.write_text(json.dumps(settings))
- request = self.request()
- script = '''import asyncio,json,sys
- from pathlib import Path
- from stl_backend.engine import Bench
- async def main():
- bench=Bench(json.loads(Path(sys.argv[1]).read_text()))
- await bench.initialize()
- command=await bench.start_run(json.loads(sys.argv[2]))
- while bench.station("S1").snapshot["phase"]!="mt": await asyncio.sleep(.005)
- print(json.dumps(command),flush=True)
- await asyncio.Event().wait()
- asyncio.run(main())
- '''
- env = os.environ.copy()
- env["PYTHONPATH"] = str(ROOT / "src")
- process = await asyncio.create_subprocess_exec(sys.executable, "-c", script, str(path), json.dumps(request),
- stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env)
- try:
- raw = await asyncio.wait_for(process.stdout.readline(), 6)
- if not raw:
- self.fail((await process.stderr.read()).decode())
- command = json.loads(raw)
- process.kill()
- await process.wait()
- finally:
- if process.returncode is None:
- process.kill()
- await process.wait()
- writes = []
- class WriteSpyDevice(SimulatedDevice):
- async def supply_set(self, on):
- writes.append(("supply", on))
- return await super().supply_set(on)
- async def bmc_power(self, action):
- writes.append(("bmc", action))
- return await super().bmc_power(action)
- async def sol_write(self, data):
- writes.append(("sol", data))
- return await super().sol_write(data)
- await self.make_bench(WriteSpyDevice)
- result = await self.bench.store.get_run(command["run_id"])
- self.assertEqual(result["state"], "recovery_required")
- self.assertEqual(result["supply_state"], "unknown")
- self.assertEqual(result["verdict"], "inconclusive")
- self.assertEqual(self.bench.station("S1").run["run_id"], command["run_id"])
- self.assertIsNone(self.bench.station("S1").task)
- await asyncio.sleep(0.05)
- self.assertEqual(writes, [])
- with self.assertRaises(BenchError):
- await self.start()
- if __name__ == "__main__":
- unittest.main()
|