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.
This commit is contained in:
+4
-2
@@ -52,9 +52,11 @@ def studies() -> list[Study]:
|
||||
return [Study(**s) for s in eeg.studies()]
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
@router.post(
|
||||
"/analyze",
|
||||
description="Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.",
|
||||
)
|
||||
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")
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""The execution choices a deployment offers and the health of a chosen cluster."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from persistance import cluster
|
||||
|
||||
+24
-14
@@ -24,6 +24,7 @@ from core.domains import Domain, measures, part
|
||||
from core.follow_up import window_start
|
||||
from core.pipeline import ID_PATTERN
|
||||
from core.tea import fhir as tea_fhir
|
||||
from core.tea.follow_up import FILTERS as TEA_FILTERS
|
||||
from persistance import config_log, readers
|
||||
from persistance import fhir as reads
|
||||
from persistance import measures as measure_reads
|
||||
@@ -115,7 +116,13 @@ _CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last d
|
||||
_STATUS = Query(None, alias="follow-up-status")
|
||||
|
||||
|
||||
@router.get("/Patient/$eeg-summary", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Patient/$eeg-summary",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="EEG counts for the follow-up list. Without a window or start, "
|
||||
"use the whole history.",
|
||||
)
|
||||
def eeg_summary(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
@@ -124,7 +131,6 @@ def eeg_summary(
|
||||
cutoff: date | None = _CUTOFF,
|
||||
status: str | None = _STATUS,
|
||||
) -> Response:
|
||||
"""EEG counts for the follow-up list. Without a window or start, use the whole history."""
|
||||
fu = _clinical(domain)
|
||||
if not hasattr(fu, "summary"):
|
||||
return outcome(404, f"no EEG summary for {domain.value}")
|
||||
@@ -178,7 +184,16 @@ def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
@router.get("/Patient", responses=_OK, response_class=Response)
|
||||
@router.get(
|
||||
"/Patient",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"Patients, or the domain's follow-up list selected by window or start.\n\n"
|
||||
"For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n"
|
||||
"follow-up episodes appear only in the plain search."
|
||||
),
|
||||
)
|
||||
def search_patient(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
@@ -194,11 +209,6 @@ def search_patient(
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> Response:
|
||||
"""Patients, or the domain's follow-up list selected by window or start.
|
||||
|
||||
For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without
|
||||
follow-up episodes appear only in the plain search.
|
||||
"""
|
||||
fu = _clinical(domain)
|
||||
count, offset = _page(_count, _offset)
|
||||
at = _cutoff(domain, cutoff)
|
||||
@@ -242,11 +252,11 @@ def _patient_rows(
|
||||
) -> tuple[list[dict], bool, dict]:
|
||||
filters = {
|
||||
name: request.query_params.getlist(name)
|
||||
for name in getattr(fu, "FILTERS", ())
|
||||
for name in (TEA_FILTERS if domain == Domain.TEA else ())
|
||||
if name in request.query_params
|
||||
}
|
||||
if filters:
|
||||
fu.matches({}, filters) # Validate values even when the selection has no rows.
|
||||
fu.matches({}, filters)
|
||||
listed = (
|
||||
whole_history
|
||||
or start is not None
|
||||
@@ -378,7 +388,6 @@ def _tea_risks(persons: list[str], at: str) -> list[Resource]:
|
||||
groups = defaultdict(list)
|
||||
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
|
||||
group = groups[row["person_id"]]
|
||||
# The earliest scored EEG supplies the one set of predictions for this child.
|
||||
if (
|
||||
not group
|
||||
or row["edf"] == group[0]["edf"]
|
||||
@@ -607,9 +616,10 @@ def metadata(request: Request, domain: Domain) -> Response:
|
||||
if kind == "Patient" and not rest:
|
||||
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
||||
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
|
||||
entry["searchParam"] += [
|
||||
{"name": name, "type": spec[0]} for name, spec in getattr(fu, "FILTERS", {}).items()
|
||||
]
|
||||
if domain == Domain.TEA:
|
||||
entry["searchParam"] += [
|
||||
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
|
||||
]
|
||||
entry["interaction"].append({"code": "read" if rest else "search-type"})
|
||||
for param in route.dependant.query_params:
|
||||
name = param.alias
|
||||
|
||||
+5
-7
@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field, WithJsonSchema
|
||||
|
||||
from core import domains
|
||||
from core import tea
|
||||
from core.domains import Domain, InputSpec
|
||||
from persistance import bundle, cluster, inputs, registry
|
||||
from persistance.cluster import Execution, Reference
|
||||
@@ -176,7 +176,7 @@ def lineage(domain: Domain, name: str, version: int) -> dict:
|
||||
|
||||
|
||||
def _training_inputs(domain: Domain, name: str) -> tuple[InputSpec, Path]:
|
||||
declared = getattr(domains.part(domain), "TRAINING_INPUTS", {})
|
||||
declared = tea.TRAINING_INPUTS if domain == Domain.TEA else {}
|
||||
spec = declared.get(name, declared.get("*"))
|
||||
if spec is None:
|
||||
raise HTTPException(404, detail=f"no training inputs for {domain.value}.{name}")
|
||||
@@ -233,7 +233,7 @@ class TrainingForm(BaseModel):
|
||||
|
||||
|
||||
class Training(TrainingForm):
|
||||
models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence)
|
||||
models: list[str] = []
|
||||
|
||||
|
||||
class TrainingConfig(BaseModel):
|
||||
@@ -247,7 +247,7 @@ class TrainingConfig(BaseModel):
|
||||
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
||||
json_schema = TrainingForm.model_json_schema()
|
||||
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
||||
if "reference" in getattr(domains.part(domain), "TRAINING_OPTIONS", ()):
|
||||
if domain == Domain.TEA:
|
||||
defaults["reference"] = {"line_hz": 50}
|
||||
else:
|
||||
del json_schema["properties"]["reference"]
|
||||
@@ -265,9 +265,7 @@ class Analyze(BaseModel):
|
||||
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."""
|
||||
if request.reference is not None and "reference" not in getattr(
|
||||
domains.part(domain), "TRAINING_OPTIONS", ()
|
||||
):
|
||||
if request.reference is not None and domain != Domain.TEA:
|
||||
raise HTTPException(422, f"{domain.value} models take no reference cohort")
|
||||
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||
if request.as_of:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Upload temporary study files and follow their TEA preview run."""
|
||||
|
||||
from datetime import date
|
||||
from typing import Annotated
|
||||
|
||||
|
||||
+17
-16
@@ -106,7 +106,7 @@ def dagster() -> DagsterGraphQLClient:
|
||||
return DagsterGraphQLClient(host, port_number=port)
|
||||
|
||||
|
||||
LOCKED = "database is locked" # Dagster's SQLite run storage, busy while a run writes its events
|
||||
LOCKED = "database is locked"
|
||||
LOCK_RETRIES = 5
|
||||
STARTING_WAIT_S = 30
|
||||
|
||||
@@ -121,24 +121,25 @@ def _locked(payload: dict) -> bool:
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
"""Dagster's GraphQL answer; a read that found its run storage locked is tried again."""
|
||||
host, port = _dagster_address()
|
||||
for attempt in range(LOCK_RETRIES + 1):
|
||||
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 not _locked(payload) or attempt == LOCK_RETRIES:
|
||||
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"}
|
||||
@@ -244,7 +245,7 @@ def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
||||
@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 # Dagster cannot terminate a run still starting
|
||||
deadline = time.monotonic() + STARTING_WAIT_S
|
||||
while status == "STARTING" and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
status = _status(client, run_id)
|
||||
|
||||
Reference in New Issue
Block a user