Runs API: a run's state, steps, live progress, info and warnings apart, the failure's own message; cancel; history by job and domain; execution options and health; POST /tea/eegs/analyze

test_runs.py: 17 passed on SQLite and Postgres
(compose test stack). test_conectar.py fails on an identity-merge count, as it does on tea/parity
without this change.
This commit is contained in:
2026-11-28 06:54:00 -06:00
parent 1e878b8942
commit 4793cf01f0
7 changed files with 500 additions and 23 deletions
+16 -1
View File
@@ -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:
+23
View File
@@ -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
+2 -1
View File
@@ -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)
+16 -13
View File
@@ -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)
+238 -7
View File
@@ -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}