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:
+238
-7
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user