"""Shared queue, station dispatch and restart behavior; simulated devices only.""" import asyncio import base64 import sqlite3 import tempfile import unittest import uuid from pathlib import Path from stl_backend.config import load_settings from stl_backend.devices.base import ManualActionRequired from stl_backend.devices.simulator import SimulatedDevice from stl_backend.engine import Bench from stl_backend.errors import BenchError from stl_backend.generated import bench_pb2 as pb from stl_backend.service import as_dict, message ROOT = Path(__file__).resolve().parents[1] TERMINAL = {"succeeded", "failed", "interrupted"} class QueueTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.tmp = tempfile.TemporaryDirectory() self.settings = load_settings(ROOT / "config/simulated.json") self.settings["data_dir"] = self.tmp.name self.settings["telemetry_interval_s"] = 0.02 for recipe in self.settings["recipes"]: recipe.update(preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=5, finish_timeout_s=2) for cfg in self.settings["stations"]: cfg["simulation"].update(step_delay_s=0.005, mt_duration_s=10) self.bench = Bench(self.settings) await self.bench.initialize() async def asyncTearDown(self): await asyncio.wait_for(self.bench.close(), 10) self.tmp.cleanup() def request(self, method, station="S1", **arguments): return {"command_id": "Q-" + uuid.uuid4().hex, "station_id": station, "operator": "queue-test", "method": method, "arguments": arguments} async def wait(self, condition): async with asyncio.timeout(4): while not condition(): await asyncio.sleep(0.005) async def done(self, item): async with asyncio.timeout(5): while item["state"] not in TERMINAL: await asyncio.sleep(0.01) item = await self.bench.command_queue.storage.get(item["command_id"]) return item async def send(self, method, station="S1", **arguments): return await self.done(await self.bench.enqueue_command(self.request(method, station, **arguments))) async def test_short_commands_serial_per_station_and_four_stations_parallel(self): entered, release = [], asyncio.Event() for station, rt in self.bench.runtimes.items(): await rt.device.supply_set(True) original = rt.device.bmc_power async def controlled(action, station=station, original=original): entered.append((station, action)) if action == "on": await release.wait() return await original(action) rt.device.bmc_power = controlled try: first = await self.bench.enqueue_command(self.request("StationPower", action="host_on")) second = await self.bench.enqueue_command(self.request("StationPower", action="host_off")) others = [await self.bench.enqueue_command(self.request("StationPower", station, action="host_on")) for station in ("S2", "S3", "S4")] await self.wait(lambda: len(entered) == 4) self.assertEqual(set(entered), {(s, "on") for s in ("S1", "S2", "S3", "S4")}) self.assertEqual((await self.bench.command_queue.storage.get(second["command_id"]))["state"], "queued") release.set() for item in (first, second, *others): self.assertEqual((await self.done(item))["state"], "succeeded") self.assertEqual([action for station, action in entered if station == "S1"], ["on", "off"]) finally: release.set() async def test_duplicate_input_and_two_ui_event_cursors(self): self.assertEqual((await self.send("StationPower", action="supply_on"))["state"], "succeeded") await self.send("SetDiagnosticSol", action="open") await self.send("StationPower", action="host_on") rt = self.bench.station("S1") await self.wait(lambda: rt.diagnostic.state["phase"] == "uip") request = self.request("WriteDiagnosticSol", session_id=rt.diagnostic.state["session_id"], data=base64.b64encode(b"help\r").decode()) ui1, ui2 = await asyncio.gather(self.bench.enqueue_command(request), self.bench.enqueue_command(request)) self.assertEqual(ui1["sequence"], ui2["sequence"]) self.assertEqual((await self.done(ui1))["state"], "succeeded") self.assertEqual(rt.device.sent_commands, [b"help\r"]) with self.assertRaises(BenchError) as caught: await self.bench.enqueue_command({**request, "arguments": {**request["arguments"], "data": "DQ=="}}) self.assertEqual(caught.exception.code, "ALREADY_EXISTS") # Two independent consumers read the same sequence; one cannot drain it. first = await self.bench.read_event_queue(0, "S1", 1000) repeated = await self.bench.read_event_queue(0, "S1", 1000) self.assertEqual(first, repeated) self.assertTrue(any(e["payload"].get("source") == "bios_console" for e in first["events"])) cursor = first["next_after_sequence"] rt.device._emit("[0][AMEMDIAG #]") await self.wait(lambda: rt.diagnostic.state["phase"] == "amemdiag") async with asyncio.timeout(3): while True: next1 = await self.bench.read_event_queue(cursor, "S1", 1000) if any(e["phase"] == "amemdiag" for e in next1["events"]): break await asyncio.sleep(.005) next2 = await self.bench.read_event_queue(cursor, "S1", 1000) self.assertEqual(next1, next2) self.assertTrue(any(e["phase"] == "amemdiag" for e in next1["events"])) message(pb.EventPage, next1) message(pb.QueueSnapshot, await self.bench.get_queue("S1")) async def test_query_failure_is_visible_and_does_not_stop_dispatch(self): failed = await self.send("QueryBmc", query="info") self.assertEqual(failed["state"], "failed") self.assertEqual(failed["error_code"], "UNAVAILABLE") self.assertIn("未通电", failed["detail"]) await self.send("StationPower", action="supply_on") result = await self.send("QueryBmc", query="info") self.assertEqual(result["state"], "succeeded") self.assertIn("SIMULATED", result["result"]["text"]) async def test_start_and_stop_do_not_block_manual_power_confirmations(self): class ManualSim(SimulatedDevice): def __init__(self, config): super().__init__(config) self.confirmed = None self.off_requested = False self.close_waiting = asyncio.Event() self.release = asyncio.Event() async def supply_set(self, on): if self.confirmed is not on: if not on: self.off_requested = True raise ManualActionRequired(on) return await super().supply_set(on) async def confirm_supply(self, on): self.confirmed = on if not on: self.release.set() await super().supply_set(on) async def sol_close(self): if self.off_requested and not self.release.is_set(): self.close_waiting.set() await self.release.wait() await super().sol_close() rt = self.bench.station("S1") rt.cfg["supply_mode"] = "manual" rt.device = ManualSim(rt.cfg) rt.diagnostic.device = rt.device try: start = await self.bench.enqueue_command(self.request("StartRun", recipe_id="DEMO-80", work_order="QUEUE-WO", batch_no="QUEUE-BATCH", dimms=[{"cpu":0,"channel":"0","slot":"A1","sn":"QUEUE-SN"}])) await self.wait(lambda: rt.pending_supply is True) self.assertEqual((await self.bench.command_queue.storage.get(start["command_id"]))["state"], "running") run_id = rt.run["run_id"] confirmed = await self.send("ConfirmPower", expected_run_id=run_id, supply_on=True) self.assertEqual(confirmed["state"], "succeeded", confirmed) stop = await self.bench.enqueue_command(self.request("StopRun", run_id=run_id, reason="queue test")) await asyncio.wait_for(rt.device.close_waiting.wait(), 4) self.assertEqual((await self.bench.command_queue.storage.get(stop["command_id"]))["state"], "running") confirmed = await self.send("ConfirmPower", expected_run_id=run_id, supply_on=False) self.assertEqual(confirmed["state"], "succeeded", confirmed) self.assertEqual((await self.done(stop))["state"], "succeeded") self.assertEqual(rt.snapshot["supply_state"], "off") self.assertIsNone(rt.run) finally: rt.device.release.set() async def test_struct_cpu_validated_before_run_creation_and_integral_floats_normalized(self): def queued_request(dimms): # Exercise the exact Struct conversion used by EnqueueCommand. return as_dict(message(pb.EnqueueCommandRequest, self.request("StartRun", recipe_id="DEMO-80", work_order="QUEUE-WO", batch_no="QUEUE-BATCH", dimms=dimms))) for cpu in (0.5, True): with self.subTest(cpu=cpu): request = queued_request([{"cpu": cpu, "channel": "0", "slot": "A1", "sn": "INVALID"}]) failed = await self.done(await self.bench.enqueue_command(request)) self.assertEqual(failed["state"], "failed") self.assertEqual(failed["error_code"], "INVALID_ARGUMENT") self.assertIn("CPU must be an integer", failed["detail"]) self.assertEqual(await self.bench.store.list_runs({}), []) self.assertIsNone(self.bench.station("S1").run) request = queued_request([ {"cpu": 0.0, "channel": "0", "slot": "A1", "sn": "CPU0"}, {"cpu": 1.0, "channel": "0", "slot": "A1", "sn": "CPU1"}, ]) self.assertIs(type(request["arguments"]["dimms"][0]["cpu"]), float) await self.bench.enqueue_command(request) await self.wait(lambda: self.bench.station("S1").run is not None) run = await self.bench.store.get_run(self.bench.station("S1").run["run_id"]) self.assertEqual([d["cpu"] for d in run["dimms"]], [0, 1]) self.assertTrue(all(type(d["cpu"]) is int for d in run["dimms"])) self.assertEqual([d.cpu for d in message(pb.Run, run).dimms], [0, 1]) async def test_old_database_and_pending_queue_restart_without_replay(self): recipe = await self.bench.store.get_recipe("DEMO-80") recipe["name"] = "existing user recipe" await self.bench.store.put_recipe(recipe, recipe["revision"]) event = await self.bench.store.add_event({"run_id":"", "station_id":"S1", "kind":"legacy", "observed_unix_ms":1, "severity":"info", "phase":"idle", "message":"kept", "details":{}}) await self.bench.close() # A pre-queue schema 1 database has neither of these new tables. db = sqlite3.connect(Path(self.tmp.name) / "bench.sqlite3") db.executescript("DROP TABLE command_queue; DROP TABLE event_queue;") db.close() self.bench = Bench(self.settings) normalized = self.request("StationPower", action="host_on") item = await self.bench.command_queue.storage.enqueue({**normalized, "state":"queued", "created_unix_ms":1, "updated_unix_ms":1, "detail":"", "run_id":"", "result":{}, "error_code":""}, "crash-seed") # The queue entry is durable, but no worker ever dispatched it. await self.bench.initialize() interrupted = await self.bench.command_queue.storage.get(item["command_id"]) self.assertEqual(interrupted["state"], "interrupted") self.assertIn("not replayed", interrupted["detail"]) self.assertEqual((await self.bench.store.get_recipe("DEMO-80"))["name"], "existing user recipe") self.assertEqual((await self.bench.store.list_events({}))[0]["event_id"], event["event_id"]) self.assertEqual(self.bench.station("S1").device.host, "off") self.assertEqual(self.bench.station("S1").device.sent_commands, [])