TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n

Update tests/test_tea.py. Wait for sensor analysis immediately after ingest. Keep training and promotion before scoring and submit the pending scope to apply curves.

Use monotonic polling deadlines, check failures before success, and allow 900 seconds for the expected-failure run to reach a terminal state. Pick the first valid API study, resolve its EDF through silver, compare verdict and level exactly, and compare numeric fields and code-keyed metrics with pytest.approx.
This commit is contained in:
2026-11-29 01:24:49 -06:00
parent 2131ff60a5
commit 51bcdbdfe3
+59 -2
View File
@@ -12,6 +12,7 @@ import hashlib
import json import json
import os import os
import sqlite3 import sqlite3
import time
from collections import defaultdict from collections import defaultdict
from datetime import date from datetime import date
from pathlib import Path from pathlib import Path
@@ -142,6 +143,19 @@ def _day(value) -> date:
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10]) 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 @pytest.fixture
def scored_hospital(api, platform): def scored_hospital(api, platform):
db = HOSPITAL / "hospital_tea.db" db = HOSPITAL / "hospital_tea.db"
@@ -151,6 +165,7 @@ def scored_hospital(api, platform):
put_concept_map(api, "hospital_tea") put_concept_map(api, "hospital_tea")
ok(api.put("/ingest/pipelines/tea", json=pipeline)) ok(api.put("/ingest/pipelines/tea", json=pipeline))
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800) wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800)
_wait_for_sensor_analysis(api)
q = platform.query q = platform.query
# Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is # Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is
@@ -192,7 +207,6 @@ def scored_hospital(api, platform):
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]]) 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. # The EEG analysis: every signal's verdict, level and metrics are the current platform's.
wait_for(api, ok(api.post("/models/tea/analyze"))["run_id"], 3600) # 62 EEGs, 2 CPUs: ~45 min
with sqlite3.connect(db) as con: with sqlite3.connect(db) as con:
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null") 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} hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
@@ -221,7 +235,8 @@ def scored_hospital(api, platform):
for name in names: 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/reports/clinical_validation", files=files))
ok(api.post(f"/models/tea/{name}/versions/1/promote")) ok(api.post(f"/models/tea/{name}/versions/1/promote"))
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800) 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( 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 "select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
for key, theirs in metrics.items(): for key, theirs in metrics.items():
@@ -251,6 +266,48 @@ def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
for m in shown["metrics"]) # fmt: skip for m in shown["metrics"]) # fmt: skip
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch) _preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
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()
assert after[:2] == before[:2]
assert after[2:] == pytest.approx(before[2:], rel=1e-12)
assert reanalysed == pytest.approx(values, rel=1e-12)
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): def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):