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:
+1
-7
@@ -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"])
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user