test_grpc_integration.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. """Meaningful loopback integration tests; all devices are explicitly simulated."""
  2. from __future__ import annotations
  3. import asyncio
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. import sys
  8. import time
  9. import grpc
  10. from google.protobuf import empty_pb2
  11. import pytest
  12. import pytest_asyncio
  13. from stl_backend.config import load_settings
  14. from stl_backend.generated import bench_pb2 as pb
  15. from stl_backend.generated import bench_pb2_grpc as rpc
  16. from stl_backend.server import start_server
  17. ROOT = Path(__file__).resolve().parents[1]
  18. def fast_settings(tmp_path):
  19. settings = load_settings(ROOT / "config" / "simulated.json")
  20. settings["data_dir"] = str(tmp_path / "data")
  21. settings["listen"] = "127.0.0.1:0"
  22. settings["telemetry_interval_s"] = 0.1
  23. for recipe in settings["recipes"]:
  24. recipe.update(preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=5, finish_timeout_s=2)
  25. for profile in settings["profiles"].values():
  26. for step in profile["steps"]:
  27. if "initial_delay_s" in step: step["initial_delay_s"] = 0.01
  28. if "interval_s" in step: step["interval_s"] = 0.01
  29. for station in settings["stations"]:
  30. station.setdefault("simulation", {}).update(step_delay_s=0.01, mt_duration_s=0.3)
  31. return settings
  32. @pytest_asyncio.fixture
  33. async def service(tmp_path):
  34. settings = fast_settings(tmp_path)
  35. server, bench, port = await start_server(settings)
  36. assert port > 0
  37. channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
  38. stub = rpc.BenchServiceStub(channel)
  39. try:
  40. await asyncio.wait_for(channel.channel_ready(), 5)
  41. yield stub, bench, f"127.0.0.1:{port}", settings
  42. finally:
  43. await channel.close()
  44. await server.stop(0)
  45. await bench.grpc_service.drain()
  46. await bench.close()
  47. def start_request(station, command="start-1", *, suffix="one"):
  48. # Identical slot labels on distinct CPUs are valid physical identities.
  49. return pb.StartRunRequest(command_id=command, station_id=station, recipe_id="DEMO-80",
  50. work_order="WO-INTEGRATION", batch_no="BATCH-INTEGRATION", operator="test-operator",
  51. dimms=[pb.DimmIdentity(sn=f"TEST-{suffix}-CPU0", cpu=0, channel="0", slot="A1"),
  52. pb.DimmIdentity(sn=f"TEST-{suffix}-CPU1", cpu=1, channel="0", slot="A1")])
  53. async def completed(stub, run_id, timeout=15):
  54. deadline = time.monotonic() + timeout
  55. while time.monotonic() < deadline:
  56. run = await stub.GetRun(pb.RunKey(run_id=run_id), timeout=3)
  57. if run.finished_unix_ms:
  58. return run
  59. await asyncio.sleep(0.03)
  60. raise AssertionError(f"Run did not finish: {run_id}")
  61. async def command_done(stub, command_id, timeout=10):
  62. deadline = time.monotonic() + timeout
  63. while time.monotonic() < deadline:
  64. command = await stub.GetCommand(pb.CommandKey(command_id=command_id), timeout=3)
  65. if command.state in {"succeeded", "failed", "interrupted"}:
  66. return command
  67. await asyncio.sleep(0.03)
  68. raise AssertionError(f"Command did not finish: {command_id}")
  69. async def waiting_step(stub, station_id, timeout=5):
  70. deadline = time.monotonic() + timeout
  71. while time.monotonic() < deadline:
  72. station = await stub.GetStation(pb.StationKey(station_id=station_id), timeout=3)
  73. if station.pending_step_id:
  74. return station
  75. await asyncio.sleep(0.02)
  76. raise AssertionError("Station did not reach the expected manual step")
  77. def result_bytes(run_id, verdict="pass"):
  78. return json.dumps({"schema": "stl.test-result.v1", "run_id": run_id,
  79. "status": "completed", "verdict": verdict, "error_count": 0 if verdict == "pass" else 1,
  80. "simulated": True, "tests": [{"name": "mt", "status": "completed"}]}, sort_keys=True).encode()
  81. async def upload_result(stub, run_id, data=None, upload_id="result-upload"):
  82. data = result_bytes(run_id) if data is None else data
  83. await stub.BeginArtifact(pb.BeginArtifactRequest(upload_id=upload_id, run_id=run_id,
  84. filename="sim-result.json", kind="result_json", total_bytes=len(data), operator="test-operator"), timeout=3)
  85. await stub.UploadArtifactChunk(pb.ArtifactChunkRequest(upload_id=upload_id, offset=0, data=data), timeout=3)
  86. return await stub.FinishArtifact(pb.FinishArtifactRequest(upload_id=upload_id,
  87. sha256=hashlib.sha256(data).hexdigest()), timeout=10)
  88. async def test_four_stations_are_independent_and_wait_for_real_artifact_import(service):
  89. stub, bench, _, _ = service
  90. initial = await stub.ListStations(empty_pb2.Empty(), timeout=3)
  91. assert len(initial.stations) == 4
  92. assert {s.frontend_index for s in initial.stations} == {0, 1, 2, 3}
  93. assert all(s.mode == "simulated" and len(s.channels) == 24 for s in initial.stations)
  94. commands = await asyncio.gather(*[stub.StartRun(start_request(s.station_id, f"start-four-{i}", suffix=str(i)), timeout=3)
  95. for i, s in enumerate(initial.stations)])
  96. assert len({c.run_id for c in commands}) == 4
  97. runs = await asyncio.gather(*[completed(stub, c.run_id) for c in commands])
  98. assert all(r.state == "completed" and r.workflow_complete for r in runs)
  99. assert all(r.supply_state == "off" for r in runs)
  100. assert all(r.verdict == "pending" and r.artifact_state == "pending_import" for r in runs), [
  101. (r.run_id, r.verdict, r.artifact_state) for r in runs]
  102. assert all(len(r.dimms) == 2 for r in runs)
  103. for i, run in enumerate(runs):
  104. await upload_result(stub, run.run_id, upload_id=f"four-result-{i}")
  105. report = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
  106. assert report.run.verdict == "pass"
  107. assert report.run.artifact_state == "complete"
  108. assert report.sol_bytes > 0 and report.temperature_sample_count > 0
  109. assert len(report.artifacts) == 1
  110. snapshots = await stub.ListStations(empty_pb2.Empty(), timeout=3)
  111. for station in snapshots.stations:
  112. assert station.run_id == "" and station.supply_state == "off"
  113. assert station.temperature.dimm_quality == "powered_off"
  114. assert sum(c.state == "pass" for c in station.channels) == 2
  115. assert sum(c.state == "idle" for c in station.channels) == 22
  116. async def test_retried_command_is_deduplicated_and_conflicting_payload_rejected(service):
  117. stub, _, _, _ = service
  118. request = start_request("S1", "same-command")
  119. a, b = await asyncio.gather(stub.StartRun(request, timeout=3), stub.StartRun(request, timeout=3))
  120. assert a.run_id == b.run_id and a.command_id == b.command_id
  121. changed = pb.StartRunRequest(); changed.CopyFrom(request); changed.batch_no = "ANOTHER-BATCH"
  122. with pytest.raises(grpc.aio.AioRpcError) as error:
  123. await stub.StartRun(changed, timeout=3)
  124. assert error.value.code() == grpc.StatusCode.ALREADY_EXISTS
  125. with pytest.raises(grpc.aio.AioRpcError) as error:
  126. await stub.StartRun(start_request("S1", "other-command", suffix="busy"), timeout=3)
  127. assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
  128. await completed(stub, a.run_id)
  129. history = await stub.ListRuns(pb.ListRunsRequest(station_id="S1", limit=10), timeout=3)
  130. assert len(history.runs) == 1
  131. by_sn = await stub.ListRuns(pb.ListRunsRequest(sn="TEST-one-CPU1", limit=10), timeout=3)
  132. assert [r.run_id for r in by_sn.runs] == [a.run_id]
  133. async def test_stop_is_run_scoped_and_other_station_continues(service):
  134. stub, _, _, _ = service
  135. first = await stub.StartRun(start_request("S1", "stop-start-1"), timeout=3)
  136. other = await stub.StartRun(start_request("S2", "stop-start-2", suffix="other"), timeout=3)
  137. stopped = await stub.StopRun(pb.StopRunRequest(command_id="stop-once", run_id=first.run_id,
  138. operator="test-operator", reason="test stop"), timeout=3)
  139. result = await command_done(stub, stopped.command_id)
  140. assert result.state == "succeeded"
  141. final = await completed(stub, first.run_id)
  142. assert final.state == "stopped" and final.supply_state == "off"
  143. assert final.verdict == "inconclusive"
  144. assert (await completed(stub, other.run_id)).state == "completed"
  145. replacement = await stub.StartRun(start_request("S1", "replacement", suffix="replacement"), timeout=3)
  146. with pytest.raises(grpc.aio.AioRpcError) as error:
  147. await stub.StopRun(pb.StopRunRequest(command_id="stale-stop", run_id=first.run_id,
  148. operator="test-operator"), timeout=3)
  149. assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
  150. assert (await completed(stub, replacement.run_id)).state == "completed"
  151. async def test_upload_resume_hash_validation_and_original_file_roundtrip(service):
  152. stub, _, endpoint, _ = service
  153. command = await stub.StartRun(start_request("S1", "upload-start"), timeout=3)
  154. await completed(stub, command.run_id)
  155. data = result_bytes(command.run_id)
  156. begin = pb.BeginArtifactRequest(upload_id="resume-one", run_id=command.run_id,
  157. filename="original.json", kind="result_json", total_bytes=len(data), operator="test-operator")
  158. session = await stub.BeginArtifact(begin, timeout=3)
  159. assert session.next_offset == 0
  160. split = len(data) // 2
  161. chunk = pb.ArtifactChunkRequest(upload_id="resume-one", offset=0, data=data[:split])
  162. session = await stub.UploadArtifactChunk(chunk, timeout=3)
  163. assert session.next_offset == split
  164. # A new client sees committed progress; re-sending the same bytes is harmless.
  165. async with grpc.aio.insecure_channel(endpoint) as channel:
  166. second = rpc.BenchServiceStub(channel)
  167. session = await second.BeginArtifact(begin, timeout=3)
  168. assert session.next_offset == split
  169. session = await second.UploadArtifactChunk(chunk, timeout=3)
  170. assert session.next_offset == split
  171. await second.UploadArtifactChunk(pb.ArtifactChunkRequest(upload_id="resume-one", offset=split, data=data[split:]), timeout=3)
  172. with pytest.raises(grpc.aio.AioRpcError) as error:
  173. await second.FinishArtifact(pb.FinishArtifactRequest(upload_id="resume-one", sha256="0" * 64), timeout=5)
  174. assert error.value.code() in {grpc.StatusCode.INVALID_ARGUMENT, grpc.StatusCode.DATA_LOSS}
  175. finish = pb.FinishArtifactRequest(upload_id="resume-one", sha256=hashlib.sha256(data).hexdigest())
  176. artifact = await second.FinishArtifact(finish, timeout=10)
  177. repeated = await second.FinishArtifact(finish, timeout=10)
  178. assert repeated.artifact_id == artifact.artifact_id
  179. read = await stub.ReadArtifact(pb.ReadArtifactRequest(artifact_id=artifact.artifact_id, offset=0, max_bytes=256 * 1024), timeout=3)
  180. assert read.data == data and read.eof and read.next_offset == len(data)
  181. listed = await stub.ListArtifacts(pb.RunKey(run_id=command.run_id), timeout=3)
  182. assert len(listed.artifacts) == 1
  183. assert (await stub.GetRunReport(pb.RunKey(run_id=command.run_id), timeout=3)).run.verdict == "pass"
  184. async def test_sol_byte_cursors_temperature_quality_and_events(service):
  185. stub, _, _, _ = service
  186. command = await stub.StartRun(start_request("S1", "read-start"), timeout=3)
  187. run = await completed(stub, command.run_id)
  188. a = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=0, max_bytes=23), timeout=3)
  189. b = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=a.next_offset, max_bytes=23), timeout=3)
  190. full = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=0, max_bytes=256 * 1024), timeout=3)
  191. assert a.data + b.data == full.data[:46]
  192. assert a.next_offset == 23 and b.next_offset == 46
  193. assert b"[0][CxmtDdrTest]Current stage is 1" in full.data
  194. temperatures = await stub.QueryTemperatures(pb.TemperatureQuery(run_id=run.run_id, limit=2000), timeout=3)
  195. assert any(s.temperature.dimm_quality == "unavailable_in_phase" for s in temperatures.samples)
  196. assert any(s.temperature.dimms for s in temperatures.samples)
  197. events = await stub.ListEvents(pb.ListEventsRequest(run_id=run.run_id, limit=1000), timeout=3)
  198. assert events.events
  199. event = await stub.AcknowledgeEvent(pb.AcknowledgeEventRequest(event_id=events.events[0].event_id,
  200. operator="test-operator"), timeout=3)
  201. assert event.acknowledged_by == "test-operator"
  202. page = await stub.ListEvents(pb.ListEventsRequest(run_id=run.run_id, after_event_id=event.event_id, limit=10), timeout=3)
  203. assert all(e.event_id > event.event_id for e in page.events)
  204. async def test_client_disconnect_does_not_stop_backend_and_cli_transfer_works(service, tmp_path):
  205. from stl_backend.cli import Client, build_parser, download, upload
  206. stub, _, endpoint, _ = service
  207. async with grpc.aio.insecure_channel(endpoint) as channel:
  208. transient = rpc.BenchServiceStub(channel)
  209. command = await transient.StartRun(start_request("S1", "disconnect-start"), timeout=3)
  210. run = await completed(stub, command.run_id)
  211. assert run.state == "completed"
  212. path = tmp_path / "cli-result.json"
  213. data = result_bytes(run.run_id)
  214. path.write_bytes(data)
  215. args = build_parser().parse_args(["--target", endpoint, "system"])
  216. def operate_cli():
  217. client = Client(args)
  218. try:
  219. artifact = upload(client, run.run_id, path, kind="result_json", operator="test-operator")
  220. artifact_again = upload(client, run.run_id, path, kind="result_json", operator="test-operator")
  221. assert artifact.artifact_id == artifact_again.artifact_id
  222. target = tmp_path / "download.json"
  223. result = download(client, artifact.artifact_id, target, expected_sha256=artifact.sha256)
  224. assert result["expected_hash_verified"] and target.read_bytes() == data
  225. finally:
  226. client.close()
  227. await asyncio.to_thread(operate_cli)
  228. assert (await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)).run.verdict == "pass"
  229. async def test_deadline_after_durable_insert_does_not_orphan_accepted_run(service, monkeypatch):
  230. stub, bench, _, _ = service
  231. persisted, release = asyncio.Event(), asyncio.Event()
  232. original = bench.store.create_run
  233. async def gate_after_insert(*args):
  234. run = await original(*args)
  235. persisted.set()
  236. await release.wait()
  237. return run
  238. monkeypatch.setattr(bench.store, "create_run", gate_after_insert)
  239. request = start_request("S1", "deadline-start")
  240. call = stub.StartRun(request, timeout=0.2)
  241. try:
  242. await asyncio.wait_for(persisted.wait(), 3)
  243. with pytest.raises(grpc.aio.AioRpcError) as error:
  244. await call
  245. assert error.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED
  246. finally:
  247. release.set()
  248. # The same intent is retried with the SAME command ID. It must return the
  249. # already-persisted run, and that run must actually acquire its worker.
  250. retried = await stub.StartRun(request, timeout=3)
  251. final = await completed(stub, retried.run_id)
  252. assert final.state == "completed" and final.supply_state == "off"
  253. history = await stub.ListRuns(pb.ListRunsRequest(station_id="S1", limit=10), timeout=3)
  254. assert [r.run_id for r in history.runs] == [retried.run_id]
  255. async def test_invalid_topology_and_recipe_revisions_preserve_run_snapshot(service):
  256. stub, _, _, _ = service
  257. invalid = start_request("S1", "invalid-channel")
  258. invalid.dimms[0].channel = "12"
  259. with pytest.raises(grpc.aio.AioRpcError) as error:
  260. await stub.StartRun(invalid, timeout=3)
  261. assert error.value.code() == grpc.StatusCode.INVALID_ARGUMENT
  262. empty = start_request("S1", "missing-dimms")
  263. empty.ClearField("dimms")
  264. with pytest.raises(grpc.aio.AioRpcError) as error:
  265. await stub.StartRun(empty, timeout=3)
  266. assert error.value.code() == grpc.StatusCode.INVALID_ARGUMENT
  267. assert not (await stub.ListRuns(pb.ListRunsRequest(station_id="S1"), timeout=3)).runs
  268. recipe = await stub.GetRecipe(pb.RecipeKey(recipe_id="DEMO-80"), timeout=3)
  269. recipe.recipe_id = "SNAPSHOT-RECIPE"
  270. first = await stub.PutRecipe(pb.PutRecipeRequest(recipe=recipe, expected_revision=0), timeout=3)
  271. assert first.revision == 1
  272. request = start_request("S1", "snapshot-start")
  273. request.recipe_id = first.recipe_id
  274. command = await stub.StartRun(request, timeout=3)
  275. changed = pb.Recipe(); changed.CopyFrom(first)
  276. changed.dimm_target_c = 81
  277. changed.notes = "edited after the run began"
  278. second = await stub.PutRecipe(pb.PutRecipeRequest(recipe=changed, expected_revision=1), timeout=3)
  279. assert second.revision == 2
  280. with pytest.raises(grpc.aio.AioRpcError) as error:
  281. await stub.PutRecipe(pb.PutRecipeRequest(recipe=changed, expected_revision=1), timeout=3)
  282. assert error.value.code() == grpc.StatusCode.ABORTED
  283. run = await completed(stub, command.run_id)
  284. assert run.recipe.revision == 1 and run.recipe.dimm_target_c == 80
  285. assert run.recipe.notes == first.notes
  286. async def test_bearer_auth_applies_to_read_and_mutation_rpcs(service):
  287. stub, bench, _, _ = service
  288. bench.grpc_service.token = "integration-only-token"
  289. try:
  290. for metadata in (None, (("authorization", "Bearer wrong-token"),)):
  291. with pytest.raises(grpc.aio.AioRpcError) as error:
  292. await stub.GetSystemInfo(empty_pb2.Empty(), timeout=3, metadata=metadata)
  293. assert error.value.code() == grpc.StatusCode.UNAUTHENTICATED
  294. with pytest.raises(grpc.aio.AioRpcError) as error:
  295. await stub.StartRun(start_request("S1", "unauthenticated-start"), timeout=3)
  296. assert error.value.code() == grpc.StatusCode.UNAUTHENTICATED
  297. metadata = (("authorization", "Bearer integration-only-token"),)
  298. info = await stub.GetSystemInfo(empty_pb2.Empty(), timeout=3, metadata=metadata)
  299. assert info.station_count == 4 and info.mode == "simulated"
  300. assert not (await stub.ListRuns(pb.ListRunsRequest(), timeout=3, metadata=metadata)).runs
  301. finally:
  302. bench.grpc_service.token = ""
  303. async def test_completed_history_artifacts_and_command_identity_survive_restart(tmp_path):
  304. settings = fast_settings(tmp_path)
  305. request = start_request("S1", "persisted-start", suffix="persistent")
  306. server, bench, port = await start_server(settings)
  307. channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
  308. try:
  309. stub = rpc.BenchServiceStub(channel)
  310. command = await stub.StartRun(request, timeout=3)
  311. run = await completed(stub, command.run_id)
  312. artifact = await upload_result(stub, run.run_id, upload_id="persisted-artifact")
  313. before = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
  314. assert before.run.verdict == "pass"
  315. finally:
  316. await channel.close()
  317. await server.stop(0)
  318. await bench.grpc_service.drain()
  319. await bench.close()
  320. server, bench, port = await start_server(settings)
  321. channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
  322. try:
  323. stub = rpc.BenchServiceStub(channel)
  324. after = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
  325. assert after.run.verdict == "pass" and after.run.supply_state == "off"
  326. assert after.run.recipe == before.run.recipe
  327. assert after.sol_bytes == before.sol_bytes and after.temperature_sample_count == before.temperature_sample_count
  328. assert [a.artifact_id for a in after.artifacts] == [artifact.artifact_id]
  329. history = await stub.ListRuns(pb.ListRunsRequest(sn="TEST-persistent-CPU1", limit=10), timeout=3)
  330. assert [r.run_id for r in history.runs] == [run.run_id]
  331. retried = await stub.StartRun(request, timeout=3)
  332. assert retried.run_id == run.run_id
  333. assert bench.runtimes["S1"].run is None
  334. finally:
  335. await channel.close()
  336. await server.stop(0)
  337. await bench.grpc_service.drain()
  338. await bench.close()
  339. async def test_result_for_another_run_cannot_turn_selected_run_into_pass(service):
  340. stub, _, _, _ = service
  341. command = await stub.StartRun(start_request("S1", "wrong-artifact-start"), timeout=3)
  342. await completed(stub, command.run_id)
  343. with pytest.raises(grpc.aio.AioRpcError) as error:
  344. await upload_result(stub, command.run_id, result_bytes("R-another-run"), upload_id="wrong-run-result")
  345. assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
  346. report = await stub.GetRunReport(pb.RunKey(run_id=command.run_id), timeout=3)
  347. assert report.run.verdict == "pending" and not report.artifacts
  348. async def test_full_cli_demo_runs_four_stations_and_imports_simulated_pass_results(service):
  349. stub, _, endpoint, _ = service
  350. process = await asyncio.create_subprocess_exec(sys.executable, "-m", "stl_backend.cli",
  351. "--target", endpoint, "demo", "--wait-seconds", "30", "--interval", "0.2",
  352. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
  353. try:
  354. stdout, stderr = await asyncio.wait_for(process.communicate(), 40)
  355. except BaseException:
  356. if process.returncode is None:
  357. process.kill()
  358. await process.wait()
  359. raise
  360. assert process.returncode == 0, stderr.decode(errors="replace")
  361. results = json.loads(stdout)
  362. assert len(results) == 4 and len({r["run_id"] for r in results}) == 4
  363. assert all(r["mode"] == "simulated" and r["verdict"] == "pass"
  364. and r["supply_state"] == "off" and r["artifact_state"] == "complete" for r in results)
  365. assert all(not s.run_id for s in (await stub.ListStations(empty_pb2.Empty(), timeout=3)).stations)
  366. async def test_competing_manual_confirmations_cannot_overwrite_the_first_claim(service, monkeypatch):
  367. stub, bench, _, settings = service
  368. settings["profiles"]["sim-cxmt"]["steps"][0]["manual"] = True
  369. command = await stub.StartRun(start_request("S1", "manual-claim-start"), timeout=3)
  370. waiting = await waiting_step(stub, "S1")
  371. entered, release = asyncio.Event(), asyncio.Event()
  372. original = bench.event
  373. async def hold_first_confirmation(rt, kind, *args, **kwargs):
  374. if kind == "manual_confirmation" and not entered.is_set():
  375. entered.set()
  376. await release.wait()
  377. return await original(rt, kind, *args, **kwargs)
  378. monkeypatch.setattr(bench, "event", hold_first_confirmation)
  379. first = await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="manual-confirm-first",
  380. run_id=command.run_id, step_id=waiting.pending_step_id, operator="operator-a",
  381. evidence="first confirmation evidence", succeeded=True), timeout=3)
  382. try:
  383. await asyncio.wait_for(entered.wait(), 3)
  384. try:
  385. other = await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="manual-confirm-conflict",
  386. run_id=command.run_id, step_id=waiting.pending_step_id, operator="operator-b",
  387. evidence="competing confirmation evidence", succeeded=False), timeout=3)
  388. except grpc.aio.AioRpcError as error:
  389. assert error.code() == grpc.StatusCode.FAILED_PRECONDITION
  390. else:
  391. # An implementation may reject at acceptance or in the durable
  392. # command worker. It must never apply the competing acknowledgement.
  393. assert (await command_done(stub, other.command_id)).state == "failed"
  394. finally:
  395. release.set()
  396. assert (await command_done(stub, first.command_id)).state == "succeeded"
  397. assert (await completed(stub, command.run_id)).state == "completed"
  398. async def test_target_change_is_rejected_until_initial_target_is_applied(service, monkeypatch):
  399. stub, bench, _, settings = service
  400. settings["profiles"]["sim-cxmt"]["steps"][0]["manual"] = True
  401. entered, release = asyncio.Event(), asyncio.Event()
  402. device = bench.runtimes["S1"].device
  403. original = device.set_target
  404. async def hold_initial_target(target):
  405. if not entered.is_set():
  406. entered.set()
  407. await release.wait()
  408. return await original(target)
  409. monkeypatch.setattr(device, "set_target", hold_initial_target)
  410. command = await stub.StartRun(start_request("S1", "target-init-start"), timeout=3)
  411. try:
  412. await asyncio.wait_for(entered.wait(), 3)
  413. with pytest.raises(grpc.aio.AioRpcError) as error:
  414. await stub.SetTargetTemperature(pb.SetTargetRequest(command_id="target-too-early",
  415. run_id=command.run_id, target_c=85, operator="test-operator"), timeout=3)
  416. assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
  417. finally:
  418. release.set()
  419. waiting = await waiting_step(stub, "S1")
  420. changed = await stub.SetTargetTemperature(pb.SetTargetRequest(command_id="target-after-init",
  421. run_id=command.run_id, target_c=85, operator="test-operator"), timeout=3)
  422. result = await command_done(stub, changed.command_id)
  423. assert result.state == "succeeded" and result.result["applied_target_c"] == 85
  424. station = await stub.GetStation(pb.StationKey(station_id="S1"), timeout=3)
  425. assert station.temperature.requested_target_c == 85 and station.temperature.applied_target_c == 85
  426. await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="target-step-confirm",
  427. run_id=command.run_id, step_id=waiting.pending_step_id, operator="test-operator",
  428. evidence="complete manual step after target change", succeeded=True), timeout=3)
  429. run = await completed(stub, command.run_id)
  430. assert run.state == "completed" and run.recipe.dimm_target_c == 80
  431. assert run.evidence["target_changes"][0]["applied_c"] == 85
  432. async def test_server_only_diagnostic_rpc_console_and_read_only_bmc_query(service):
  433. stub, bench, _, _ = service
  434. power = await stub.StationPower(pb.StationPowerRequest(command_id="diagnostic-supply",
  435. station_id="S1", action="supply_on", operator="test-operator"), timeout=3)
  436. assert (await command_done(stub, power.command_id)).state == "succeeded"
  437. query = await stub.QueryBmc(pb.BmcQueryRequest(station_id="S1", query="info"), timeout=3)
  438. assert query.mode == "simulated" and "SIMULATED BMC" in query.text and query.observed_unix_ms
  439. opened = await stub.SetDiagnosticSol(pb.SetDiagnosticSolRequest(command_id="diagnostic-open",
  440. station_id="S1", action="open", operator="test-operator"), timeout=3)
  441. assert (await command_done(stub, opened.command_id)).state == "succeeded"
  442. status = await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)
  443. assert status.state == "online" and status.phase == "unknown"
  444. power = await stub.StationPower(pb.StationPowerRequest(command_id="diagnostic-boot",
  445. station_id="S1", action="host_on", operator="test-operator"), timeout=3)
  446. assert (await command_done(stub, power.command_id)).state == "succeeded"
  447. async with asyncio.timeout(3):
  448. while (await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)).phase != "uip":
  449. await asyncio.sleep(0.01)
  450. sent = await stub.WriteDiagnosticSol(pb.WriteDiagnosticSolRequest(command_id="diagnostic-input",
  451. station_id="S1", session_id=status.session_id, data=b"help\r", operator="test-operator"), timeout=3)
  452. assert (await command_done(stub, sent.command_id)).state == "succeeded"
  453. read = await stub.ReadDiagnosticSol(pb.ReadDiagnosticSolRequest(station_id="S1",
  454. session_id=status.session_id, max_bytes=65536), timeout=3)
  455. assert b"Current stage is 1" in read.data
  456. assert bench.runtimes["S1"].device.sent_commands == [b"help\r"]
  457. assert not (await stub.ListRuns(pb.ListRunsRequest(), timeout=3)).runs
  458. closed = await stub.SetDiagnosticSol(pb.SetDiagnosticSolRequest(command_id="diagnostic-close",
  459. station_id="S1", action="close", operator="test-operator"), timeout=3)
  460. assert (await command_done(stub, closed.command_id)).state == "succeeded"
  461. assert (await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)).state == "closed"
  462. assert (await stub.GetStation(pb.StationKey(station_id="S1"), timeout=3)).server_power == "on"
  463. async def test_shared_queue_native_grpc_and_independent_event_consumers(service):
  464. stub, _, target, _ = service
  465. async def queue_done(command_id):
  466. async with asyncio.timeout(4):
  467. while True:
  468. item = await stub.GetQueueItem(pb.CommandKey(command_id=command_id), timeout=3)
  469. if item.state in ("succeeded", "failed", "interrupted"):
  470. return item
  471. await asyncio.sleep(.01)
  472. request = pb.EnqueueCommandRequest(command_id="native-queue-power", station_id="S1",
  473. method="StationPower", operator="native-ui-one", arguments={"action":"supply_on"})
  474. first = await stub.EnqueueCommand(request, timeout=3)
  475. assert (await queue_done(first.command_id)).state == "succeeded"
  476. channel2 = grpc.aio.insecure_channel(target)
  477. try:
  478. second_ui = rpc.BenchServiceStub(channel2)
  479. repeated = await second_ui.EnqueueCommand(request, timeout=3)
  480. assert repeated.sequence == first.sequence
  481. queued = await second_ui.EnqueueCommand(pb.EnqueueCommandRequest(command_id="native-queue-info",
  482. station_id="S1", method="QueryBmc", operator="native-ui-two", arguments={"query":"info"}), timeout=3)
  483. result = await queue_done(queued.command_id)
  484. assert result.state == "succeeded" and "SIMULATED" in result.result["text"]
  485. listing = await stub.GetQueue(pb.GetQueueRequest(station_id="S1", limit=100), timeout=3)
  486. assert [item.command_id for item in listing.items] == [queued.command_id, first.command_id]
  487. page1 = await stub.ReadEventQueue(pb.ReadEventQueueRequest(station_id="S1", limit=1000), timeout=3)
  488. page2 = await second_ui.ReadEventQueue(pb.ReadEventQueueRequest(station_id="S1", limit=1000), timeout=3)
  489. assert page1 == page2 and page1.events
  490. assert any(event.command_id == queued.command_id for event in page1.events)
  491. finally:
  492. await channel2.close()