Files
WebApi/webapi/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

300 lines
9.5 KiB
Python

"""Runs live in Dagster: the API starts them and reads their state, never computes."""
import json
import os
import time
from typing import Any, Literal
import requests
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
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!, $outputs: Boolean! = false) {
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 ExecutionStepOutputEvent @include(if: $outputs) {
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
}
... 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
outputs: dict[str, Any] | None = 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:
host, port = _dagster_address()
return DagsterGraphQLClient(host, port_number=port)
LOCKED = "database is locked"
LOCK_RETRIES = 5
STARTING_WAIT_S = 30
def _locked(payload: dict) -> bool:
results = (payload.get("data") or {}).values()
return LOCKED in str(payload.get("errors", "")) or any(
isinstance(r, dict)
and r.get("__typename") == "PythonError"
and LOCKED in r.get("message", "")
for r in results
)
def _graphql_response(url: str, query: str, variables: dict) -> dict:
try:
response = requests.post(url, json={"query": query, "variables": variables}, timeout=15)
if response.status_code != 200:
raise HTTPException(502, detail=response.text)
return response.json()
except requests.RequestException as e:
raise HTTPException(502, detail=str(e)) from e
def graphql(query: str, variables: dict) -> dict:
host, port = _dagster_address()
url = f"http://{host}:{port}/graphql"
payload = _graphql_response(url, query, variables)
for attempt in range(LOCK_RETRIES):
if not _locked(payload):
break
time.sleep(0.2 * 2**attempt)
payload = _graphql_response(url, query, variables)
if _locked(payload):
raise HTTPException(
503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"}
)
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], outputs: bool = False) -> 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
result = {} if outputs else 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 result is not None and kind == "ExecutionStepOutputEvent":
for entry in event.get("metadataEntries", ()):
if "jsonString" in entry:
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
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,
outputs=result,
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, outputs: bool = False) -> Run:
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
run = _result(data["runOrError"], "Run")
logs = _result(data["logsForRun"], "EventConnection")
return shape(run, logs["events"], outputs)
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
try:
return client.get_run_status(run_id).value
except DagsterGraphQLClientError as 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)
deadline = time.monotonic() + STARTING_WAIT_S
while status == "STARTING" and time.monotonic() < deadline:
time.sleep(0.5)
status = _status(client, run_id)
if status in ("SUCCESS", "FAILURE", "CANCELED"):
raise HTTPException(409, detail=f"the run already ended: {STATE[status]}")
if status == "STARTING":
raise HTTPException(
409, detail="the run is still starting; try again", headers={"Retry-After": "5"}
)
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}