test_engine.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. """Workflow integration tests: local simulated devices and durable SQLite only."""
  2. from __future__ import annotations
  3. import asyncio
  4. import copy
  5. import json
  6. import os
  7. from pathlib import Path
  8. import sys
  9. import tempfile
  10. import unittest
  11. from unittest.mock import patch
  12. import uuid
  13. from stl_backend.config import load_settings
  14. from stl_backend.devices import ManualActionRequired, SimulatedDevice
  15. from stl_backend.engine import Bench
  16. from stl_backend.errors import BenchError
  17. ROOT = Path(__file__).resolve().parents[1]
  18. class ColdDevice(SimulatedDevice):
  19. async def read_telemetry(self):
  20. data = await super().read_telemetry()
  21. data["air_c"] = 20.0
  22. return data
  23. class UnknownOffDevice(SimulatedDevice):
  24. simulated = False
  25. async def supply_set(self, on):
  26. if not on:
  27. return "unknown"
  28. return await super().supply_set(on)
  29. class SlowTargetDevice(SimulatedDevice):
  30. def __init__(self, config):
  31. super().__init__(config)
  32. self.target_calls = 0
  33. self.target_started = asyncio.Event()
  34. self.target_release = asyncio.Event()
  35. self.target_cancelled = False
  36. self.off_attempts = 0
  37. async def set_target(self, c):
  38. self.target_calls += 1
  39. if self.target_calls > 1:
  40. self.target_started.set()
  41. try:
  42. await self.target_release.wait()
  43. except asyncio.CancelledError:
  44. self.target_cancelled = True
  45. raise
  46. return await super().set_target(c)
  47. async def supply_set(self, on):
  48. if not on:
  49. self.off_attempts += 1
  50. return await super().supply_set(on)
  51. class ManualOffDevice(SimulatedDevice):
  52. simulated = False
  53. def __init__(self, config):
  54. super().__init__(config)
  55. self.supply = "on" # Operator has already confirmed the initial supply.
  56. self.tail_draining = asyncio.Event()
  57. self.allow_close = asyncio.Event()
  58. async def supply_set(self, on):
  59. if on:
  60. return "on"
  61. raise ManualActionRequired(False)
  62. async def confirm_supply(self, on):
  63. self.supply = "on" if on else "off"
  64. if not on:
  65. self.host = "off"
  66. await self._cancel_tasks()
  67. async def sol_close(self):
  68. self.tail_draining.set()
  69. await self.allow_close.wait()
  70. await super().sol_close()
  71. class EarlyCpu1Device(SimulatedDevice):
  72. """Both CPU prompts may be printed before CPU0's command round completes."""
  73. def __init__(self, config):
  74. super().__init__(config)
  75. self._cpu1_printed = False
  76. def _emit(self, text):
  77. if "[1][CxmtDdrTest]Current stage is 1" in text:
  78. if self._cpu1_printed:
  79. return
  80. self._cpu1_printed = True
  81. super()._emit(text)
  82. async def _boot(self):
  83. await super()._boot()
  84. self._emit("[1][CxmtDdrTest]Current stage is 1\r\n")
  85. class EngineTests(unittest.IsolatedAsyncioTestCase):
  86. async def asyncSetUp(self):
  87. self.tmp = tempfile.TemporaryDirectory()
  88. self.settings = load_settings(ROOT / "config/simulated.json")
  89. self.settings["data_dir"] = str(Path(self.tmp.name) / "data")
  90. self.settings["telemetry_interval_s"] = 0.03
  91. recipe = self.settings["recipes"][0]
  92. recipe.update(preheat_hold_s=0, preheat_timeout_s=4, phase_timeout_s=3, finish_timeout_s=1)
  93. for station in self.settings["stations"]:
  94. station["simulation"] = {"step_delay_s": 0.005, "mt_duration_s": 0.08}
  95. for step in self.settings["profiles"]["sim-cxmt"]["steps"]:
  96. step["interval_s"] = 0
  97. self.bench = None
  98. self.manual_devices = []
  99. async def asyncTearDown(self):
  100. for device in self.manual_devices:
  101. device.allow_close.set()
  102. if self.bench is not None:
  103. await asyncio.wait_for(self.bench.close(), 10)
  104. self.tmp.cleanup()
  105. async def make_bench(self, factory=None):
  106. self.bench = Bench(copy.deepcopy(self.settings))
  107. if factory:
  108. with patch("stl_backend.engine.create_device", factory):
  109. await self.bench.initialize()
  110. else:
  111. await self.bench.initialize()
  112. return self.bench
  113. def request(self, station="S1"):
  114. return {"command_id": "start-" + uuid.uuid4().hex, "operator": "test-operator",
  115. "station_id": station, "recipe_id": "DEMO-80", "work_order": "WO-test", "batch_no": "B-test",
  116. "dimms": [{"sn": station + "-SN", "slot": "A1", "cpu": 0, "channel": "A"}]}
  117. async def start(self, station="S1"):
  118. return await self.bench.start_run(self.request(station))
  119. async def until(self, condition, timeout=5):
  120. async with asyncio.timeout(timeout):
  121. while not condition():
  122. await asyncio.sleep(0.005)
  123. async def completed(self, command, timeout=6):
  124. rt = self.bench.station(command["station_id"])
  125. await asyncio.wait_for(asyncio.shield(rt.task), timeout)
  126. return await self.bench.store.get_run(command["run_id"])
  127. async def command_done(self, command_id):
  128. async with asyncio.timeout(5):
  129. while True:
  130. command = await self.bench.store.get_command(command_id)
  131. if command["state"] not in ("accepted", "running"):
  132. return command
  133. await asyncio.sleep(0.005)
  134. async def test_firmware_inventory_preserves_registered_sn_and_history_index(self):
  135. await self.make_bench(ColdDevice)
  136. request = self.request()
  137. # The old implementation treated this accepted literal SN as an
  138. # instruction to overwrite identity, but never updated the SN index.
  139. request["dimms"][0]["sn"] = "auto"
  140. command = await self.bench.start_run(request)
  141. rt = self.bench.station("S1")
  142. await self.until(lambda: rt.snapshot["phase"] == "preheating")
  143. await self.bench._parsed_event(rt, {
  144. "kind": "dimm_info", "message": "Firmware inventory", "severity": "info",
  145. "details": {"cpu": 0, "channel": 0, "dimm": 0, "serial": "FIRMWARE-OTHER-SN"},
  146. })
  147. await self.bench._save_run(rt.run)
  148. run = await self.bench.store.get_run(command["run_id"])
  149. self.assertEqual(run["dimms"][0]["sn"], "auto")
  150. indexed = await self.bench.store.list_runs({"sn": "auto"})
  151. self.assertEqual([item["run_id"] for item in indexed], [command["run_id"]])
  152. self.assertEqual(await self.bench.store.list_runs({"sn": "FIRMWARE-OTHER-SN"}), [])
  153. snapshot = await self.bench.snapshot("S1")
  154. self.assertEqual(snapshot["channels"][0]["sns"], ["auto"])
  155. events = await self.bench.store.list_events({"run_id": command["run_id"]})
  156. inventory = [event for event in events if event["kind"] == "dimm_info"]
  157. self.assertEqual(inventory[0]["details"]["serial"], "FIRMWARE-OTHER-SN")
  158. async def test_four_stations_independent_stop_during_preheat(self):
  159. await self.make_bench(lambda cfg: ColdDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
  160. commands = await asyncio.gather(*(self.start(f"S{i}") for i in range(1, 5)))
  161. await self.until(lambda: self.bench.station("S1").snapshot["phase"] == "preheating")
  162. stop = await self.bench.stop_run({"command_id": "stop-cold", "operator": "test-operator", "run_id": commands[0]["run_id"]})
  163. # This checks station isolation and outcomes, not host throughput.
  164. # Four workflows share SQLite/the event loop; their sequential phases
  165. # and capture drains legitimately exceed the single-run 6 s watchdog
  166. # on a contended host. Keep the device/phase deadlines unchanged.
  167. results = await asyncio.gather(*(self.completed(c, timeout=30) for c in commands))
  168. self.assertEqual(results[0]["state"], "stopped")
  169. self.assertEqual(results[0]["end_reason"], "operator_stopped")
  170. self.assertFalse(results[0]["evidence"]["preheat_met"])
  171. self.assertEqual((await self.command_done(stop["command_id"]))["state"], "succeeded")
  172. for command, result in zip(commands, results):
  173. self.assertEqual(result["run_id"], command["run_id"])
  174. self.assertEqual(result["station_id"], command["station_id"])
  175. self.assertEqual(result["supply_state"], "off")
  176. for result in results[1:]:
  177. self.assertEqual(result["state"], "completed")
  178. self.assertEqual(result["end_reason"], "completed")
  179. self.assertTrue(result["workflow_complete"])
  180. self.assertEqual(result["verdict"], "pending") # USB/result JSON still required.
  181. raw = (await self.bench.read_sol(result["run_id"]))["data"]
  182. self.assertIn(b"STL_SIM TEST_RESULT PASS", raw)
  183. self.assertEqual(self.bench.station("S1").device.sent_commands, [])
  184. async def test_workflow_phase_change_clears_previous_tool_progress(self):
  185. await self.make_bench()
  186. rt = self.bench.station("S1")
  187. await self.bench._phase(rt, "rmt")
  188. rt.snapshot.update(progress_percent=100, progress_phase="rmt", progress_observed_unix_ms=1234)
  189. await self.bench._phase(rt, "rmt")
  190. self.assertEqual((await self.bench.snapshot("S1"))["progress_percent"], 100)
  191. await self.bench._phase(rt, "mt")
  192. snapshot = await self.bench.snapshot("S1")
  193. self.assertNotIn("progress_percent", snapshot)
  194. self.assertEqual(snapshot["progress_phase"], "")
  195. self.assertEqual(snapshot["progress_observed_unix_ms"], 0)
  196. saved = (await self.bench.store.load_stations())["S1"]
  197. self.assertNotIn("progress_percent", saved)
  198. async def test_stage1_is_reset_for_each_run_and_each_cpu(self):
  199. # Overrides are now opt-in; this test explicitly exercises one.
  200. self.settings["recipes"][0]["stage1_commands"] = ["actm tCL 44"]
  201. await self.make_bench()
  202. run_ids = []
  203. for _ in range(2):
  204. command = await self.start()
  205. result = await self.completed(command)
  206. self.assertEqual(result["state"], "completed")
  207. run_ids.append(result["run_id"])
  208. raw = (await self.bench.read_sol(result["run_id"]))["data"]
  209. for cpu in (0, 1):
  210. token = f"[{cpu}][CxmtDdrTest]User input command is actm tCL 44".encode()
  211. self.assertEqual(raw.count(token), 1)
  212. self.assertNotEqual(run_ids[0], run_ids[1])
  213. async def test_fail_result_triggers_cutoff_and_preserves_fail(self):
  214. self.settings["stations"][0]["simulation"]["fail_mt"] = True
  215. await self.make_bench()
  216. request = self.request()
  217. # The same slot label on another CPU must not inherit CPU0's failure.
  218. request["dimms"].append({"sn": "S1-OTHER-CPU", "cpu": 1, "channel": "A", "slot": "A1"})
  219. result = await self.completed(await self.bench.start_run(request))
  220. self.assertEqual(result["verdict"], "fail")
  221. self.assertEqual(result["end_reason"], "test_failed")
  222. self.assertEqual(result["supply_state"], "off")
  223. self.assertGreater(result["error_count"], 0)
  224. self.assertEqual(await self.bench.station("S1").device.supply_read(), "off")
  225. snapshot = await self.bench.snapshot("S1")
  226. channels = {(c["cpu"], c["channel"]): c for c in snapshot["channels"]}
  227. self.assertEqual(channels[0, "0"]["state"], "fail")
  228. self.assertGreater(channels[0, "0"]["error_count"], 0)
  229. self.assertNotEqual(channels[1, "0"]["state"], "fail")
  230. events = await self.bench.store.list_events({"run_id": result["run_id"], "limit": 1000})
  231. attributed = [e for e in events if e.get("details", {}).get("test_failure") and e["details"].get("slot") == "A1"]
  232. self.assertTrue(attributed)
  233. for event in attributed:
  234. self.assertEqual(event["details"].get("sn"), "S1-SN")
  235. async def test_disabled_rmt_amt_are_skipped_in_execution_and_log(self):
  236. self.settings["recipes"][0].update(run_rmt=False, run_amt=False)
  237. await self.make_bench()
  238. result = await self.completed(await self.start())
  239. self.assertEqual(result["state"], "completed")
  240. self.assertEqual(result["tests"]["rmt"], "skipped_by_recipe")
  241. self.assertEqual(result["tests"]["amt"], "skipped_by_recipe")
  242. self.assertEqual(result["tests"]["mt"], "completed")
  243. raw = (await self.bench.read_sol(result["run_id"]))["data"]
  244. self.assertNotIn(b"STL_SIM RMT_START", raw)
  245. self.assertNotIn(b"STL_SIM AMT_START", raw)
  246. self.assertIn(b"STL_SIM TEST_START MT", raw)
  247. async def test_stale_stop_cannot_affect_next_run(self):
  248. await self.make_bench()
  249. previous = await self.completed(await self.start())
  250. command = await self.start()
  251. with self.assertRaises(BenchError) as caught:
  252. await self.bench.stop_run({"command_id": "stale-stop", "operator": "test-operator", "run_id": previous["run_id"]})
  253. self.assertEqual(caught.exception.code, "FAILED_PRECONDITION")
  254. current = await self.completed(command)
  255. self.assertEqual(current["state"], "completed")
  256. self.assertEqual(current["end_reason"], "completed")
  257. async def test_manual_mode_can_resume_while_automatic_sender_is_paused(self):
  258. # Delay CPU0 sending long enough to enter manual mode with a live SOL.
  259. self.settings["profiles"]["sim-cxmt"]["steps"][0]["initial_delay_s"] = 0.2
  260. await self.make_bench()
  261. command = await self.start()
  262. rt = self.bench.station("S1")
  263. await self.until(lambda: rt.snapshot["sol_state"] == "online")
  264. manual = await self.bench.set_sol_mode({"command_id": "mode-manual", "operator": "test-operator", "run_id": command["run_id"], "mode": "manual"})
  265. self.assertEqual((await self.command_done(manual["command_id"]))["state"], "succeeded")
  266. before = len(rt.device.sent_commands)
  267. await asyncio.sleep(0.3)
  268. self.assertEqual(len(rt.device.sent_commands), before)
  269. auto = await self.bench.set_sol_mode({"command_id": "mode-auto", "operator": "test-operator", "run_id": command["run_id"], "mode": "auto"})
  270. self.assertEqual((await self.command_done(auto["command_id"]))["state"], "succeeded")
  271. self.assertEqual((await self.completed(command))["state"], "completed")
  272. async def test_unknown_supply_off_keeps_station_reserved_for_reconciliation(self):
  273. await self.make_bench(lambda cfg: UnknownOffDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
  274. result = await self.completed(await self.start())
  275. self.assertEqual(result["supply_state"], "unknown")
  276. self.assertEqual(result["state"], "recovery_required")
  277. self.assertEqual(self.bench.station("S1").run["run_id"], result["run_id"])
  278. with self.assertRaises(BenchError):
  279. await self.start()
  280. async def test_manual_off_confirmation_during_tail_drain_is_not_overwritten(self):
  281. self.settings["stations"][0]["supply_mode"] = "manual"
  282. def factory(cfg):
  283. if cfg["station_id"] != "S1":
  284. return SimulatedDevice(cfg)
  285. device = ManualOffDevice(cfg)
  286. self.manual_devices.append(device)
  287. return device
  288. await self.make_bench(factory)
  289. command = await self.start()
  290. rt = self.bench.station("S1")
  291. device = rt.device
  292. await asyncio.wait_for(device.tail_draining.wait(), 5)
  293. self.assertIs(rt.pending_supply, False)
  294. confirmation = await self.bench.confirm_power({"command_id": "manual-off", "operator": "test-operator",
  295. "station_id": "S1", "expected_run_id": command["run_id"], "supply_on": False})
  296. self.assertEqual((await self.command_done(confirmation["command_id"]))["state"], "succeeded")
  297. device.allow_close.set()
  298. result = await self.completed(command)
  299. self.assertEqual(result["state"], "completed")
  300. self.assertEqual(result["supply_state"], "off")
  301. self.assertEqual(result["supply_confirmation"], "operator_confirmed")
  302. self.assertIsNone(rt.run)
  303. async def test_early_cpu1_stage_marker_is_not_lost_while_cpu0_is_configured(self):
  304. self.settings["recipes"][0]["stage1_commands"] = ["actm tCL 44"]
  305. await self.make_bench(lambda cfg: EarlyCpu1Device(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
  306. result = await self.completed(await self.start())
  307. self.assertEqual(result["state"], "completed", result["end_reason"])
  308. raw = (await self.bench.read_sol(result["run_id"]))["data"]
  309. self.assertEqual(raw.count(b"[1][CxmtDdrTest]Current stage is 1"), 1)
  310. self.assertIn(b"[1][CxmtDdrTest]User input command is actm tCL 44", raw)
  311. async def test_manual_off_confirmation_after_finalization_releases_station(self):
  312. self.settings["stations"][0]["supply_mode"] = "manual"
  313. def factory(cfg):
  314. if cfg["station_id"] != "S1":
  315. return SimulatedDevice(cfg)
  316. device = ManualOffDevice(cfg)
  317. device.allow_close.set()
  318. self.manual_devices.append(device)
  319. return device
  320. await self.make_bench(factory)
  321. command = await self.start()
  322. result = await self.completed(command)
  323. self.assertEqual(result["state"], "recovery_required")
  324. self.assertEqual(result["supply_state"], "unknown")
  325. with self.assertRaises(BenchError):
  326. await self.start()
  327. confirmation = await self.bench.confirm_power({"command_id": "late-manual-off", "operator": "test-operator",
  328. "station_id": "S1", "expected_run_id": command["run_id"], "supply_on": False})
  329. self.assertEqual((await self.command_done(confirmation["command_id"]))["state"], "succeeded")
  330. result = await self.bench.store.get_run(command["run_id"])
  331. self.assertEqual(result["state"], "completed")
  332. self.assertEqual(result["supply_state"], "off")
  333. self.assertEqual(result["supply_confirmation"], "operator_confirmed")
  334. self.assertIsNone(self.bench.station("S1").run)
  335. self.assertIsNone(self.bench.station("S1").pending_supply)
  336. async def test_stop_cancels_slow_target_write_and_still_attempts_supply_off(self):
  337. self.settings["stations"][0]["simulation"]["mt_duration_s"] = 10
  338. await self.make_bench(lambda cfg: SlowTargetDevice(cfg) if cfg["station_id"] == "S1" else SimulatedDevice(cfg))
  339. command = await self.start()
  340. rt = self.bench.station("S1")
  341. await self.until(lambda: rt.snapshot["phase"] == "mt")
  342. target = await self.bench.set_target({"command_id": "slow-target", "operator": "test-operator",
  343. "run_id": command["run_id"], "target_c": 81.0})
  344. await asyncio.wait_for(rt.device.target_started.wait(), 1)
  345. try:
  346. stopped = await self.bench.stop_run({"command_id": "stop-slow-target", "operator": "test-operator",
  347. "run_id": command["run_id"]})
  348. result = await self.completed(command, timeout=3)
  349. self.assertEqual(result["state"], "stopped")
  350. self.assertEqual(result["supply_state"], "off")
  351. self.assertGreaterEqual(rt.device.off_attempts, 1)
  352. self.assertTrue(rt.device.target_cancelled)
  353. self.assertEqual((await self.command_done(stopped["command_id"]))["state"], "succeeded")
  354. finally:
  355. rt.device.target_release.set()
  356. await self.command_done(target["command_id"])
  357. async def test_process_crash_recovers_records_without_replaying_device_writes(self):
  358. # An actual killed process establishes that cleanup cannot manufacture a
  359. # completed run; the next process must retain an interrupted run.
  360. settings = copy.deepcopy(self.settings)
  361. settings["stations"][0]["simulation"]["mt_duration_s"] = 30
  362. path = Path(self.tmp.name) / "crash-settings.json"
  363. path.write_text(json.dumps(settings))
  364. request = self.request()
  365. script = '''import asyncio,json,sys
  366. from pathlib import Path
  367. from stl_backend.engine import Bench
  368. async def main():
  369. bench=Bench(json.loads(Path(sys.argv[1]).read_text()))
  370. await bench.initialize()
  371. command=await bench.start_run(json.loads(sys.argv[2]))
  372. while bench.station("S1").snapshot["phase"]!="mt": await asyncio.sleep(.005)
  373. print(json.dumps(command),flush=True)
  374. await asyncio.Event().wait()
  375. asyncio.run(main())
  376. '''
  377. env = os.environ.copy()
  378. env["PYTHONPATH"] = str(ROOT / "src")
  379. process = await asyncio.create_subprocess_exec(sys.executable, "-c", script, str(path), json.dumps(request),
  380. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env)
  381. try:
  382. raw = await asyncio.wait_for(process.stdout.readline(), 6)
  383. if not raw:
  384. self.fail((await process.stderr.read()).decode())
  385. command = json.loads(raw)
  386. process.kill()
  387. await process.wait()
  388. finally:
  389. if process.returncode is None:
  390. process.kill()
  391. await process.wait()
  392. writes = []
  393. class WriteSpyDevice(SimulatedDevice):
  394. async def supply_set(self, on):
  395. writes.append(("supply", on))
  396. return await super().supply_set(on)
  397. async def bmc_power(self, action):
  398. writes.append(("bmc", action))
  399. return await super().bmc_power(action)
  400. async def sol_write(self, data):
  401. writes.append(("sol", data))
  402. return await super().sol_write(data)
  403. await self.make_bench(WriteSpyDevice)
  404. result = await self.bench.store.get_run(command["run_id"])
  405. self.assertEqual(result["state"], "recovery_required")
  406. self.assertEqual(result["supply_state"], "unknown")
  407. self.assertEqual(result["verdict"], "inconclusive")
  408. self.assertEqual(self.bench.station("S1").run["run_id"], command["run_id"])
  409. self.assertIsNone(self.bench.station("S1").task)
  410. await asyncio.sleep(0.05)
  411. self.assertEqual(writes, [])
  412. with self.assertRaises(BenchError):
  413. await self.start()
  414. if __name__ == "__main__":
  415. unittest.main()