| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313 |
- """Exercise the extracted services directly, without the Bench/gRPC facade."""
- from __future__ import annotations
- import asyncio
- import copy
- from pathlib import Path
- import pytest
- from stl_backend.application.acquisition import Acquisition
- from stl_backend.application.workflow import Workflow
- from stl_backend.config import load_settings
- from stl_backend.devices.base import DeviceError
- from stl_backend.domain.errors import StopRequested
- from stl_backend.domain.results import channel_key, evaluate_verdict
- from stl_backend.domain.station import Runtime, mark_powered_off, step_selected
- from stl_backend.parsers import IncrementalSolParser
- ROOT = Path(__file__).resolve().parents[1]
- def sample_run():
- return {
- "run_id": "R-layer-test", "station_id": "S1", "state": "running",
- "phase": "uip", "verdict": "pending", "artifact_state": "not_started",
- "recipe": {"run_rmt": True, "run_amt": False, "run_mt": False,
- "phase_timeout_s": 1, "finish_timeout_s": 1,
- "required_artifact_kinds": ["memtest_html"]},
- "profile_snapshot": {"steps": []}, "dimms": [],
- "tests": {"rmt": "completed", "amt": "skipped_by_recipe", "mt": "skipped_by_recipe"},
- "workflow_complete": True, "error_count": 0, "finished_unix_ms": 0,
- "hardware_snapshot": {"cpu_count": 2, "channels_per_cpu": 12},
- "evidence": {"sol_gap": False, "preheat_met": True, "target_changes": []},
- }
- class MemoryJournal:
- """Small recording dependency so services are tested without facade state."""
- def __init__(self):
- self.runs = []
- self.snapshots = []
- self.events = []
- async def save_run(self, run):
- self.runs.append(copy.deepcopy(run))
- async def publish(self, rt):
- self.snapshots.append(copy.deepcopy(rt.snapshot))
- async def event(self, rt, kind, severity, message, details=None, **extra):
- self.events.append({"kind": kind, "severity": severity, "message": message,
- "details": details or {}, **extra})
- async def phase(self, rt, phase):
- rt.snapshot["phase"] = phase
- rt.run["phase"] = phase
- await self.save_run(rt.run)
- async def artifacts(self, run_id):
- return []
- def make_services(tmp_path, device):
- settings = load_settings(ROOT / "config/simulated.json")
- rt = Runtime(settings["stations"][0], device=device)
- rt.attach_run(sample_run())
- journal = MemoryJournal()
- acquisition = Acquisition(settings, journal, tmp_path,
- save_run=journal.save_run, publish=journal.publish, event=journal.event)
- workflow = Workflow(settings, journal, tmp_path, asyncio.Lock(), acquisition,
- save_run=journal.save_run, publish=journal.publish,
- event=journal.event, phase=journal.phase)
- return rt, journal, acquisition, workflow
- def test_verdict_calculation_does_not_mutate_evidence_or_sum_sources():
- run = sample_run()
- run["evidence"]["sol_channel_error_counts"] = {"0:0": 2}
- artifacts = [{"artifact_id": "A-one", "kind": "memtest_html", "summary": {
- "verdict": "fail", "complete": True,
- "channel_error_counts": [{"cpu": 0, "channel": "A", "error_count": 3}],
- }}]
- before = copy.deepcopy((run, artifacts))
- result = evaluate_verdict(run, artifacts)
- assert (run, artifacts) == before
- assert result["verdict"] == "fail"
- assert result["evidence"]["channel_error_counts"] == {"0:0": 3}
- assert result["evidence"]["channel_error_counts_by_source"] == {
- "sol": {"0:0": 2}, "artifact:A-one": {"0:0": 3},
- }
- result["evidence"]["target_changes"].append({"requested_c": 70})
- assert run["evidence"]["target_changes"] == []
- @pytest.mark.parametrize("complete,gap,errors,artifact_verdict,expected,artifact_state", [
- (True, False, 0, None, "pending", "pending_import"),
- (True, False, 0, "pass", "pass", "complete"),
- (True, False, 0, "unknown", "inconclusive", "partial"),
- (True, True, 0, "pass", "inconclusive", "complete"),
- (False, False, 0, "pass", "inconclusive", "complete"),
- (False, True, 1, None, "fail", "pending_import"),
- ])
- def test_result_rules_preserve_failure_and_require_complete_evidence(
- complete, gap, errors, artifact_verdict, expected, artifact_state):
- run = sample_run()
- run.update(workflow_complete=complete, error_count=errors, finished_unix_ms=100)
- run["tests"]["mt"] = "completed"
- run["evidence"]["sol_gap"] = gap
- artifacts = [] if artifact_verdict is None else [{
- "artifact_id": "A-result", "kind": "memtest_html",
- "summary": {"complete": True, "verdict": artifact_verdict},
- }]
- result = evaluate_verdict(run, artifacts)
- assert result["verdict"] == expected
- assert result["artifact_state"] == artifact_state
- @pytest.mark.parametrize("details,expected", [
- ({"cpu": 1, "channel": "CH11"}, "1:11"),
- ({"cpu": True, "channel": "A"}, None),
- ({"cpu": 255, "channel": "A"}, None),
- ({"cpu": 0, "channel": 255}, None),
- ({"channel": "A"}, None),
- ])
- def test_channel_key_uses_observed_valid_topology(details, expected):
- assert channel_key(details, sample_run()) == expected
- def test_new_run_drops_old_console_and_temperature_observations():
- cfg = load_settings(ROOT / "config/simulated.json")["stations"][0]
- device = object()
- rt = Runtime(cfg, {"last_run_id": "R-old", "revision": 9}, device=device)
- assert rt.device is device
- assert rt.snapshot["last_run_id"] == "R-old"
- assert rt.snapshot["revision"] == 9
- rt.stop.set()
- rt.auto.clear()
- rt.uefi_ready = True
- rt.error = "old transport error"
- rt.window, rt.window_start, rt.cursor = "old console", 10, 20
- rt.observed_markers = {"old": {"text": "old evidence", "end": 20}}
- rt.sol_temperatures = {(0, "0", "A1"): {"value_c": 80, "quality": "valid"}}
- rt.snapshot.update(progress_percent=90, progress_phase="mt", progress_observed_unix_ms=123)
- rt.decoder.decode(b"\xe6") # An unfinished UTF-8 sequence must not cross runs.
- old_parser = rt.parser
- run = sample_run()
- run["profile_snapshot"]["steps"] = [
- {"id": "cpu1", "expect": "CPU1 UIP", "expect_from_start": True},
- {"id": "optional-amt", "when": "amt", "expect": "AMT", "expect_from_start": True},
- ]
- rt.attach_run(run)
- assert rt.run is run
- assert not rt.stop.is_set() and rt.auto.is_set()
- assert not rt.uefi_ready and not rt.error
- assert (rt.window, rt.window_start, rt.cursor) == ("", 0, 0)
- assert rt.observed_markers == {} and rt.sol_temperatures == {}
- assert list(rt.marker_patterns) == ["cpu1"]
- assert rt.decoder.decode(b"list") == "list"
- assert rt.parser is not old_parser
- assert len(rt.snapshot["temperature"]["dimms"]) == 24
- assert all("value_c" not in x for x in rt.snapshot["temperature"]["dimms"])
- assert "progress_percent" not in rt.snapshot
- assert rt.snapshot["progress_phase"] == ""
- assert rt.snapshot["progress_observed_unix_ms"] == 0
- assert step_selected({"when": "not_amt"}, run["recipe"])
- async def test_progress_keeps_actual_source_and_drops_previous_firmware_phase(tmp_path, monkeypatch):
- rt, journal, acquisition, _ = make_services(tmp_path, object())
- rt.snapshot["phase"] = "bios_config" # Workflow phase is not the tool phase.
- monkeypatch.setattr("stl_backend.application.acquisition.now_ms", lambda: 1234)
- await acquisition.parsed_event(rt, {
- "kind": "progress", "phase": "rmt", "message": "100%",
- "details": {"percent": 100},
- })
- assert rt.snapshot["progress_percent"] == 100
- assert rt.snapshot["progress_phase"] == "rmt"
- assert rt.snapshot["progress_observed_unix_ms"] == 1234
- await acquisition.parsed_event(rt, {
- "kind": "stage", "phase": "rmt", "message": "RMT done", "details": {},
- })
- assert rt.snapshot["progress_percent"] == 100 # Same source phase retained.
- await acquisition.parsed_event(rt, {
- "kind": "prompt", "phase": "uefi", "message": "Shell>", "details": {},
- })
- assert "progress_percent" not in rt.snapshot
- assert rt.snapshot["progress_phase"] == ""
- assert rt.snapshot["progress_observed_unix_ms"] == 0
- monkeypatch.setattr("stl_backend.application.acquisition.now_ms", lambda: 5678)
- await acquisition.parsed_event(rt, {
- "kind": "progress", "phase": "mt", "message": "0%",
- "details": {"percent": 0},
- })
- assert rt.snapshot["progress_percent"] == 0 # Zero is an actual observation.
- assert rt.snapshot["progress_phase"] == "mt"
- assert rt.snapshot["progress_observed_unix_ms"] == 5678
- assert journal.events[-1]["phase"] == "mt"
- async def test_run_events_expose_same_algorithm_projection_without_inventing_percent(tmp_path):
- rt, journal, acquisition, _ = make_services(tmp_path, object())
- rt.snapshot["sol_state"] = "online"
- raw = (ROOT / "tests/fixtures/live_amemdiag_algorithms_20261023.log").read_bytes()
- for event in rt.parser.feed(raw):
- await acquisition.parsed_event(rt, event)
- rows = journal.events[-1]["details"]["algorithm_progress"]
- assert [(row["cpu"], row["completed_count"], row["algorithm_index"]) for row in rows] == [(0, 8, 9), (1, 8, 9)]
- assert all(row["state"] == "running" and row["live"] for row in rows)
- assert "progress_percent" not in rt.snapshot
- assert rt.run["verdict"] == "pending" and rt.run["error_count"] == 0
- rt.snapshot["sol_state"] = "offline"
- event = IncrementalSolParser().feed(b"[0][AMEMDIAG 1/1 1/1 10/19] Algo A-MD2 Start...\n")[0]
- await acquisition.parsed_event(rt, event)
- assert all(row["state"] == "unknown" and not row["live"]
- for row in journal.events[-1]["details"]["algorithm_progress"])
- rt.attach_run(sample_run())
- assert rt.algorithm_progress.snapshot() == []
- async def test_acquisition_retains_raw_bytes_and_forwards_evidence_without_bench(tmp_path):
- raw = (b"\xffraw prefix\r\n[0][CxmtDdrTest]Current stage is 1\r\n"
- b"[HD_RMTSensor]N0.C0.D0:42.5\r\n")
- class Console:
- async def sol_read(self):
- for start in range(0, len(raw), 7):
- yield raw[start:start + 7]
- rt, journal, acquisition, _ = make_services(tmp_path, Console())
- path = tmp_path / "runs" / rt.run["run_id"] / "sol.raw"
- path.parent.mkdir(parents=True)
- rt.finishing = True # This capture ends normally while draining the device.
- rt.snapshot["sol_state"] = "online"
- await acquisition.sol_reader(rt)
- assert path.read_bytes() == raw
- assert not rt.run["evidence"]["sol_gap"]
- assert any(event["kind"] == "stage" and event["phase"] == "uip" for event in journal.events)
- assert any(event["kind"] == "dimm_temperature" for event in journal.events)
- assert rt.snapshot["temperature"]["dimms"][0]["quality"] == "unavailable_in_phase"
- rt.uefi_ready = True
- acquisition.merge_sol_temperatures(rt)
- assert rt.snapshot["temperature"]["dimms"][0]["quality"] == "unavailable_in_phase"
- for event in IncrementalSolParser().feed(b"UEFI Interactive Shell v2.2\nShell> \n"):
- await acquisition.parsed_event(rt, event)
- await acquisition.parsed_event(rt, {
- "kind": "dimm_temperature", "phase": "uefi", "message": "new sample",
- "details": {"cpu": 0, "channel": "0", "dimm": 0, "temperature_c": 43.0},
- })
- assert rt.snapshot["temperature"]["dimms"][0]["quality"] == "valid"
- assert rt.snapshot["temperature"]["dimms"][0]["value_c"] == 43.0
- async def test_controlled_operation_is_cancelled_before_stop_returns(tmp_path):
- rt, _, _, workflow = make_services(tmp_path, object())
- started, cancelled = asyncio.Event(), asyncio.Event()
- async def slow_device_call():
- started.set()
- try:
- await asyncio.Event().wait()
- finally:
- cancelled.set()
- task = asyncio.create_task(workflow.controlled(rt, slow_device_call(), 5))
- await asyncio.wait_for(started.wait(), 1)
- rt.stop.set()
- with pytest.raises(StopRequested):
- await asyncio.wait_for(task, 1)
- assert cancelled.is_set()
- async def test_finish_attempts_whole_station_off_after_host_power_error(tmp_path):
- class FailedHostOff:
- simulated = True
- def __init__(self):
- self.calls = []
- async def bmc_power(self, action):
- self.calls.append(("host", action))
- raise DeviceError("host power controller unavailable")
- async def supply_set(self, on):
- self.calls.append(("supply", on))
- return "off"
- async def sol_close(self):
- self.calls.append(("sol", "close"))
- device = FailedHostOff()
- rt, journal, _, workflow = make_services(tmp_path, device)
- run = rt.run
- run["workflow_complete"] = False
- run["tests"]["rmt"] = "running"
- await workflow.finalize(rt, "operator_stopped")
- assert device.calls == [("host", "off"), ("supply", False), ("sol", "close")]
- assert rt.run is None
- assert run["state"] == "stopped" and run["verdict"] == "inconclusive"
- assert run["tests"]["rmt"] == "interrupted"
- assert rt.snapshot["supply_state"] == "off"
- assert rt.snapshot["temperature"]["dimm_quality"] == "powered_off"
- assert journal.runs[-1]["artifact_state"] == "complete"
- assert any(event["kind"] == "run_finished" for event in journal.events)
- def test_confirmed_power_off_keeps_last_reading_but_marks_it_unavailable():
- cfg = load_settings(ROOT / "config/simulated.json")["stations"][0]
- rt = Runtime(cfg, device=object())
- rt.snapshot["temperature"]["dimms"] = [{"value_c": 80, "quality": "valid"}]
- mark_powered_off(rt)
- assert rt.snapshot["temperature"]["dimms"] == [{"value_c": 80, "quality": "powered_off"}]
|