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
+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",