Files
WebApi/tests/test_runs.py
T
alberto ec5d945f71 Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
1. No prose in code
- Remove parity-added Python comments and docstrings across the EEG, FHIR,
  execution, preview, training and run code and tests. Preserve endpoint
  descriptions as explicit FastAPI schema metadata.

2. No hacks, no glued code
- Read the declared TEA patient filters and training inputs directly and
  use the same TEA check for exposing and validating reference options.
- Give the Dagster GraphQL request one helper. Keep lock backoff and
  cancellation polling because their timing and error behavior are
  covered by run tests and they handle different Dagster states.
- Use the renamed FHIR report ID helper in the hospital test. Keep
  TEA_GATE_SLOW local to that test and preserve the test assertions.

3. Everything in its place
- Keep endpoint and run handling in WebApi and reuse Core and Persistance
  for domain rules and reads. Leave tests in the existing testpaths.
2026-11-30 13:41:49 -06:00

283 lines
9.6 KiB
Python

import os
import time
import pytest
import yaml
import conftest
from persistance.cluster import Progress
from webapi.runs import STATE, graphql, shape
PAYLOAD = {
"runId": "run",
"jobName": "analyze",
"status": "SUCCESS",
"startTime": 1.0,
"endTime": 4.0,
"tags": [{"key": "domain", "value": "cacu"}],
}
def test_shape_splits_info_and_warnings():
def event(level, message, step_key=None, kind="LogMessageEvent"):
return {"__typename": kind, "level": level, "message": message, "stepKey": step_key}
run = shape(
PAYLOAD,
[
event("INFO", "starting"),
event("WARNING", "skipped", "analyze_studies"),
event("DEBUG", "debug"),
event("INFO", "engine", kind="EngineEvent"),
event("INFO", "finished", "analyze_studies"),
],
)
assert run.info == ["starting", "analyze_studies: finished"]
assert run.warnings == ["analyze_studies: skipped"]
assert run.error is None
warning_only = shape(PAYLOAD, [event("WARNING", "skipped")])
assert warning_only.state == "succeeded"
assert warning_only.error is None
steps = [
{"stepKey": "waiting", "status": "SKIPPED", "startTime": None, "endTime": None},
{"stepKey": "second", "status": "SUCCESS", "startTime": 2, "endTime": 4},
{"stepKey": "first", "status": "SUCCESS", "startTime": 0, "endTime": 1},
]
assert [step.key for step in shape(PAYLOAD | {"stepStats": steps}, []).steps] == [
"first", "second", "waiting",
] # fmt: skip
capped = shape(
PAYLOAD, [event(level, str(i)) for i in range(201) for level in ("INFO", "WARNING")]
)
assert capped.info == [str(i) for i in range(1, 201)]
assert capped.warnings == [str(i) for i in range(200)]
def test_shape_failure_message_is_the_ops_own_exception():
failed = PAYLOAD | {"status": "FAILURE"}
step_failure = {
"__typename": "ExecutionStepFailureEvent",
"error": {
"message": "DagsterExecutionStepExecutionError: invocation failed",
"causes": [
{"message": "intermediate cause"},
{"message": " LookupError: no EEG x|2026-01-01\nmore details "},
],
},
}
assert shape(failed, [step_failure]).error == "LookupError: no EEG x|2026-01-01"
run_failure = {"__typename": "RunFailureEvent", "error": {"message": "x" * 501}}
assert shape(failed, [step_failure, run_failure]).error == "x" * 500
assert shape(failed, []).error == "the run failed"
def test_shape_progress_tag():
progress = Progress(
phase="analyzing", done=3, total=6, elapsed_s=4, eta_s=4, mode="sync",
scheduler=None, updated_at="2026-01-01T00:00:00Z",
) # fmt: skip
def with_tag(value):
return PAYLOAD | {"tags": [{"key": "isssteleon/progress", "value": value}]}
run = shape(with_tag(progress.model_dump_json()), [])
assert run.progress is not None
assert run.progress.done == 3
assert run.progress.phase == "analyzing"
assert shape(with_tag("{bad json"), []).progress is None
for status, state in STATE.items():
run = shape(PAYLOAD | {"status": status}, [])
assert (run.status, run.state) == (status, state)
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
def test_shape_outputs():
events = [
{
"__typename": "ExecutionStepOutputEvent",
"stepKey": "preview_study",
"outputName": "result",
"metadataEntries": [
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
{"label": "text"},
],
},
]
assert shape(PAYLOAD, events, outputs=True).outputs == {
"preview_study.result": {"eeg": {"valid": False}}
}
assert shape(PAYLOAD, events, outputs=False).outputs is None
def _ok(response):
assert response.status_code == 200, response.text
return response.json()
@pytest.fixture
def failed_run(api):
run_id = _ok(api.post("/models/cacu/analyze"))["run_id"]
deadline = time.monotonic() + 120
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] != "failed":
assert time.monotonic() < deadline, run
time.sleep(1)
return run
def test_unknown_run_is_404(api):
assert api.get("/runs/does-not-exist").status_code == 404
assert api.post("/runs/does-not-exist/cancel").status_code == 404
def test_failed_run_reports_its_error(failed_run):
assert failed_run["status"] == "FAILURE"
assert "analyze" in failed_run["error"]
assert isinstance(failed_run["info"], list)
assert isinstance(failed_run["warnings"], list)
assert any(
step["key"] == "analyze_studies" and step["status"] == "FAILURE"
for step in failed_run["steps"]
)
assert failed_run["domain"] == "cacu"
assert failed_run["job"] == "analyze"
def test_history_filters_by_job_and_domain(api, failed_run):
run_id = failed_run["id"]
history = _ok(api.get("/runs", params={"job": "analyze", "domain": "cacu"}))
assert run_id in {run["id"] for run in history}
for params in ({"job": "train"}, {"domain": "tea"}):
assert run_id not in {run["id"] for run in _ok(api.get("/runs", params=params))}
another_id = _ok(api.post("/models/cacu/analyze"))["run_id"]
page = _ok(api.get("/runs", params={"limit": 1}))
assert [run["id"] for run in page] == [another_id]
page = _ok(api.get("/runs", params={"limit": 1, "before": another_id}))
assert [run["id"] for run in page] == [run_id]
def test_cancel_a_finished_run_is_409(api, failed_run):
response = api.post(f"/runs/{failed_run['id']}/cancel")
assert response.status_code == 409
assert response.json()["detail"] == "the run already ended: failed"
@pytest.fixture
def api_with_dagster_address(platform, request, monkeypatch):
ports = []
free_port = conftest._free_port
def record_port():
port = free_port()
ports.append(port)
return port
monkeypatch.setattr(conftest, "_free_port", record_port)
api = request.getfixturevalue("api")
monkeypatch.setenv("DAGSTER_HOST", "127.0.0.1")
monkeypatch.setenv("DAGSTER_PORT", str(ports[0]))
return api
def test_run_requests_validate_the_execution_choice(api_with_dagster_address):
api = api_with_dagster_address
path = "/models/tea/analyze"
for execution in (
{"mode": "remote", "scheduler": "tcp://evil:8786"},
{"mode": "local", "scheduler": "tcp://x:8786"},
):
assert api.post(path, json={"execution": execution}).status_code == 422
run_id = _ok(api.post(path, json={"execution": {"mode": "sync"}}))["run_id"]
data = graphql(
"""
query RunConfig($id: ID!) {
runOrError(runId: $id) { ... on Run { runConfigYaml } }
}
""",
{"id": run_id},
)
config = yaml.safe_load(data["runOrError"]["runConfigYaml"])
assert config["ops"]["analyze_studies"]["config"]["execution"]["mode"] == "sync"
def test_execution_options_and_health(api):
options = _ok(api.get("/execution/options"))
assert options["default_mode"] == "sync"
configured = [s for s in os.environ.get("DASK_SCHEDULERS", "").split(",") if s]
assert options["schedulers"] == configured
health = _ok(api.get("/execution/health", params={"mode": "local"}))
assert health["reachable"] is True
assert health["workers"] >= 1
if configured:
remote = {"mode": "remote", "scheduler": configured[0]}
health = _ok(api.get("/execution/health", params=remote))
assert health["reachable"] is True
assert health["workers"] == int(os.environ.get("DASK_EXPECTED_WORKERS", "1"))
else:
assert api.get("/execution/health", params={"mode": "remote"}).status_code == 422
assert api.get("/execution/health?mode=sync&reference=..%2Fx").status_code == 422
def test_tea_eegs_analyze_validates_scope(api):
response = api.post("/tea/eegs/analyze", json={"scope": {"mode": "first_n"}})
assert response.status_code == 422
def test_a_locked_run_storage_is_read_again(monkeypatch):
from fastapi import HTTPException
from webapi import runs
error = {"__typename": "PythonError", "message": "OperationalError: database is locked"}
locked = {"data": {"runOrError": {"__typename": "Run"}, "logsForRun": error}}
fine = {
"data": {
"runOrError": {"__typename": "Run"},
"logsForRun": {"__typename": "EventConnection"},
}
}
answers = [locked, locked, fine]
class Answer:
status_code = 200
def __init__(self, payload):
self.payload = payload
def json(self):
return self.payload
monkeypatch.setattr(runs.time, "sleep", lambda s: None)
monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(answers.pop(0)))
assert runs.graphql("q", {}) == fine["data"]
monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(locked))
with pytest.raises(HTTPException) as raised:
runs.graphql("q", {})
assert raised.value.status_code == 503
def test_cancel_waits_for_a_starting_run(monkeypatch):
from webapi import runs
statuses = iter(["STARTING", "STARTING", "STARTED", "CANCELING"])
terminated = []
class Client:
def get_run_status(self, run_id):
class S:
value = next(statuses)
return S()
def terminate_run(self, run_id):
terminated.append(run_id)
monkeypatch.setattr(runs.time, "sleep", lambda s: None)
answer = runs.cancel_run("r1", client=Client())
assert terminated == ["r1"]
assert answer.status == "CANCELING"