| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551 |
- """Meaningful loopback integration tests; all devices are explicitly simulated."""
- from __future__ import annotations
- import asyncio
- import hashlib
- import json
- from pathlib import Path
- import sys
- import time
- import grpc
- from google.protobuf import empty_pb2
- import pytest
- import pytest_asyncio
- from stl_backend.config import load_settings
- from stl_backend.generated import bench_pb2 as pb
- from stl_backend.generated import bench_pb2_grpc as rpc
- from stl_backend.server import start_server
- ROOT = Path(__file__).resolve().parents[1]
- def fast_settings(tmp_path):
- settings = load_settings(ROOT / "config" / "simulated.json")
- settings["data_dir"] = str(tmp_path / "data")
- settings["listen"] = "127.0.0.1:0"
- settings["telemetry_interval_s"] = 0.1
- for recipe in settings["recipes"]:
- recipe.update(preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=5, finish_timeout_s=2)
- for profile in settings["profiles"].values():
- for step in profile["steps"]:
- if "initial_delay_s" in step: step["initial_delay_s"] = 0.01
- if "interval_s" in step: step["interval_s"] = 0.01
- for station in settings["stations"]:
- station.setdefault("simulation", {}).update(step_delay_s=0.01, mt_duration_s=0.3)
- return settings
- @pytest_asyncio.fixture
- async def service(tmp_path):
- settings = fast_settings(tmp_path)
- server, bench, port = await start_server(settings)
- assert port > 0
- channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
- stub = rpc.BenchServiceStub(channel)
- try:
- await asyncio.wait_for(channel.channel_ready(), 5)
- yield stub, bench, f"127.0.0.1:{port}", settings
- finally:
- await channel.close()
- await server.stop(0)
- await bench.grpc_service.drain()
- await bench.close()
- def start_request(station, command="start-1", *, suffix="one"):
- # Identical slot labels on distinct CPUs are valid physical identities.
- return pb.StartRunRequest(command_id=command, station_id=station, recipe_id="DEMO-80",
- work_order="WO-INTEGRATION", batch_no="BATCH-INTEGRATION", operator="test-operator",
- dimms=[pb.DimmIdentity(sn=f"TEST-{suffix}-CPU0", cpu=0, channel="0", slot="A1"),
- pb.DimmIdentity(sn=f"TEST-{suffix}-CPU1", cpu=1, channel="0", slot="A1")])
- async def completed(stub, run_id, timeout=15):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- run = await stub.GetRun(pb.RunKey(run_id=run_id), timeout=3)
- if run.finished_unix_ms:
- return run
- await asyncio.sleep(0.03)
- raise AssertionError(f"Run did not finish: {run_id}")
- async def command_done(stub, command_id, timeout=10):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- command = await stub.GetCommand(pb.CommandKey(command_id=command_id), timeout=3)
- if command.state in {"succeeded", "failed", "interrupted"}:
- return command
- await asyncio.sleep(0.03)
- raise AssertionError(f"Command did not finish: {command_id}")
- async def waiting_step(stub, station_id, timeout=5):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- station = await stub.GetStation(pb.StationKey(station_id=station_id), timeout=3)
- if station.pending_step_id:
- return station
- await asyncio.sleep(0.02)
- raise AssertionError("Station did not reach the expected manual step")
- def result_bytes(run_id, verdict="pass"):
- return json.dumps({"schema": "stl.test-result.v1", "run_id": run_id,
- "status": "completed", "verdict": verdict, "error_count": 0 if verdict == "pass" else 1,
- "simulated": True, "tests": [{"name": "mt", "status": "completed"}]}, sort_keys=True).encode()
- async def upload_result(stub, run_id, data=None, upload_id="result-upload"):
- data = result_bytes(run_id) if data is None else data
- await stub.BeginArtifact(pb.BeginArtifactRequest(upload_id=upload_id, run_id=run_id,
- filename="sim-result.json", kind="result_json", total_bytes=len(data), operator="test-operator"), timeout=3)
- await stub.UploadArtifactChunk(pb.ArtifactChunkRequest(upload_id=upload_id, offset=0, data=data), timeout=3)
- return await stub.FinishArtifact(pb.FinishArtifactRequest(upload_id=upload_id,
- sha256=hashlib.sha256(data).hexdigest()), timeout=10)
- async def test_four_stations_are_independent_and_wait_for_real_artifact_import(service):
- stub, bench, _, _ = service
- initial = await stub.ListStations(empty_pb2.Empty(), timeout=3)
- assert len(initial.stations) == 4
- assert {s.frontend_index for s in initial.stations} == {0, 1, 2, 3}
- assert all(s.mode == "simulated" and len(s.channels) == 24 for s in initial.stations)
- commands = await asyncio.gather(*[stub.StartRun(start_request(s.station_id, f"start-four-{i}", suffix=str(i)), timeout=3)
- for i, s in enumerate(initial.stations)])
- assert len({c.run_id for c in commands}) == 4
- runs = await asyncio.gather(*[completed(stub, c.run_id) for c in commands])
- assert all(r.state == "completed" and r.workflow_complete for r in runs)
- assert all(r.supply_state == "off" for r in runs)
- assert all(r.verdict == "pending" and r.artifact_state == "pending_import" for r in runs), [
- (r.run_id, r.verdict, r.artifact_state) for r in runs]
- assert all(len(r.dimms) == 2 for r in runs)
- for i, run in enumerate(runs):
- await upload_result(stub, run.run_id, upload_id=f"four-result-{i}")
- report = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
- assert report.run.verdict == "pass"
- assert report.run.artifact_state == "complete"
- assert report.sol_bytes > 0 and report.temperature_sample_count > 0
- assert len(report.artifacts) == 1
- snapshots = await stub.ListStations(empty_pb2.Empty(), timeout=3)
- for station in snapshots.stations:
- assert station.run_id == "" and station.supply_state == "off"
- assert station.temperature.dimm_quality == "powered_off"
- assert sum(c.state == "pass" for c in station.channels) == 2
- assert sum(c.state == "idle" for c in station.channels) == 22
- async def test_retried_command_is_deduplicated_and_conflicting_payload_rejected(service):
- stub, _, _, _ = service
- request = start_request("S1", "same-command")
- a, b = await asyncio.gather(stub.StartRun(request, timeout=3), stub.StartRun(request, timeout=3))
- assert a.run_id == b.run_id and a.command_id == b.command_id
- changed = pb.StartRunRequest(); changed.CopyFrom(request); changed.batch_no = "ANOTHER-BATCH"
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StartRun(changed, timeout=3)
- assert error.value.code() == grpc.StatusCode.ALREADY_EXISTS
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StartRun(start_request("S1", "other-command", suffix="busy"), timeout=3)
- assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
- await completed(stub, a.run_id)
- history = await stub.ListRuns(pb.ListRunsRequest(station_id="S1", limit=10), timeout=3)
- assert len(history.runs) == 1
- by_sn = await stub.ListRuns(pb.ListRunsRequest(sn="TEST-one-CPU1", limit=10), timeout=3)
- assert [r.run_id for r in by_sn.runs] == [a.run_id]
- async def test_stop_is_run_scoped_and_other_station_continues(service):
- stub, _, _, _ = service
- first = await stub.StartRun(start_request("S1", "stop-start-1"), timeout=3)
- other = await stub.StartRun(start_request("S2", "stop-start-2", suffix="other"), timeout=3)
- stopped = await stub.StopRun(pb.StopRunRequest(command_id="stop-once", run_id=first.run_id,
- operator="test-operator", reason="test stop"), timeout=3)
- result = await command_done(stub, stopped.command_id)
- assert result.state == "succeeded"
- final = await completed(stub, first.run_id)
- assert final.state == "stopped" and final.supply_state == "off"
- assert final.verdict == "inconclusive"
- assert (await completed(stub, other.run_id)).state == "completed"
- replacement = await stub.StartRun(start_request("S1", "replacement", suffix="replacement"), timeout=3)
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StopRun(pb.StopRunRequest(command_id="stale-stop", run_id=first.run_id,
- operator="test-operator"), timeout=3)
- assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
- assert (await completed(stub, replacement.run_id)).state == "completed"
- async def test_upload_resume_hash_validation_and_original_file_roundtrip(service):
- stub, _, endpoint, _ = service
- command = await stub.StartRun(start_request("S1", "upload-start"), timeout=3)
- await completed(stub, command.run_id)
- data = result_bytes(command.run_id)
- begin = pb.BeginArtifactRequest(upload_id="resume-one", run_id=command.run_id,
- filename="original.json", kind="result_json", total_bytes=len(data), operator="test-operator")
- session = await stub.BeginArtifact(begin, timeout=3)
- assert session.next_offset == 0
- split = len(data) // 2
- chunk = pb.ArtifactChunkRequest(upload_id="resume-one", offset=0, data=data[:split])
- session = await stub.UploadArtifactChunk(chunk, timeout=3)
- assert session.next_offset == split
- # A new client sees committed progress; re-sending the same bytes is harmless.
- async with grpc.aio.insecure_channel(endpoint) as channel:
- second = rpc.BenchServiceStub(channel)
- session = await second.BeginArtifact(begin, timeout=3)
- assert session.next_offset == split
- session = await second.UploadArtifactChunk(chunk, timeout=3)
- assert session.next_offset == split
- await second.UploadArtifactChunk(pb.ArtifactChunkRequest(upload_id="resume-one", offset=split, data=data[split:]), timeout=3)
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await second.FinishArtifact(pb.FinishArtifactRequest(upload_id="resume-one", sha256="0" * 64), timeout=5)
- assert error.value.code() in {grpc.StatusCode.INVALID_ARGUMENT, grpc.StatusCode.DATA_LOSS}
- finish = pb.FinishArtifactRequest(upload_id="resume-one", sha256=hashlib.sha256(data).hexdigest())
- artifact = await second.FinishArtifact(finish, timeout=10)
- repeated = await second.FinishArtifact(finish, timeout=10)
- assert repeated.artifact_id == artifact.artifact_id
- read = await stub.ReadArtifact(pb.ReadArtifactRequest(artifact_id=artifact.artifact_id, offset=0, max_bytes=256 * 1024), timeout=3)
- assert read.data == data and read.eof and read.next_offset == len(data)
- listed = await stub.ListArtifacts(pb.RunKey(run_id=command.run_id), timeout=3)
- assert len(listed.artifacts) == 1
- assert (await stub.GetRunReport(pb.RunKey(run_id=command.run_id), timeout=3)).run.verdict == "pass"
- async def test_sol_byte_cursors_temperature_quality_and_events(service):
- stub, _, _, _ = service
- command = await stub.StartRun(start_request("S1", "read-start"), timeout=3)
- run = await completed(stub, command.run_id)
- a = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=0, max_bytes=23), timeout=3)
- b = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=a.next_offset, max_bytes=23), timeout=3)
- full = await stub.ReadSol(pb.ReadSolRequest(run_id=run.run_id, offset=0, max_bytes=256 * 1024), timeout=3)
- assert a.data + b.data == full.data[:46]
- assert a.next_offset == 23 and b.next_offset == 46
- assert b"[0][CxmtDdrTest]Current stage is 1" in full.data
- temperatures = await stub.QueryTemperatures(pb.TemperatureQuery(run_id=run.run_id, limit=2000), timeout=3)
- assert any(s.temperature.dimm_quality == "unavailable_in_phase" for s in temperatures.samples)
- assert any(s.temperature.dimms for s in temperatures.samples)
- events = await stub.ListEvents(pb.ListEventsRequest(run_id=run.run_id, limit=1000), timeout=3)
- assert events.events
- event = await stub.AcknowledgeEvent(pb.AcknowledgeEventRequest(event_id=events.events[0].event_id,
- operator="test-operator"), timeout=3)
- assert event.acknowledged_by == "test-operator"
- page = await stub.ListEvents(pb.ListEventsRequest(run_id=run.run_id, after_event_id=event.event_id, limit=10), timeout=3)
- assert all(e.event_id > event.event_id for e in page.events)
- async def test_client_disconnect_does_not_stop_backend_and_cli_transfer_works(service, tmp_path):
- from stl_backend.cli import Client, build_parser, download, upload
- stub, _, endpoint, _ = service
- async with grpc.aio.insecure_channel(endpoint) as channel:
- transient = rpc.BenchServiceStub(channel)
- command = await transient.StartRun(start_request("S1", "disconnect-start"), timeout=3)
- run = await completed(stub, command.run_id)
- assert run.state == "completed"
- path = tmp_path / "cli-result.json"
- data = result_bytes(run.run_id)
- path.write_bytes(data)
- args = build_parser().parse_args(["--target", endpoint, "system"])
- def operate_cli():
- client = Client(args)
- try:
- artifact = upload(client, run.run_id, path, kind="result_json", operator="test-operator")
- artifact_again = upload(client, run.run_id, path, kind="result_json", operator="test-operator")
- assert artifact.artifact_id == artifact_again.artifact_id
- target = tmp_path / "download.json"
- result = download(client, artifact.artifact_id, target, expected_sha256=artifact.sha256)
- assert result["expected_hash_verified"] and target.read_bytes() == data
- finally:
- client.close()
- await asyncio.to_thread(operate_cli)
- assert (await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)).run.verdict == "pass"
- async def test_deadline_after_durable_insert_does_not_orphan_accepted_run(service, monkeypatch):
- stub, bench, _, _ = service
- persisted, release = asyncio.Event(), asyncio.Event()
- original = bench.store.create_run
- async def gate_after_insert(*args):
- run = await original(*args)
- persisted.set()
- await release.wait()
- return run
- monkeypatch.setattr(bench.store, "create_run", gate_after_insert)
- request = start_request("S1", "deadline-start")
- call = stub.StartRun(request, timeout=0.2)
- try:
- await asyncio.wait_for(persisted.wait(), 3)
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await call
- assert error.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED
- finally:
- release.set()
- # The same intent is retried with the SAME command ID. It must return the
- # already-persisted run, and that run must actually acquire its worker.
- retried = await stub.StartRun(request, timeout=3)
- final = await completed(stub, retried.run_id)
- assert final.state == "completed" and final.supply_state == "off"
- history = await stub.ListRuns(pb.ListRunsRequest(station_id="S1", limit=10), timeout=3)
- assert [r.run_id for r in history.runs] == [retried.run_id]
- async def test_invalid_topology_and_recipe_revisions_preserve_run_snapshot(service):
- stub, _, _, _ = service
- invalid = start_request("S1", "invalid-channel")
- invalid.dimms[0].channel = "12"
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StartRun(invalid, timeout=3)
- assert error.value.code() == grpc.StatusCode.INVALID_ARGUMENT
- empty = start_request("S1", "missing-dimms")
- empty.ClearField("dimms")
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StartRun(empty, timeout=3)
- assert error.value.code() == grpc.StatusCode.INVALID_ARGUMENT
- assert not (await stub.ListRuns(pb.ListRunsRequest(station_id="S1"), timeout=3)).runs
- recipe = await stub.GetRecipe(pb.RecipeKey(recipe_id="DEMO-80"), timeout=3)
- recipe.recipe_id = "SNAPSHOT-RECIPE"
- first = await stub.PutRecipe(pb.PutRecipeRequest(recipe=recipe, expected_revision=0), timeout=3)
- assert first.revision == 1
- request = start_request("S1", "snapshot-start")
- request.recipe_id = first.recipe_id
- command = await stub.StartRun(request, timeout=3)
- changed = pb.Recipe(); changed.CopyFrom(first)
- changed.dimm_target_c = 81
- changed.notes = "edited after the run began"
- second = await stub.PutRecipe(pb.PutRecipeRequest(recipe=changed, expected_revision=1), timeout=3)
- assert second.revision == 2
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.PutRecipe(pb.PutRecipeRequest(recipe=changed, expected_revision=1), timeout=3)
- assert error.value.code() == grpc.StatusCode.ABORTED
- run = await completed(stub, command.run_id)
- assert run.recipe.revision == 1 and run.recipe.dimm_target_c == 80
- assert run.recipe.notes == first.notes
- async def test_bearer_auth_applies_to_read_and_mutation_rpcs(service):
- stub, bench, _, _ = service
- bench.grpc_service.token = "integration-only-token"
- try:
- for metadata in (None, (("authorization", "Bearer wrong-token"),)):
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.GetSystemInfo(empty_pb2.Empty(), timeout=3, metadata=metadata)
- assert error.value.code() == grpc.StatusCode.UNAUTHENTICATED
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.StartRun(start_request("S1", "unauthenticated-start"), timeout=3)
- assert error.value.code() == grpc.StatusCode.UNAUTHENTICATED
- metadata = (("authorization", "Bearer integration-only-token"),)
- info = await stub.GetSystemInfo(empty_pb2.Empty(), timeout=3, metadata=metadata)
- assert info.station_count == 4 and info.mode == "simulated"
- assert not (await stub.ListRuns(pb.ListRunsRequest(), timeout=3, metadata=metadata)).runs
- finally:
- bench.grpc_service.token = ""
- async def test_completed_history_artifacts_and_command_identity_survive_restart(tmp_path):
- settings = fast_settings(tmp_path)
- request = start_request("S1", "persisted-start", suffix="persistent")
- server, bench, port = await start_server(settings)
- channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
- try:
- stub = rpc.BenchServiceStub(channel)
- command = await stub.StartRun(request, timeout=3)
- run = await completed(stub, command.run_id)
- artifact = await upload_result(stub, run.run_id, upload_id="persisted-artifact")
- before = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
- assert before.run.verdict == "pass"
- finally:
- await channel.close()
- await server.stop(0)
- await bench.grpc_service.drain()
- await bench.close()
- server, bench, port = await start_server(settings)
- channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
- try:
- stub = rpc.BenchServiceStub(channel)
- after = await stub.GetRunReport(pb.RunKey(run_id=run.run_id), timeout=3)
- assert after.run.verdict == "pass" and after.run.supply_state == "off"
- assert after.run.recipe == before.run.recipe
- assert after.sol_bytes == before.sol_bytes and after.temperature_sample_count == before.temperature_sample_count
- assert [a.artifact_id for a in after.artifacts] == [artifact.artifact_id]
- history = await stub.ListRuns(pb.ListRunsRequest(sn="TEST-persistent-CPU1", limit=10), timeout=3)
- assert [r.run_id for r in history.runs] == [run.run_id]
- retried = await stub.StartRun(request, timeout=3)
- assert retried.run_id == run.run_id
- assert bench.runtimes["S1"].run is None
- finally:
- await channel.close()
- await server.stop(0)
- await bench.grpc_service.drain()
- await bench.close()
- async def test_result_for_another_run_cannot_turn_selected_run_into_pass(service):
- stub, _, _, _ = service
- command = await stub.StartRun(start_request("S1", "wrong-artifact-start"), timeout=3)
- await completed(stub, command.run_id)
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await upload_result(stub, command.run_id, result_bytes("R-another-run"), upload_id="wrong-run-result")
- assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
- report = await stub.GetRunReport(pb.RunKey(run_id=command.run_id), timeout=3)
- assert report.run.verdict == "pending" and not report.artifacts
- async def test_full_cli_demo_runs_four_stations_and_imports_simulated_pass_results(service):
- stub, _, endpoint, _ = service
- process = await asyncio.create_subprocess_exec(sys.executable, "-m", "stl_backend.cli",
- "--target", endpoint, "demo", "--wait-seconds", "30", "--interval", "0.2",
- stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
- try:
- stdout, stderr = await asyncio.wait_for(process.communicate(), 40)
- except BaseException:
- if process.returncode is None:
- process.kill()
- await process.wait()
- raise
- assert process.returncode == 0, stderr.decode(errors="replace")
- results = json.loads(stdout)
- assert len(results) == 4 and len({r["run_id"] for r in results}) == 4
- assert all(r["mode"] == "simulated" and r["verdict"] == "pass"
- and r["supply_state"] == "off" and r["artifact_state"] == "complete" for r in results)
- assert all(not s.run_id for s in (await stub.ListStations(empty_pb2.Empty(), timeout=3)).stations)
- async def test_competing_manual_confirmations_cannot_overwrite_the_first_claim(service, monkeypatch):
- stub, bench, _, settings = service
- settings["profiles"]["sim-cxmt"]["steps"][0]["manual"] = True
- command = await stub.StartRun(start_request("S1", "manual-claim-start"), timeout=3)
- waiting = await waiting_step(stub, "S1")
- entered, release = asyncio.Event(), asyncio.Event()
- original = bench.event
- async def hold_first_confirmation(rt, kind, *args, **kwargs):
- if kind == "manual_confirmation" and not entered.is_set():
- entered.set()
- await release.wait()
- return await original(rt, kind, *args, **kwargs)
- monkeypatch.setattr(bench, "event", hold_first_confirmation)
- first = await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="manual-confirm-first",
- run_id=command.run_id, step_id=waiting.pending_step_id, operator="operator-a",
- evidence="first confirmation evidence", succeeded=True), timeout=3)
- try:
- await asyncio.wait_for(entered.wait(), 3)
- try:
- other = await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="manual-confirm-conflict",
- run_id=command.run_id, step_id=waiting.pending_step_id, operator="operator-b",
- evidence="competing confirmation evidence", succeeded=False), timeout=3)
- except grpc.aio.AioRpcError as error:
- assert error.code() == grpc.StatusCode.FAILED_PRECONDITION
- else:
- # An implementation may reject at acceptance or in the durable
- # command worker. It must never apply the competing acknowledgement.
- assert (await command_done(stub, other.command_id)).state == "failed"
- finally:
- release.set()
- assert (await command_done(stub, first.command_id)).state == "succeeded"
- assert (await completed(stub, command.run_id)).state == "completed"
- async def test_target_change_is_rejected_until_initial_target_is_applied(service, monkeypatch):
- stub, bench, _, settings = service
- settings["profiles"]["sim-cxmt"]["steps"][0]["manual"] = True
- entered, release = asyncio.Event(), asyncio.Event()
- device = bench.runtimes["S1"].device
- original = device.set_target
- async def hold_initial_target(target):
- if not entered.is_set():
- entered.set()
- await release.wait()
- return await original(target)
- monkeypatch.setattr(device, "set_target", hold_initial_target)
- command = await stub.StartRun(start_request("S1", "target-init-start"), timeout=3)
- try:
- await asyncio.wait_for(entered.wait(), 3)
- with pytest.raises(grpc.aio.AioRpcError) as error:
- await stub.SetTargetTemperature(pb.SetTargetRequest(command_id="target-too-early",
- run_id=command.run_id, target_c=85, operator="test-operator"), timeout=3)
- assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION
- finally:
- release.set()
- waiting = await waiting_step(stub, "S1")
- changed = await stub.SetTargetTemperature(pb.SetTargetRequest(command_id="target-after-init",
- run_id=command.run_id, target_c=85, operator="test-operator"), timeout=3)
- result = await command_done(stub, changed.command_id)
- assert result.state == "succeeded" and result.result["applied_target_c"] == 85
- station = await stub.GetStation(pb.StationKey(station_id="S1"), timeout=3)
- assert station.temperature.requested_target_c == 85 and station.temperature.applied_target_c == 85
- await stub.ConfirmStage(pb.ConfirmStageRequest(command_id="target-step-confirm",
- run_id=command.run_id, step_id=waiting.pending_step_id, operator="test-operator",
- evidence="complete manual step after target change", succeeded=True), timeout=3)
- run = await completed(stub, command.run_id)
- assert run.state == "completed" and run.recipe.dimm_target_c == 80
- assert run.evidence["target_changes"][0]["applied_c"] == 85
- async def test_server_only_diagnostic_rpc_console_and_read_only_bmc_query(service):
- stub, bench, _, _ = service
- power = await stub.StationPower(pb.StationPowerRequest(command_id="diagnostic-supply",
- station_id="S1", action="supply_on", operator="test-operator"), timeout=3)
- assert (await command_done(stub, power.command_id)).state == "succeeded"
- query = await stub.QueryBmc(pb.BmcQueryRequest(station_id="S1", query="info"), timeout=3)
- assert query.mode == "simulated" and "SIMULATED BMC" in query.text and query.observed_unix_ms
- opened = await stub.SetDiagnosticSol(pb.SetDiagnosticSolRequest(command_id="diagnostic-open",
- station_id="S1", action="open", operator="test-operator"), timeout=3)
- assert (await command_done(stub, opened.command_id)).state == "succeeded"
- status = await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)
- assert status.state == "online" and status.phase == "unknown"
- power = await stub.StationPower(pb.StationPowerRequest(command_id="diagnostic-boot",
- station_id="S1", action="host_on", operator="test-operator"), timeout=3)
- assert (await command_done(stub, power.command_id)).state == "succeeded"
- async with asyncio.timeout(3):
- while (await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)).phase != "uip":
- await asyncio.sleep(0.01)
- sent = await stub.WriteDiagnosticSol(pb.WriteDiagnosticSolRequest(command_id="diagnostic-input",
- station_id="S1", session_id=status.session_id, data=b"help\r", operator="test-operator"), timeout=3)
- assert (await command_done(stub, sent.command_id)).state == "succeeded"
- read = await stub.ReadDiagnosticSol(pb.ReadDiagnosticSolRequest(station_id="S1",
- session_id=status.session_id, max_bytes=65536), timeout=3)
- assert b"Current stage is 1" in read.data
- assert bench.runtimes["S1"].device.sent_commands == [b"help\r"]
- assert not (await stub.ListRuns(pb.ListRunsRequest(), timeout=3)).runs
- closed = await stub.SetDiagnosticSol(pb.SetDiagnosticSolRequest(command_id="diagnostic-close",
- station_id="S1", action="close", operator="test-operator"), timeout=3)
- assert (await command_done(stub, closed.command_id)).state == "succeeded"
- assert (await stub.GetDiagnostic(pb.StationKey(station_id="S1"), timeout=3)).state == "closed"
- assert (await stub.GetStation(pb.StationKey(station_id="S1"), timeout=3)).server_power == "on"
- async def test_shared_queue_native_grpc_and_independent_event_consumers(service):
- stub, _, target, _ = service
- async def queue_done(command_id):
- async with asyncio.timeout(4):
- while True:
- item = await stub.GetQueueItem(pb.CommandKey(command_id=command_id), timeout=3)
- if item.state in ("succeeded", "failed", "interrupted"):
- return item
- await asyncio.sleep(.01)
- request = pb.EnqueueCommandRequest(command_id="native-queue-power", station_id="S1",
- method="StationPower", operator="native-ui-one", arguments={"action":"supply_on"})
- first = await stub.EnqueueCommand(request, timeout=3)
- assert (await queue_done(first.command_id)).state == "succeeded"
- channel2 = grpc.aio.insecure_channel(target)
- try:
- second_ui = rpc.BenchServiceStub(channel2)
- repeated = await second_ui.EnqueueCommand(request, timeout=3)
- assert repeated.sequence == first.sequence
- queued = await second_ui.EnqueueCommand(pb.EnqueueCommandRequest(command_id="native-queue-info",
- station_id="S1", method="QueryBmc", operator="native-ui-two", arguments={"query":"info"}), timeout=3)
- result = await queue_done(queued.command_id)
- assert result.state == "succeeded" and "SIMULATED" in result.result["text"]
- listing = await stub.GetQueue(pb.GetQueueRequest(station_id="S1", limit=100), timeout=3)
- assert [item.command_id for item in listing.items] == [queued.command_id, first.command_id]
- page1 = await stub.ReadEventQueue(pb.ReadEventQueueRequest(station_id="S1", limit=1000), timeout=3)
- page2 = await second_ui.ReadEventQueue(pb.ReadEventQueueRequest(station_id="S1", limit=1000), timeout=3)
- assert page1 == page2 and page1.events
- assert any(event.command_id == queued.command_id for event in page1.events)
- finally:
- await channel2.close()
|