diff --git a/pyproject.toml b/pyproject.toml index f840617..f46f097 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ name = "webapi" version = "0.0.0" description = "FastAPI: FHIR routes, control routes, the auth dependency." requires-python = ">=3.12" -dependencies = ["core", "persistance", "fastapi[standard]", "dagster-graphql"] +dependencies = ["core", "persistance", "fastapi[standard]", "dagster-graphql", "requests"] [build-system] requires = ["uv_build>=0.12,<0.13"] diff --git a/tests/test_runs.py b/tests/test_runs.py new file mode 100644 index 0000000..59c2f9c --- /dev/null +++ b/tests/test_runs.py @@ -0,0 +1,204 @@ +"""Run shaping and the API's Dagster-backed run and execution routes.""" + +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 _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): + """Capture the Dagster port chosen by the shared API fixture for its first process.""" + 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" + assert options["schedulers"] == [] + health = _ok(api.get("/execution/health", params={"mode": "local"})) + assert health["reachable"] is True + assert health["workers"] >= 1 + 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 diff --git a/webapi/eeg.py b/webapi/eeg.py index 2e17b91..d11e521 100644 --- a/webapi/eeg.py +++ b/webapi/eeg.py @@ -1,10 +1,13 @@ """TEA's EEGs for model governance: every study with its analysis verdict, and one study's metrics with their age curves' scores.""" -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from persistance import eeg +from persistance.cluster import Execution +from persistance.eeg import Scope +from webapi.runs import dagster, execution_config, submit router = APIRouter(prefix="/tea/eegs", tags=["eeg"]) @@ -35,11 +38,23 @@ class Analysis(BaseModel): metrics: list[Metric] +class AnalyzeRequest(BaseModel): + scope: Scope = Scope() + execution: Execution | None = None + + @router.get("") def studies() -> list[Study]: return [Study(**s) for s in eeg.studies()] +@router.post("/analyze") +def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str, str]: + """Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.""" + config = {"scope": request.scope.model_dump(), "execution": execution_config(request.execution)} + return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea") + + @router.get("/{eeg_id}") def study(eeg_id: str) -> Analysis: if (found := eeg.study(eeg_id)) is None: diff --git a/webapi/execution.py b/webapi/execution.py new file mode 100644 index 0000000..9ef502f --- /dev/null +++ b/webapi/execution.py @@ -0,0 +1,23 @@ +"""The execution choices a deployment offers and the health of a chosen cluster.""" + +from fastapi import APIRouter, HTTPException + +from persistance import cluster +from persistance.cluster import Execution, Health, Mode, Options + +router = APIRouter(prefix="/execution", tags=["execution"]) + + +@router.get("/options") +def execution_options() -> Options: + return cluster.options() + + +@router.get("/health") +def execution_health( + mode: Mode | None = None, scheduler: str | None = None, reference: str | None = None +) -> Health: + try: + return cluster.health(Execution(mode=mode, scheduler=scheduler), reference) + except cluster.ExecutionError as e: + raise HTTPException(422, detail=str(e)) from e diff --git a/webapi/main.py b/webapi/main.py index cbca1a2..62b09f5 100644 --- a/webapi/main.py +++ b/webapi/main.py @@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler from starlette.exceptions import HTTPException from core.domains import Domain -from webapi import eeg, fhir, ingest, models, review, runs +from webapi import eeg, execution, fhir, ingest, models, review, runs from webapi.auth import caller app = FastAPI( @@ -15,6 +15,7 @@ app = FastAPI( app.include_router(ingest.router) app.include_router(review.router) app.include_router(runs.router) +app.include_router(execution.router) app.include_router(models.router) app.include_router(eeg.router) app.include_router(fhir.router) diff --git a/webapi/models.py b/webapi/models.py index 1fab3cd..78214f9 100644 --- a/webapi/models.py +++ b/webapi/models.py @@ -4,14 +4,15 @@ scoring runs (Dagster). The API starts runs and reads the registry; it never tra import mimetypes from datetime import date -from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError +from dagster_graphql import DagsterGraphQLClient from fastapi import APIRouter, Depends, HTTPException, UploadFile from fastapi.responses import Response from pydantic import BaseModel from core.domains import Domain from persistance import registry -from webapi.runs import dagster +from persistance.cluster import Execution +from webapi.runs import dagster, execution_config, submit router = APIRouter(prefix="/models", tags=["models"]) @@ -76,36 +77,38 @@ def promote(domain: Domain, name: str, version: int) -> dict: class Training(BaseModel): as_of: date | None = None # the date the data are taken up to (default: today) models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence) + execution: Execution | None = None -def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]: - try: - run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}}) - except DagsterGraphQLClientError as e: - raise HTTPException(502, detail=str(e)) from e - return {"run_id": run_id} +class Analyze(BaseModel): + execution: Execution | None = None @router.post("/{domain}/train") def train(domain: Domain, request: Training, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip """Starts training a new version of every model of the domain; follow it at /runs.""" - config: dict = {"domain": domain.value} + config: dict = {"domain": domain.value, "execution": execution_config(request.execution)} if request.as_of: config["as_of"] = request.as_of.isoformat() if request.models: config["models"] = request.models - return _submit(client, "train", "train_models", config) + return submit(client, "train", "train_models", config, domain=domain.value) @router.post("/{domain}/analyze") -def analyze(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: +def analyze( + domain: Domain, + request: Analyze = Analyze(), # noqa: B008 + client: DagsterGraphQLClient = Depends(dagster), +) -> dict[str, str]: """Starts analysing the studies the domain's models read whole (TEA: its EEGs); follow it at /runs.""" - return _submit(client, "analyze", "analyze_studies", {"domain": domain.value}) + config = {"domain": domain.value, "execution": execution_config(request.execution)} + return submit(client, "analyze", "analyze_studies", config, domain=domain.value) @router.post("/{domain}/score") def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: """Starts a risk batch from each model's champion; follow it at /runs.""" - return _submit(client, "score", "score_models", {"domain": domain.value}) + return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value) diff --git a/webapi/runs.py b/webapi/runs.py index cc5888e..5f6e397 100644 --- a/webapi/runs.py +++ b/webapi/runs.py @@ -1,23 +1,254 @@ """Runs live in Dagster: the API starts them and reads their state, never computes.""" import os +from typing import Literal +import requests from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, ValidationError + +from core.domains import Domain +from persistance import cluster +from persistance.cluster import Execution, Progress router = APIRouter(prefix="/runs", tags=["runs"]) +State = Literal["queued", "running", "succeeded", "failed", "cancelling", "cancelled"] +STATE: dict[str, State] = { + "QUEUED": "queued", + "NOT_STARTED": "queued", + "MANAGED": "queued", + "STARTING": "running", + "STARTED": "running", + "CANCELING": "cancelling", + "CANCELED": "cancelled", + "SUCCESS": "succeeded", + "FAILURE": "failed", +} + +RUN_QUERY = """ +query Run($id: ID!) { + runOrError(runId: $id) { + __typename + ... on Run { runId jobName status startTime endTime tags { key value } + stepStats { stepKey status startTime endTime } } + ... on RunNotFoundError { message } + ... on PythonError { message } + } + logsForRun(runId: $id, limit: 5000) { + __typename + ... on EventConnection { events { __typename + ... on MessageEvent { message level stepKey } + ... on ExecutionStepFailureEvent { error { message causes { message } } } + ... on RunFailureEvent { error { message causes { message } } } } } + ... on RunNotFoundError { message } + ... on PythonError { message } + } +} +""" + +RUNS_QUERY = """ +query Runs($filter: RunsFilter, $cursor: String, $limit: Int) { + runsOrError(filter: $filter, cursor: $cursor, limit: $limit) { + __typename + ... on Runs { results { runId jobName status startTime endTime tags { key value } } } + ... on InvalidPipelineRunsFilterError { message } + ... on PythonError { message } + } +} +""" + + +class RunSummary(BaseModel): + id: str + job: str + domain: str | None + status: str + state: State + started: float | None + ended: float | None + + +class Step(BaseModel): + key: str + status: str + started: float | None + ended: float | None + + +class Run(RunSummary): + progress: Progress | None + steps: list[Step] + info: list[str] + warnings: list[str] + error: str | None + + +class Cancel(BaseModel): + id: str + status: str + state: State + + +def _dagster_address() -> tuple[str, int]: + return os.environ.get("DAGSTER_HOST", "localhost"), int(os.environ.get("DAGSTER_PORT", "3000")) + def dagster() -> DagsterGraphQLClient: - return DagsterGraphQLClient( - os.environ.get("DAGSTER_HOST", "localhost"), - port_number=int(os.environ.get("DAGSTER_PORT", "3000")), + host, port = _dagster_address() + return DagsterGraphQLClient(host, port_number=port) + + +def graphql(query: str, variables: dict) -> dict: + host, port = _dagster_address() + try: + response = requests.post( + f"http://{host}:{port}/graphql", + json={"query": query, "variables": variables}, + timeout=15, + ) + if response.status_code != 200: + raise HTTPException(502, detail=response.text) + payload = response.json() + except requests.RequestException as e: + raise HTTPException(502, detail=str(e)) from e + if "errors" in payload: + raise HTTPException(502, detail=str(payload["errors"])) + return payload["data"] + + +def _tags(run: dict) -> dict[str, str]: + return {tag["key"]: tag["value"] for tag in run.get("tags", [])} + + +def _summary(run: dict) -> RunSummary: + status = run["status"] + return RunSummary( + id=run["runId"], + job=run["jobName"], + domain=_tags(run).get("domain"), + status=status, + state=STATE.get(status, "running"), + started=run.get("startTime"), + ended=run.get("endTime"), ) +def shape(run: dict, logs: list[dict]) -> Run: + summary = _summary(run) + progress = None + if (tag := _tags(run).get("isssteleon/progress")) is not None: + try: + progress = Progress.model_validate_json(tag) + except ValidationError: + pass + + steps = [ + Step( + key=step["stepKey"], + status=step["status"], + started=step.get("startTime"), + ended=step.get("endTime"), + ) + for step in run.get("stepStats", []) + ] + steps.sort(key=lambda step: (step.started is None, step.started or 0.0)) + + info, warnings = [], [] + error = None + for event in logs: + kind = event["__typename"] + if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"): + line = event["message"] + if step_key := event.get("stepKey"): + line = f"{step_key}: {line}" + (info if event["level"] == "INFO" else warnings).append(line) + if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"): + failure = event.get("error") + error = None + if failure: + causes = failure.get("causes") + message = (causes[-1] if causes else failure)["message"] + lines = message.strip().splitlines() + error = lines[0][:500] if lines else None + + return Run( + **summary.model_dump(), + progress=progress, + steps=steps, + info=info[-200:], + warnings=warnings[:200], + error=(error or "the run failed") if summary.state == "failed" else None, + ) + + +def _result(result: dict, typename: str) -> dict: + if result["__typename"] != typename: + status = 404 if result["__typename"] == "RunNotFoundError" else 502 + raise HTTPException(status, detail=result.get("message", result["__typename"])) + return result + + @router.get("/{run_id}") -def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: +def run_status(run_id: str) -> Run: + data = graphql(RUN_QUERY, {"id": run_id}) + run = _result(data["runOrError"], "Run") + logs = _result(data["logsForRun"], "EventConnection") + return shape(run, logs["events"]) + + +def _status(client: DagsterGraphQLClient, run_id: str) -> str: try: - return {"id": run_id, "status": client.get_run_status(run_id).value} + return client.get_run_status(run_id).value except DagsterGraphQLClientError as e: - raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e + raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e + + +@router.post("/{run_id}/cancel") +def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel: + status = _status(client, run_id) + if status in ("SUCCESS", "FAILURE", "CANCELED"): + raise HTTPException(409, detail=f"the run already ended: {STATE[status]}") + try: + client.terminate_run(run_id) + except DagsterGraphQLClientError as e: + raise HTTPException(502, detail=str(e)) from e + status = _status(client, run_id) + return Cancel(id=run_id, status=status, state=STATE.get(status, "running")) + + +@router.get("") +def run_history( + job: str | None = None, + domain: Domain | None = None, + limit: int = Query(50, ge=1, le=200), + before: str | None = None, +) -> list[RunSummary]: + filters = {} + if job is not None: + filters["pipelineName"] = job + if domain is not None: + filters["tags"] = [{"key": "domain", "value": domain.value}] + data = graphql(RUNS_QUERY, {"filter": filters, "cursor": before, "limit": limit}) + return [_summary(run) for run in _result(data["runsOrError"], "Runs")["results"]] + + +def submit( + client: DagsterGraphQLClient, job: str, op: str, config: dict, domain: str +) -> dict[str, str]: + try: + run_id = client.submit_job_execution( + job, run_config={"ops": {op: {"config": config}}}, tags={"domain": domain} + ) + except DagsterGraphQLClientError as e: + raise HTTPException(502, detail=str(e)) from e + return {"run_id": run_id} + + +def execution_config(choice: Execution | None) -> dict: + try: + resolved = cluster.resolve(choice) + except cluster.ExecutionError as e: + raise HTTPException(422, detail=str(e)) from e + return {"mode": resolved.mode, "scheduler": resolved.scheduler}