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:
2026-11-30 13:39:51 -06:00
parent 54b1995681
commit ec5d945f71
9 changed files with 62 additions and 82 deletions
+1 -7
View File
@@ -1,5 +1,3 @@
"""Run shaping and the API's Dagster-backed run and execution routes."""
import os
import time
@@ -169,7 +167,6 @@ def test_cancel_a_finished_run_is_409(api, failed_run):
@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
@@ -211,7 +208,7 @@ def test_execution_options_and_health(api):
options = _ok(api.get("/execution/options"))
assert options["default_mode"] == "sync"
configured = [s for s in os.environ.get("DASK_SCHEDULERS", "").split(",") if s]
assert options["schedulers"] == configured # compose and CI name the test scheduler
assert options["schedulers"] == configured
health = _ok(api.get("/execution/health", params={"mode": "local"}))
assert health["reachable"] is True
assert health["workers"] >= 1
@@ -231,8 +228,6 @@ def test_tea_eegs_analyze_validates_scope(api):
def test_a_locked_run_storage_is_read_again(monkeypatch):
"""Dagster's SQLite run storage is locked for a moment while a run writes: the read is retried,
and a storage that stays locked is a 503 the caller can retry, not a 502."""
from fastapi import HTTPException
from webapi import runs
@@ -266,7 +261,6 @@ def test_a_locked_run_storage_is_read_again(monkeypatch):
def test_cancel_waits_for_a_starting_run(monkeypatch):
"""Dagster refuses to terminate a run that is still STARTING: cancel waits for it to start."""
from webapi import runs
statuses = iter(["STARTING", "STARTING", "STARTED", "CANCELING"])
+3 -8
View File
@@ -1,5 +1,3 @@
"""Concurrency and cancellation through the real API and Dagster daemon."""
import json
import time
from pathlib import Path
@@ -79,9 +77,9 @@ def test_cancelling_an_ingest_run_leaves_no_silver_or_gold(api, platform):
cancelled = _wait_cancelled(api, run_id)
assert cancelled["status"] == "CANCELED"
assert cancelled["error"] is None
with pytest.raises(DBAPIError): # the table was never created
with pytest.raises(DBAPIError):
platform.count("silver.person")
with pytest.raises(DBAPIError): # the table was never created
with pytest.raises(DBAPIError):
platform.count("gold.cacu_risk")
wait_for(api, _submit(api), 300)
@@ -92,8 +90,6 @@ def test_cancelling_an_ingest_run_leaves_no_silver_or_gold(api, platform):
def test_cancelling_a_queued_run_never_starts_it(api, platform):
load(api, "cacu")
runs = [_submit(api), _submit(api)]
# Dagster launches one of the two (its queue sorts by priority, not by submission order);
# the other waits behind the `writes` limit: cancel that one, whichever it is.
deadline = time.monotonic() + 120
while True:
states = {run_id: _get_run(api, run_id)["state"] for run_id in runs}
@@ -106,11 +102,10 @@ def test_cancelling_a_queued_run_never_starts_it(api, platform):
assert time.monotonic() < deadline, states
time.sleep(0.5)
ok(api.post(f"/runs/{queued[0]}/cancel"))
# Dagster stamps a start time on a queued run it cancels; what matters is that nothing ran
assert _wait_cancelled(api, queued[0])["steps"] == []
wait_for(api, running[0], 300)
@pytest.mark.skip(reason="needs killing the run worker; checked by hand")
def test_a_dead_run_does_not_stay_running():
"""The Dagster daemon detects a dead worker via `run_monitoring` in `dagster.yaml`."""
pass
+8 -24
View File
@@ -1,10 +1,9 @@
"""Phase 4 gate, TEA: the sitio-b hospital (62 children with real EEG signals, and ADOS-2
reports, as BLOBs), loaded through one drawn pipeline, gives what the current platform gives
on the same hospital (the reference fixtures, captured at the last load): the ADOS-2 results
read from the reports and their scores, the EEG analysis, its indicators and its pages. Real
API, Dagster and MLflow.
"""Phase 4 gate, TEA: the synthetic hospital (EEG signals and ADOS-2 reports as BLOBs), loaded
through one drawn pipeline, gives what the current platform gives on the same hospital (the
reference fixtures, captured at the last load): the ADOS-2 results read from the reports and
their scores, the EEG analysis, its indicators and its pages. Real API, Dagster and MLflow.
The hospital (2 GB) is kept outside git; its path is TEA_HOSPITAL (default
The hospital (205 MB) is kept outside git; its path is TEA_HOSPITAL (default
~/isssteleon-data), and its hash is the manifest's.
"""
@@ -33,7 +32,6 @@ from models.definitions import tea_preview
from persistance import config, previews
ROOT = Path(__file__).parents[2]
# A busy shared server runs the gate slower: its waits stretch by this factor (default 1).
SLOW = float(os.environ.get("TEA_GATE_SLOW", "1"))
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
# The age curves' reference cohort (public, outside git) and where its measures are kept.
@@ -84,7 +82,7 @@ ZONES = {
"temporal_izq": "temporal_left",
"temporal_der": "temporal_right",
}
CAPTURED_ON = "2026-11-28" # the day of the capture's load: durations counted to it
CAPTURED_ON = "2026-11-28"
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
CODES = { # the current platform's code -> the platform's
"CONFIRMADO": "confirmed", "EN_PROCESO": "in_process", "SIN_TEA": "not_confirmed",
@@ -95,14 +93,10 @@ CODES = { # the current platform's code -> the platform's
} # fmt: skip
STRATA = {"estado": "category", "paso": "category", "calidad": "category",
"grupo_edad": "age_group", "edad_sexo": "age_sex", "sexo": "sex"} # fmt: skip
# Stratifiers only the platform reports: the current platform's M30 gives the total alone, so
# its group per alteration has nothing here to be compared with (gold.tea_alterations is
# tested in dbt).
ONLY_OURS = {"M30_RESULTADO_EEG": {"alteration"}}
def _code(text: str) -> str:
"""A stratum value in the platform's codes; "16_23|FEMENINO" part by part."""
return "|".join(CODES.get(part, part) for part in text.split("|"))
@@ -203,7 +197,6 @@ def scored_hospital(api, platform):
kept = "select count(*) from bronze.files where key in (select edf from silver.eeg)"
assert q(kept)[0][0] == signals
# ADOS-2: the results read from every report are the current platform's.
reference = {(r["ado_fecha"], r["ado_pac_id"]): r for r in
json.loads((REFERENCE / "tables" / "ados2.json").read_text())
if r["ado_modulo"]} # fmt: skip
@@ -311,7 +304,6 @@ def _association_gate(api, platform):
field,
)
# Match reference EEG IDs to silver EEGs by the same signal hash used for analysis.
with sqlite3.connect(HOSPITAL / "hospital_tea.db") as con:
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
@@ -346,7 +338,6 @@ def _fhir_code(concept):
def _fhir_extensions(resource):
return {
# a complex extension (curve-centiles) has sub-extensions instead of a value[x]
e["url"].rsplit("/", 1)[-1]: next(
(v for k, v in e.items() if k.startswith("value")), e.get("extension")
)
@@ -420,8 +411,6 @@ def _fhir_eeg_gate(api, platform, patients, reference):
def table(name):
return json.loads((tables / f"{name}.json").read_text(), parse_float=Decimal)
# The FHIR fixture carries aggregate values. The reference tables carry the same EEGs'
# electrode and zone values, keyed by the metric ID and the child's record number.
records = {r["eeg_pac_id"]: r["eeg_id"] for r in table("eeg")}
metric_ids = {(r["met_eeg_id"], METRICS[r["met_codigo"]]): r["met_id"]
for r in table("eeg_metrica")} # fmt: skip
@@ -434,9 +423,8 @@ def _fhir_eeg_gate(api, platform, patients, reference):
code = r[f"{prefix}_{site}"]
sites[r[f"{prefix}_met_id"]][kind, ZONES.get(code, code)] = r[f"{prefix}_valor"]
# Stored champion scores by the served report id (one per EEG study, as core.tea.fhir names it).
scores = {
(tea_fhir._eeg_id(person, day), metric): z
(tea_fhir._eeg_report_id(person, day), metric): z
for person, day, metric, z in platform.query(
"select e.person_id, e.study_date, s.metric, s.z from bronze.eeg_scores as s "
"join silver.eeg as e on e.edf = s.edf where s.part = 'value' and s.model is not null"
@@ -631,8 +619,6 @@ def _follow_up_gate(api, platform):
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
_association_gate(api, scored_hospital)
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
# promoted curves found (as the current platform's were captured: curves trained).
indicators(api)
_follow_up_gate(api, scored_hospital)
@@ -713,7 +699,7 @@ def _reanalysis_by_id_in_local_mode_matches_sync(api, platform):
wait_for(api, ok(api.post("/tea/eegs/analyze", json=local))["run_id"])
after, reanalysed = snapshot()
def close(expected): # a value the analysis leaves empty stays empty
def close(expected):
return None if expected is None else pytest.approx(expected, rel=1e-12)
assert after[:2] == before[:2]
@@ -735,8 +721,6 @@ def _reanalysis_by_id_in_local_mode_matches_sync(api, platform):
def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):
"""P3.5: previewing one of the hospital's EDFs gives its stored analysis and scores, and
writes nothing (run here, on the already scored hospital, not as a second 80-minute load)."""
q = platform.query
tables = (
"bronze.eeg_analysis", "bronze.eeg_checks", "bronze.eeg_metrics",
+4 -2
View File
@@ -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")
-2
View File
@@ -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
View File
@@ -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
View File
@@ -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:
-2
View File
@@ -1,5 +1,3 @@
"""Upload temporary study files and follow their TEA preview run."""
from datetime import date
from typing import Annotated
+17 -16
View File
@@ -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)