test_command_queue.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """Shared queue, station dispatch and restart behavior; simulated devices only."""
  2. import asyncio
  3. import base64
  4. import sqlite3
  5. import tempfile
  6. import unittest
  7. import uuid
  8. from pathlib import Path
  9. from stl_backend.config import load_settings
  10. from stl_backend.devices.base import ManualActionRequired
  11. from stl_backend.devices.simulator import SimulatedDevice
  12. from stl_backend.engine import Bench
  13. from stl_backend.errors import BenchError
  14. from stl_backend.generated import bench_pb2 as pb
  15. from stl_backend.service import as_dict, message
  16. ROOT = Path(__file__).resolve().parents[1]
  17. TERMINAL = {"succeeded", "failed", "interrupted"}
  18. class QueueTests(unittest.IsolatedAsyncioTestCase):
  19. async def asyncSetUp(self):
  20. self.tmp = tempfile.TemporaryDirectory()
  21. self.settings = load_settings(ROOT / "config/simulated.json")
  22. self.settings["data_dir"] = self.tmp.name
  23. self.settings["telemetry_interval_s"] = 0.02
  24. for recipe in self.settings["recipes"]:
  25. recipe.update(preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=5, finish_timeout_s=2)
  26. for cfg in self.settings["stations"]:
  27. cfg["simulation"].update(step_delay_s=0.005, mt_duration_s=10)
  28. self.bench = Bench(self.settings)
  29. await self.bench.initialize()
  30. async def asyncTearDown(self):
  31. await asyncio.wait_for(self.bench.close(), 10)
  32. self.tmp.cleanup()
  33. def request(self, method, station="S1", **arguments):
  34. return {"command_id": "Q-" + uuid.uuid4().hex, "station_id": station,
  35. "operator": "queue-test", "method": method, "arguments": arguments}
  36. async def wait(self, condition):
  37. async with asyncio.timeout(4):
  38. while not condition():
  39. await asyncio.sleep(0.005)
  40. async def done(self, item):
  41. async with asyncio.timeout(5):
  42. while item["state"] not in TERMINAL:
  43. await asyncio.sleep(0.01)
  44. item = await self.bench.command_queue.storage.get(item["command_id"])
  45. return item
  46. async def send(self, method, station="S1", **arguments):
  47. return await self.done(await self.bench.enqueue_command(self.request(method, station, **arguments)))
  48. async def test_short_commands_serial_per_station_and_four_stations_parallel(self):
  49. entered, release = [], asyncio.Event()
  50. for station, rt in self.bench.runtimes.items():
  51. await rt.device.supply_set(True)
  52. original = rt.device.bmc_power
  53. async def controlled(action, station=station, original=original):
  54. entered.append((station, action))
  55. if action == "on":
  56. await release.wait()
  57. return await original(action)
  58. rt.device.bmc_power = controlled
  59. try:
  60. first = await self.bench.enqueue_command(self.request("StationPower", action="host_on"))
  61. second = await self.bench.enqueue_command(self.request("StationPower", action="host_off"))
  62. others = [await self.bench.enqueue_command(self.request("StationPower", station, action="host_on"))
  63. for station in ("S2", "S3", "S4")]
  64. await self.wait(lambda: len(entered) == 4)
  65. self.assertEqual(set(entered), {(s, "on") for s in ("S1", "S2", "S3", "S4")})
  66. self.assertEqual((await self.bench.command_queue.storage.get(second["command_id"]))["state"], "queued")
  67. release.set()
  68. for item in (first, second, *others):
  69. self.assertEqual((await self.done(item))["state"], "succeeded")
  70. self.assertEqual([action for station, action in entered if station == "S1"], ["on", "off"])
  71. finally:
  72. release.set()
  73. async def test_duplicate_input_and_two_ui_event_cursors(self):
  74. self.assertEqual((await self.send("StationPower", action="supply_on"))["state"], "succeeded")
  75. await self.send("SetDiagnosticSol", action="open")
  76. await self.send("StationPower", action="host_on")
  77. rt = self.bench.station("S1")
  78. await self.wait(lambda: rt.diagnostic.state["phase"] == "uip")
  79. request = self.request("WriteDiagnosticSol", session_id=rt.diagnostic.state["session_id"],
  80. data=base64.b64encode(b"help\r").decode())
  81. ui1, ui2 = await asyncio.gather(self.bench.enqueue_command(request), self.bench.enqueue_command(request))
  82. self.assertEqual(ui1["sequence"], ui2["sequence"])
  83. self.assertEqual((await self.done(ui1))["state"], "succeeded")
  84. self.assertEqual(rt.device.sent_commands, [b"help\r"])
  85. with self.assertRaises(BenchError) as caught:
  86. await self.bench.enqueue_command({**request, "arguments": {**request["arguments"], "data": "DQ=="}})
  87. self.assertEqual(caught.exception.code, "ALREADY_EXISTS")
  88. # Two independent consumers read the same sequence; one cannot drain it.
  89. first = await self.bench.read_event_queue(0, "S1", 1000)
  90. repeated = await self.bench.read_event_queue(0, "S1", 1000)
  91. self.assertEqual(first, repeated)
  92. self.assertTrue(any(e["payload"].get("source") == "bios_console" for e in first["events"]))
  93. cursor = first["next_after_sequence"]
  94. rt.device._emit("[0][AMEMDIAG #]")
  95. await self.wait(lambda: rt.diagnostic.state["phase"] == "amemdiag")
  96. async with asyncio.timeout(3):
  97. while True:
  98. next1 = await self.bench.read_event_queue(cursor, "S1", 1000)
  99. if any(e["phase"] == "amemdiag" for e in next1["events"]):
  100. break
  101. await asyncio.sleep(.005)
  102. next2 = await self.bench.read_event_queue(cursor, "S1", 1000)
  103. self.assertEqual(next1, next2)
  104. self.assertTrue(any(e["phase"] == "amemdiag" for e in next1["events"]))
  105. message(pb.EventPage, next1)
  106. message(pb.QueueSnapshot, await self.bench.get_queue("S1"))
  107. async def test_query_failure_is_visible_and_does_not_stop_dispatch(self):
  108. failed = await self.send("QueryBmc", query="info")
  109. self.assertEqual(failed["state"], "failed")
  110. self.assertEqual(failed["error_code"], "UNAVAILABLE")
  111. self.assertIn("未通电", failed["detail"])
  112. await self.send("StationPower", action="supply_on")
  113. result = await self.send("QueryBmc", query="info")
  114. self.assertEqual(result["state"], "succeeded")
  115. self.assertIn("SIMULATED", result["result"]["text"])
  116. async def test_start_and_stop_do_not_block_manual_power_confirmations(self):
  117. class ManualSim(SimulatedDevice):
  118. def __init__(self, config):
  119. super().__init__(config)
  120. self.confirmed = None
  121. self.off_requested = False
  122. self.close_waiting = asyncio.Event()
  123. self.release = asyncio.Event()
  124. async def supply_set(self, on):
  125. if self.confirmed is not on:
  126. if not on:
  127. self.off_requested = True
  128. raise ManualActionRequired(on)
  129. return await super().supply_set(on)
  130. async def confirm_supply(self, on):
  131. self.confirmed = on
  132. if not on:
  133. self.release.set()
  134. await super().supply_set(on)
  135. async def sol_close(self):
  136. if self.off_requested and not self.release.is_set():
  137. self.close_waiting.set()
  138. await self.release.wait()
  139. await super().sol_close()
  140. rt = self.bench.station("S1")
  141. rt.cfg["supply_mode"] = "manual"
  142. rt.device = ManualSim(rt.cfg)
  143. rt.diagnostic.device = rt.device
  144. try:
  145. start = await self.bench.enqueue_command(self.request("StartRun", recipe_id="DEMO-80",
  146. work_order="QUEUE-WO", batch_no="QUEUE-BATCH", dimms=[{"cpu":0,"channel":"0","slot":"A1","sn":"QUEUE-SN"}]))
  147. await self.wait(lambda: rt.pending_supply is True)
  148. self.assertEqual((await self.bench.command_queue.storage.get(start["command_id"]))["state"], "running")
  149. run_id = rt.run["run_id"]
  150. confirmed = await self.send("ConfirmPower", expected_run_id=run_id, supply_on=True)
  151. self.assertEqual(confirmed["state"], "succeeded", confirmed)
  152. stop = await self.bench.enqueue_command(self.request("StopRun", run_id=run_id, reason="queue test"))
  153. await asyncio.wait_for(rt.device.close_waiting.wait(), 4)
  154. self.assertEqual((await self.bench.command_queue.storage.get(stop["command_id"]))["state"], "running")
  155. confirmed = await self.send("ConfirmPower", expected_run_id=run_id, supply_on=False)
  156. self.assertEqual(confirmed["state"], "succeeded", confirmed)
  157. self.assertEqual((await self.done(stop))["state"], "succeeded")
  158. self.assertEqual(rt.snapshot["supply_state"], "off")
  159. self.assertIsNone(rt.run)
  160. finally:
  161. rt.device.release.set()
  162. async def test_struct_cpu_validated_before_run_creation_and_integral_floats_normalized(self):
  163. def queued_request(dimms):
  164. # Exercise the exact Struct conversion used by EnqueueCommand.
  165. return as_dict(message(pb.EnqueueCommandRequest, self.request("StartRun",
  166. recipe_id="DEMO-80", work_order="QUEUE-WO", batch_no="QUEUE-BATCH", dimms=dimms)))
  167. for cpu in (0.5, True):
  168. with self.subTest(cpu=cpu):
  169. request = queued_request([{"cpu": cpu, "channel": "0", "slot": "A1", "sn": "INVALID"}])
  170. failed = await self.done(await self.bench.enqueue_command(request))
  171. self.assertEqual(failed["state"], "failed")
  172. self.assertEqual(failed["error_code"], "INVALID_ARGUMENT")
  173. self.assertIn("CPU must be an integer", failed["detail"])
  174. self.assertEqual(await self.bench.store.list_runs({}), [])
  175. self.assertIsNone(self.bench.station("S1").run)
  176. request = queued_request([
  177. {"cpu": 0.0, "channel": "0", "slot": "A1", "sn": "CPU0"},
  178. {"cpu": 1.0, "channel": "0", "slot": "A1", "sn": "CPU1"},
  179. ])
  180. self.assertIs(type(request["arguments"]["dimms"][0]["cpu"]), float)
  181. await self.bench.enqueue_command(request)
  182. await self.wait(lambda: self.bench.station("S1").run is not None)
  183. run = await self.bench.store.get_run(self.bench.station("S1").run["run_id"])
  184. self.assertEqual([d["cpu"] for d in run["dimms"]], [0, 1])
  185. self.assertTrue(all(type(d["cpu"]) is int for d in run["dimms"]))
  186. self.assertEqual([d.cpu for d in message(pb.Run, run).dimms], [0, 1])
  187. async def test_old_database_and_pending_queue_restart_without_replay(self):
  188. recipe = await self.bench.store.get_recipe("DEMO-80")
  189. recipe["name"] = "existing user recipe"
  190. await self.bench.store.put_recipe(recipe, recipe["revision"])
  191. event = await self.bench.store.add_event({"run_id":"", "station_id":"S1", "kind":"legacy",
  192. "observed_unix_ms":1, "severity":"info", "phase":"idle", "message":"kept", "details":{}})
  193. await self.bench.close()
  194. # A pre-queue schema 1 database has neither of these new tables.
  195. db = sqlite3.connect(Path(self.tmp.name) / "bench.sqlite3")
  196. db.executescript("DROP TABLE command_queue; DROP TABLE event_queue;")
  197. db.close()
  198. self.bench = Bench(self.settings)
  199. normalized = self.request("StationPower", action="host_on")
  200. item = await self.bench.command_queue.storage.enqueue({**normalized, "state":"queued",
  201. "created_unix_ms":1, "updated_unix_ms":1, "detail":"", "run_id":"", "result":{}, "error_code":""}, "crash-seed")
  202. # The queue entry is durable, but no worker ever dispatched it.
  203. await self.bench.initialize()
  204. interrupted = await self.bench.command_queue.storage.get(item["command_id"])
  205. self.assertEqual(interrupted["state"], "interrupted")
  206. self.assertIn("not replayed", interrupted["detail"])
  207. self.assertEqual((await self.bench.store.get_recipe("DEMO-80"))["name"], "existing user recipe")
  208. self.assertEqual((await self.bench.store.list_events({}))[0]["event_id"], event["event_id"])
  209. self.assertEqual(self.bench.station("S1").device.host, "off")
  210. self.assertEqual(self.bench.station("S1").device.sent_commands, [])