Files
WebApi/tests/test_tea.py
T
alberto b401f98f19 TEA follow-up: Patient search with TEA filters and $eeg-summary
Use _patient_rows and shared Query declarations for follow-up selection. Validate filters with an empty row before reading candidates, and use doseq for repeated values in paging links. Keep operation routes out of the metadata scan for read and search interactions. Use _follow_up_gate to compare the 29 captured queries by normalized record number, scalar counts and metrics.
2026-11-29 19:42:17 -06:00

552 lines
27 KiB
Python

"""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.
The hospital (2 GB) is kept outside git; its path is TEA_HOSPITAL (default
~/isssteleon-data), and its hash is the manifest's.
"""
import gzip
import hashlib
import json
import os
import sqlite3
import time
from collections import defaultdict
from datetime import date
from pathlib import Path
from urllib.parse import parse_qsl
import dagster as dg
import pytest
from fhir_checks import pages
from test_conectar import ok, wait_for
from conftest import put_concept_map
from core.tea import ados2
from models.definitions import tea_preview
from persistance import config, previews
ROOT = Path(__file__).parents[2]
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.
os.environ.setdefault("TEA_REFERENCE_DIR", "/mnt/drive/eeg-helsinki")
os.environ.setdefault("TEA_REFERENCE_CACHE", str(HOSPITAL / "cache"))
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "tea"
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_tea.json"
MANIFEST = ROOT / "tests" / "fixtures" / "hospital" / "manifest.json"
# The current platform's item columns, by module, for each item's meaning.
ITEMS = {
"vocalization_directed": {"module_1": "sa_a2"},
"pointing": {"module_1": "sa_a7", "module_2": "sa_a6"},
"gestures": {"module_1": "sa_a8", "module_2": "sa_a7"},
"unusual_eye_contact": {"module_1": "sa_b1", "module_2": "sa_b1"},
"facial_expressions": {"module_1": "sa_b3", "module_2": "sa_b2"},
"gaze_integration": {"module_1": "sa_b4"},
"shared_enjoyment": {"module_1": "sa_b5", "module_2": "sa_b3"},
"showing": {"module_1": "sa_b9", "module_2": "sa_b5"},
"joint_attention_initiation": {"module_1": "sa_b10", "module_2": "sa_b6"},
"joint_attention_response": {"module_1": "sa_b11"},
"social_overtures_quality": {"module_1": "sa_b12", "module_2": "sa_b8"},
"reciprocal_communication": {"module_2": "sa_b11"},
"rapport_quality": {"module_2": "sa_b12"},
"intonation": {"module_1": "rrb_a3"},
"stereotyped_language": {"module_1": "rrb_a5", "module_2": "rrb_a4"},
"unusual_sensory_interest": {"module_1": "rrb_d1", "module_2": "rrb_d1"},
"hand_finger_mannerisms": {"module_1": "rrb_d2", "module_2": "rrb_d2"},
"repetitive_interests": {"module_1": "rrb_d4", "module_2": "rrb_d4"},
} # fmt: skip
MODULES = {"MODULO_1": "module_1", "MODULO_2": "module_2"}
CLASSIFICATION = {"NO_ESPECTRO": "non_spectrum", "ESPECTRO_AUTISTA": "autism_spectrum",
"AUTISMO": "autism"} # fmt: skip
METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2",
"HUSOS_SUENO_N3": "spindles_n3", "PICOS_PAROXISTICOS": "paroxysmal_spikes",
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient"} # fmt: skip
LEVELS = {"completo": "complete", "no_analizable": "not_analyzable", "parcial": "partial",
"sin_referencia_auricular": "no_ear_reference"} # fmt: skip
CAPTURED_ON = "2026-11-28" # the day of the capture's load: durations counted to it
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",
"SOLO_MCHAT": "mchat_only", "PSICOLOGIA": "psychology", "NEUROPEDIATRIA": "neuropediatrics",
"EEG": "eeg", "BUENO": "good", "MALO": "bad", "SIN_ANALIZAR": "not_analyzed",
"16_23": "16-23", "24_29": "24-29", "30_36": "30-36", "sin_dato": "no_data",
"FEMENINO": "female", "MASCULINO": "male", "EN_POBLACION": "in_population",
} # 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("|"))
def _report(entry: dict, ours: bool) -> tuple:
"""Counts, score and its extensions, and strata of one report, in the platform's codes.
The current platform's proportions report no initial population."""
group = entry["resource"]["group"][0]
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
if ours and "denominator" in populations:
populations.pop("initial-population")
score = group.get("measureScore", {})
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
strata = {}
for s in group.get("stratifier", []):
code = s["code"][0]
name = code["coding"][0]["code"] if "coding" in code else STRATA[code["text"]]
cells: dict = defaultdict(dict)
for x in s.get("stratum", []):
for p in x["population"]:
kind = p["code"]["coding"][0]["code"]
if not (ours and kind == "initial-population" and "denominator" in populations):
cells[_code(x["value"]["text"])][kind] = p["count"]
strata[name] = dict(cells)
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
def indicators(api) -> None:
"""Every measure, every semester, as the current platform answers them."""
reference = {k.upper(): v for k, v in
json.loads((REFERENCE / "indicators.json").read_text()).items()} # fmt: skip
(measures,) = pages(api, "/tea/fhir/Measure")
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
for measure in [e["resource"] for e in measures["entry"]]:
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
found = [e for b in pages(api, "/tea/fhir/MeasureReport", params) for e in b["entry"]]
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
name = measure["name"]
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
a, b = _report(ours, True), _report(theirs, False)
a = (*a[:3], {k: v for k, v in a[3].items() if k not in ONLY_OURS.get(name, ())})
where = (name, ours["resource"]["period"]["start"])
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
if cohort:
assert b[1] is None and a[1] == a[0]["initial-population"], where
continue
assert (a[1] is None) == (b[1] is None), where
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
assert a[2] == pytest.approx(b[2]), where
pytestmark = pytest.mark.skipif(
not (HOSPITAL / "hospital_tea.db").exists(), reason="the TEA hospital is outside git"
)
def _day(value) -> date:
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
def _wait_for_sensor_analysis(api):
deadline = time.monotonic() + 3600
while time.monotonic() < deadline:
runs = ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))
for run in runs:
if run["state"] == "failed":
pytest.fail(ok(api.get(f"/runs/{run['id']}"))["error"])
if any(run["state"] == "succeeded" for run in runs):
return
time.sleep(2)
pytest.fail("The sensor's tea_eeg run did not succeed within 3600 seconds")
@pytest.fixture
def scored_hospital(api, platform):
db = HOSPITAL / "hospital_tea.db"
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
put_concept_map(api, "hospital_tea")
ok(api.put("/ingest/pipelines/tea", json=pipeline))
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800)
_wait_for_sensor_analysis(api)
q = platform.query
# Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is
# kept once, by its hash.
with sqlite3.connect(db) as con:
source = {s: con.execute(f"select count(*) from {s}").fetchone()[0]
for s in ("mchat", "ados2", "eeg", "evaluacion_neuropediatrica")} # fmt: skip
signed = "select count(*) from eeg where eeg_estudio is not null"
signals = con.execute(signed).fetchone()[0]
counts = {s: q(f"select count(*) from silver.{s}")[0][0] for s in ("mchat", "ados2", "eeg")}
assert counts == {s: source[s] for s in counts}
assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'"
)[0][0] == source["evaluacion_neuropediatrica"] # fmt: skip
assert q("select count(*) from silver.eeg where edf is not null")[0][0] == signals
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
numbers = dict(q("select distinct person_id, record_number from bronze.staged__identity"))
names = ["person_id", "evaluation_date", "module", *ITEMS]
sql = f"select {', '.join(names)} from silver.ados2 where module is not null"
found = [dict(zip(names, r, strict=True)) for r in q(sql)]
assert len(found) == len(reference) == counts["ados2"]
for row in found:
theirs = reference[(str(row["evaluation_date"])[:10],
int(numbers[row["person_id"]].removeprefix("N")))] # fmt: skip
module = MODULES[theirs["ado_modulo"]]
assert row["module"] == module
for item, by_module in ITEMS.items():
value = theirs["ado_" + by_module[module]] if module in by_module else None
assert row[item] == (None if value is None else pytest.approx(value)), item
# and their scores: the calibrated severity and the classification.
birth = q(f"select birth_date from silver.person where person_id = '{row['person_id']}'")
css, label = ados2.score({**row, "evaluation_date": _day(row["evaluation_date"])},
_day(birth[0][0])) # fmt: skip
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]])
# The EEG analysis: every signal's verdict, level and metrics are the current platform's.
with sqlite3.connect(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}
tables = REFERENCE / "tables"
reference = {hashes[r["eeg_id"]]: r for r in json.loads((tables / "eeg.json").read_text())
if r["eeg_id"] in hashes} # fmt: skip
found = {e: (v, lvl) for e, v, lvl in q("select edf, valid, level from bronze.eeg_analysis")}
assert set(found) == set(reference)
for edf, theirs in reference.items():
assert found[edf] == (bool(theirs["eeg_valido"]), LEVELS[theirs["eeg_nivel"]]), edf
by_id = {r["eeg_id"]: hashes.get(r["eeg_id"]) for r in reference.values()}
metrics = {(by_id.get(r["met_eeg_id"]), METRICS[r["met_codigo"]]): r
for r in json.loads((tables / "eeg_metrica.json").read_text())} # fmt: skip
ours = {(e, c): v for e, c, v in q("select edf, code, value from bronze.eeg_metrics")}
for key, theirs in metrics.items():
value = theirs["met_valor"]
assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key
# The age curves: one training run gives a version of each, from the reference cohort;
# promoted after their clinical validation, they score every analysed EEG as the
# current platform's curves do.
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], 3600)
names = ok(api.get("/models/tea"))
assert len(names) == 7
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
for name in names:
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
pending = {"scope": {"mode": "pending"}}
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], 1800)
scored = {(e, c): r for e, c, *r in q(
"select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
for key, theirs in metrics.items():
if key not in scored: # an EEG of a child outside the cohort: not in gold
continue
expected = [theirs[f"met_{k}"] for k in ("z", "fuera", "p5", "mediana", "p95")]
assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9)
for v in expected], key # fmt: skip
return platform
def _association_gate(api, platform):
name = "ados2_association"
wait_for(api, ok(api.post("/models/tea/train", json={"models": [name]}))["run_id"], 3600)
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
pending = {"scope": {"mode": "pending"}}
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], 1800)
tables = REFERENCE / "tables"
biomarkers = {
"PICOS_PAROXISTICOS": "spikes",
"HUSOS_SUENO_N2": "spindles",
"RITMO_POSTERIOR": "posterior_rhythm",
"GRADIENTE_ANTEROPOSTERIOR": "gradient",
}
zones = {
"frontal_izq": "frontal_left",
"frontal_der": "frontal_right",
"frontal_media": "frontal_midline",
"temporal_izq": "temporal_left",
"temporal_der": "temporal_right",
}
reference = json.loads((tables / "relacion_ados2.json").read_text())
pair_keys = {}
expected_pairs = {}
for row in reference:
zone = row["rel_zona"]
pair = "|".join(
(biomarkers[row["rel_biomarcador"]], zones.get(zone, zone), row["rel_resultado"])
)
pair_keys[row["rel_id"]] = pair
expected_pairs[pair] = row
q = platform.query
pairs = {key: values for key, *values in q(
"select key, n, n_cohort, method, same_direction, odds_ratio, ci_low, ci_high, p, q "
"from gold.tea_associations"
)} # fmt: skip
assert pairs.keys() == expected_pairs.keys()
for key, row in expected_pairs.items():
n, n_cohort, method, same_direction, *stats = pairs[key]
assert (n, n_cohort, method, same_direction) == (
row["rel_n"],
row["rel_n_cohorte"],
row["rel_modelo"],
row["rel_mismo_sentido"],
), key
for value, field in zip(stats, ("or", "ic_inf", "ic_sup", "p", "q"), strict=True):
expected = row[f"rel_{field}"]
assert value == (None if expected is None else pytest.approx(expected, rel=1e-3)), (
key,
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}
eeg_ids = {
(edf, str(day)[:10]): f"{person}|{str(day)[:10]}"
for edf, person, day in q("select edf, person_id, study_date from silver.eeg")
}
reference_eegs = {
row["eeg_id"]: eeg_ids.get((hashes.get(row["eeg_id"]), row["eeg_fecha_estudio"]))
for row in json.loads((tables / "eeg.json").read_text())
}
reference = json.loads((tables / "relacion_ados2_paciente.json").read_text())
expected_scores = {
(reference_eegs[row["rap_eeg_id"]], pair_keys[row["rap_rel_id"]]): row for row in reference
}
score_rows = q(
"select eeg_id, pair, z, probability, reference_probability "
"from gold.tea_association_scores"
)
scores = {(eeg_id, pair): (z, prob, ref) for eeg_id, pair, z, prob, ref in score_rows}
assert scores.keys() == expected_scores.keys()
for key, row in expected_scores.items():
z, prob, ref = scores[key]
assert z == pytest.approx(row["rap_valor_z"], rel=1e-9), key
assert prob == pytest.approx(row["rap_probabilidad"], abs=1e-4), key
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
def _follow_up_gate(api, platform):
with gzip.open(REFERENCE / "follow_up.json.gz", "rt") as file:
reference = json.load(file)
persons = {
int(number.removeprefix("N")): person
for person, number in platform.query(
"select distinct person_id, record_number from bronze.staged__identity"
)
}
params_map = {
"etapa": "tea-step", "status": "follow-up-status", "resultado-eeg": "tea-eeg-result",
"modelo": "tea-model", "grupo-edad": "tea-age-group", "sexo": "tea-sex",
"mchat": "tea-mchat", "css": "tea-css",
} # fmt: skip
values = {
**CODES, "NEUROPEDIATRIA": "neurology", "anormal": "abnormal",
"sin-eeg-valido": "no_valid_eeg",
"si": "yes",
} # fmt: skip
counts = {
"con_eeg_valido": "valid", "sin_eeg_valido": "not_valid",
"normales": "normal", "anormales": "abnormal",
} # fmt: skip
for query, expected in reference.items():
params = []
for name, value in parse_qsl(query):
if name == "date":
dates = {"ge": "follow-up-start", "le": "follow-up-cutoff"}
params.append((dates[value[:2]], value[2:]))
else:
params.append((params_map[name], values.get(value, value)))
resources = [entry["resource"] for entry in expected["episodes"]["body"].get("entry", [])]
patients = {
f"Patient/{r['id']}": persons[int(next(
identifier["value"].removeprefix("N-") for identifier in r["identifier"]
if identifier["system"].endswith("/expediente")
))]
for r in resources if r["resourceType"] == "Patient"
} # fmt: skip
children = {
patients[r["patient"]["reference"]]
for r in resources if r["resourceType"] == "EpisodeOfCare"
} # fmt: skip
bundles = pages(api, "/tea/fhir/Patient", params)
assert {entry["resource"]["id"] for bundle in bundles
for entry in bundle.get("entry", [])} == children, query # fmt: skip
parameters = {}
alterations = {}
for parameter in expected["summary"]["body"]["parameter"]:
name = parameter["name"]
if name == "por_alteracion":
parts = {p["name"]: p for p in parameter["part"]}
metric = METRICS[parts["alteracion"]["valueCode"].upper()]
alterations[metric] = parts["pacientes"]["valueInteger"]
else:
parameters[counts[name]] = parameter["valueInteger"]
found = ok(api.get("/tea/fhir/Patient/$eeg-summary", params=params))
assert found["resourceType"] == "Parameters", query
assert {p["name"]: p["valueInteger"] for p in found["parameter"]
if p["name"] != "by_alteration"} == parameters, query # fmt: skip
assert {
p["part"][0]["valueCode"]: p["part"][1]["valueInteger"]
for p in found["parameter"] if p["name"] == "by_alteration"
} == alterations, query # fmt: skip
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)
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
listed = ok(api.get("/tea/eegs"))
summary = json.loads((REFERENCE / "pages.json").read_text())["/governance/tea/eeg/summary"]
expected = summary["body"]
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
one = next(e for e in listed if e["valid"])
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
for m in shown["metrics"]) # fmt: skip
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
_cancel_during_analysis_leaves_bronze_and_gold_untouched(api, scored_hospital)
def _cancel_during_analysis_leaves_bronze_and_gold_untouched(api, platform):
def snapshot():
return (
platform.query(
"select edf, valid, level, analysed_at from bronze.eeg_analysis order by edf"
),
platform.count("bronze.eeg_metrics"),
platform.count("gold.tea_eeg_metrics"),
)
before = snapshot()
ids = [study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"]]
body = {"scope": {"mode": "ids", "ids": ids}}
run_id = ok(api.post("/tea/eegs/analyze", json=body))["run_id"]
url = f"/runs/{run_id}"
deadline = time.monotonic() + 300
while (run := ok(api.get(url)))["state"] != "running":
assert run["state"] not in {"succeeded", "failed", "cancelled"}, run
assert time.monotonic() < deadline, run
time.sleep(1)
ok(api.post(f"{url}/cancel"))
deadline = time.monotonic() + 900
while (run := ok(api.get(url)))["state"] != "cancelled":
assert run["state"] not in {"succeeded", "failed"}, run
assert time.monotonic() < deadline, run
time.sleep(1)
assert snapshot() == before
def _reanalysis_by_id_in_local_mode_matches_sync(api, platform):
study_id = next(study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"])
person, day = study_id.split("|")
person = person.replace("'", "''")
((edf,),) = platform.query(
f"select edf from silver.eeg where person_id = '{person}' "
f"and cast(study_date as varchar(10)) = '{_day(day).isoformat()}'"
)
def snapshot():
(row,) = platform.query(
"select valid, level, age_months, clean_fraction "
f"from bronze.eeg_analysis where edf = '{edf}'"
)
values = dict(
platform.query(f"select code, value from bronze.eeg_metrics where edf = '{edf}'")
)
return tuple(row), values
before, values = snapshot()
local = {"scope": {"mode": "ids", "ids": [study_id]}, "execution": {"mode": "local"}}
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
return None if expected is None else pytest.approx(expected, rel=1e-12)
assert after[:2] == before[:2]
assert list(after[2:]) == [close(v) for v in before[2:]]
assert reanalysed == {code: close(v) for code, v in values.items()}
unknown = {"scope": {"mode": "ids", "ids": ["N9999|2000-01-01"]}}
run_id = ok(api.post("/tea/eegs/analyze", json=unknown))["run_id"]
deadline = time.monotonic() + 900
while (run := ok(api.get(f"/runs/{run_id}")))["state"] not in (
"succeeded",
"failed",
"cancelled",
):
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
time.sleep(2)
assert run["state"] == "failed", run
assert "no EEG" in run["error"]
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",
"bronze.eeg_scores", "bronze.files", "silver.eeg",
) # fmt: skip
before = {table: platform.count(table) for table in tables}
edf, content, birth, valid, level = q("""
select a.edf, f.content, p.birth_date, a.valid, a.level
from bronze.eeg_analysis a
join bronze.files f on f.key = a.edf
join silver.eeg e on e.edf = a.edf
join silver.person p on p.person_id = e.person_id
where a.valid and p.birth_date is not null and exists (
select 1 from gold.tea_eeg_metrics m where m.edf = a.edf and m.z is not null
)
order by a.edf
limit 1
""")[0]
values = dict(q(f"select code, value from bronze.eeg_metrics where edf = '{edf}'"))
scores = dict(q(f"select code, z from gold.tea_eeg_metrics where edf = '{edf}'"))
for name in ("PLATFORM_DATABASE_URL", "MLFLOW_TRACKING_URI", "ISSSTELEON_DATA"):
monkeypatch.setenv(name, platform.env[name])
monkeypatch.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
key = previews.put(bytes(content))
with dg.DagsterInstance.ephemeral() as instance:
run = tea_preview.execute_in_process(
run_config={"ops": {"preview_study": {"config": {
"edf": key, "birth_date": _day(birth).isoformat(),
}}}},
instance=instance,
) # fmt: skip
assert run.success
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
assert (result.eeg.valid, result.eeg.level) == (valid, level)
assert {metric.code for metric in result.eeg.metrics} == values.keys() == scores.keys()
for metric in result.eeg.metrics:
value, z = values[metric.code], scores[metric.code]
assert metric.value == (None if value is None else pytest.approx(value, rel=1e-12))
assert (metric.score.z if metric.score else None) == (
None if z is None else pytest.approx(z, rel=1e-9)
)
assert {table: platform.count(table) for table in tables} == before
assert not list(previews.area().iterdir())