Governance TEA EEG: reference cohorts, baselines export and import, cluster health, training and analysis jobs with progress, EDF upload, EEG queries

This commit is contained in:
ulises
2026-11-23 09:29:31 -06:00
parent 5831fcd9d9
commit 0e6494f053
20 changed files with 1914 additions and 88 deletions
+121
View File
@@ -0,0 +1,121 @@
"""Cover the bundle HTTP contract with an app client and two temporary registries.
Fails if export loses ZIP metadata, import misreports registry versions or malformed uploads succeed.
"""
import hashlib
import json
import zipfile
from dataclasses import replace
from io import BytesIO
import mlflow
import numpy as np
import pytest
from flask import Flask
from models.io.registry import PRODUCTION_ALIAS
from models.tea.eeg import bundle, train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.settings import settings
from webapi.blueprints.governance import governance_bp
from webapi.tea import baselines
BASELINES = "/governance/tea/baselines"
SCENARIO = "eeg-posterior-rhythm"
@pytest.fixture
def client():
"""Mount the governance routes so changes to route registration or error handling surface in HTTP."""
app = Flask(__name__)
app.config.update(TESTING=True)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.fixture
def trained_registries(tmp_path, monkeypatch):
"""Train one synthetic baseline in SQLite and provide an empty destination to expose failed transfers."""
config = settings()
metric = next(metric for metric in config.metrics if metric.scenario == SCENARIO)
config = replace(config, metrics=(metric,))
monkeypatch.setattr(baselines, "settings", lambda: config)
monkeypatch.chdir(tmp_path)
previous_uri = mlflow.get_tracking_uri()
def use_store(name):
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
try:
use_store("source")
biomarker, phase = config.scenarios[SCENARIO]
features = pipeline(config).module(biomarker).features
rng = np.random.default_rng(0)
ages = np.linspace(16, 36, 100)
found = train.Listing.of("source", [(f"/synthetic/{k}.edf", float(age)) for k, age in enumerate(ages)])
studies = [
ReferenceStudy(key, age, 1, {
(biomarker, phase): {feature: float(1 + 0.02 * age + rng.normal(0, 0.1)) for feature in features},
})
for key, _, age in found.studies
]
train.train_all(config, "PROD", found=found, studies=studies)
yield use_store
finally:
mlflow.set_tracking_uri(previous_uri)
def test_export_and_import_baselines(client, trained_registries, monkeypatch):
"""Pin ZIP headers, cleanup and registry transfer. Fail if repeats register another version."""
real_export = bundle.export
export_paths = []
def capture_export(config, path, **kwargs):
export_paths.append(path)
return real_export(config, path, **kwargs)
monkeypatch.setattr(bundle, "export", capture_export)
with client.get(f"{BASELINES}/export?environment=prod&production=0") as response:
assert response.status_code == 200
assert response.mimetype == "application/zip"
assert response.headers["Content-Disposition"] == "attachment; filename=baselines.zip"
assert response.headers["X-Baselines-Versions"] == "1"
assert export_paths[0].is_file()
archive = response.data
sha256 = hashlib.sha256(archive).hexdigest()
assert response.headers["X-Baselines-Sha256"] == sha256
assert not export_paths[0].exists()
with zipfile.ZipFile(BytesIO(archive)) as exported:
manifest = json.loads(exported.read(bundle.MANIFEST))
assert list(manifest["escenarios"]) == [SCENARIO]
model = train.latest(SCENARIO, "PROD")
mlflow.MlflowClient().set_registered_model_alias(model.name, PRODUCTION_ALIAS, model.version)
with client.get(f"{BASELINES}/export?environment=dev&production=1") as response:
assert response.status_code == 200
assert response.data == archive
assert not export_paths[1].exists()
trained_registries("destination")
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
assert response.status_code == 200
assert response.json == {"sha256": sha256, "imported": [{"scenario": SCENARIO, "version": 1}]}
assert train.latest(SCENARIO, "PROD").tags[bundle.BUNDLE_TAG] == sha256
duplicate = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
assert duplicate.status_code == 409
assert duplicate.json["error"]
versions = mlflow.MlflowClient().search_model_versions(f"name = '{model.name}'")
assert [int(version.version) for version in versions] == [1]
def test_import_rejects_garbage(client):
"""Pin a JSON 400 for non-ZIP bytes. Fail if the ZIP exception becomes a server error."""
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(b"garbage"), "baselines.zip")})
assert response.status_code == 400
assert response.json["error"]
+78
View File
@@ -0,0 +1,78 @@
"""Cover the cluster route with cluster_client and monkeypatched network probes.
Fails if an unapproved scheduler is probed or health results use the wrong HTTP status.
"""
from unittest.mock import Mock
import distributed
import pytest
from flask import Flask
from tea.pipeline import cluster_status
from webapi.blueprints.governance import governance_bp
CLUSTER_URL = "/governance/tea/cluster"
@pytest.fixture
def cluster_client(monkeypatch):
"""Mount the governance blueprint with clean config so machine defaults cannot affect routing."""
for variable in ("DASK_SCHEDULER_ADDRESS", "TEA_DASK_SCHEDULERS"):
monkeypatch.delenv(variable, raising=False)
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
def test_rejects_scheduler_outside_allow_list(cluster_client, monkeypatch):
"""Pin allow-list enforcement. Fail if an arbitrary scheduler reaches a network probe."""
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://backup:8786")
probe = Mock()
monkeypatch.setattr(cluster_status.ClusterStatus, "check", probe)
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": "tcp://other:8786"})
assert response.status_code == 400
assert response.json["error"]
probe.assert_not_called()
@pytest.mark.parametrize("mode", ["invalid", "remote"])
def test_rejects_invalid_cluster_choice(cluster_client, mode):
"""Pin validation errors. Fail if an unknown mode or addressless remote request succeeds."""
response = cluster_client.get(CLUSTER_URL, query_string={"mode": mode})
assert response.status_code == 400
assert response.json["error"]
def test_local_mode_reports_reachable(cluster_client):
"""Pin local status serialization. Fail if local checks start reporting remote details."""
response = cluster_client.get(CLUSTER_URL, query_string={"mode": "local"})
assert response.status_code == 200
assert response.json["mode"] == "local"
assert response.json["reachable"] is True
assert response.json["scheduler"] is None
assert response.json["workers"] is None
@pytest.mark.parametrize("scheduler", ["tcp://backup:8786", "tcp://default:8786"])
def test_unreachable_approved_scheduler_returns_health(cluster_client, monkeypatch, scheduler):
"""Pin HTTP 200 on connection failure. Fail if either approval source rejects its address."""
connect = Mock(side_effect=OSError("connection refused"))
monkeypatch.setattr(distributed, "Client", connect)
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=OSError))
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://first:8786, tcp://backup:8786 ")
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": scheduler})
assert response.status_code == 200
assert response.json["mode"] == "remote"
assert response.json["scheduler"] == scheduler
assert response.json["reachable"] is False
assert response.json["error"] == "connection refused"
connect.assert_called_once_with(scheduler, timeout=5)
+115
View File
@@ -0,0 +1,115 @@
"""Cover cohort metadata, uploads and request errors using a temporary root and the app client.
Fails if the API accepts unsafe files, bypasses the upload limit or loses stored metadata.
"""
from io import BytesIO
import pytest
from webapi import create_app
COHORTS = "/governance/tea/reference-cohorts"
@pytest.fixture
def cohort_client(tmp_path, monkeypatch):
"""Wire the app to a temporary root so escaped writes and metadata errors are observable."""
root = tmp_path / "reference"
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
app = create_app()
app.config.update(TESTING=True)
return app.test_client(), root
def test_list_reference_cohorts(cohort_client):
"""Pin nested EDF counts and age-table metadata. Fail if either is omitted."""
client, root = cohort_client
cohort = root / "reference-1"
nested = cohort / "2026"
nested.mkdir(parents=True)
(root / "empty").mkdir()
(root / "loose.edf").write_bytes(b"loose")
(cohort / "study.edf").write_bytes(b"edf")
(nested / "second.EDF").write_bytes(b"second")
(cohort / "edades.csv").write_bytes(b"ages")
response = client.get(COHORTS)
assert response.status_code == 200
assert response.json == [
{"name": "empty", "edfs": 0, "size_bytes": 0, "has_ages": False, "path": str(root / "empty")},
{"name": "reference-1", "edfs": 2, "size_bytes": 13, "has_ages": True, "path": str(cohort)},
]
@pytest.mark.parametrize("filename", ["study.edf", "edades.csv"])
def test_upload_reference_file(cohort_client, filename):
"""Pin each permitted upload and the stored bytes. Fail if the upload leaves a staging file."""
client, root = cohort_client
payload = b"reference data"
response = client.post(f"{COHORTS}/sample-1/files", data={"file": (BytesIO(payload), filename)})
assert response.status_code == 201
assert response.json == {"name": "sample-1", "file": filename, "size_bytes": len(payload)}
folder = root / "sample-1"
assert list(folder.iterdir()) == [folder / filename]
assert (folder / filename).read_bytes() == payload
@pytest.mark.parametrize(("name", "filename"), [
("sample", "other.csv"),
("sample", "../study.edf"),
("sample", r"..\study.edf"),
("sample", "nested/study.edf"),
("sample", r"nested\study.edf"),
("sample/other", "study.edf"),
("..", "study.edf"),
("sample..other", "study.edf"),
("bad%20name", "study.edf"),
("a" * 65, "study.edf"),
])
def test_reject_invalid_paths_and_extensions(cohort_client, name, filename):
"""Pin validation before writes. Fail if an unsafe component or unsupported extension is accepted."""
client, root = cohort_client
response = client.post(f"{COHORTS}/{name}/files", data={"file": (BytesIO(b"edf"), filename)})
assert response.status_code == 400
assert response.json["error"]
assert not root.exists()
def test_reject_a_cohort_symlink(cohort_client, tmp_path):
"""Pin root confinement. Fail if a cohort symlink allows an upload outside the root."""
client, root = cohort_client
outside = tmp_path / "outside"
outside.mkdir()
root.mkdir()
(root / "linked").symlink_to(outside, target_is_directory=True)
response = client.post(f"{COHORTS}/linked/files", data={"file": (BytesIO(b"edf"), "study.edf")})
assert response.status_code == 400
assert not list(outside.iterdir())
assert client.get(COHORTS).json == []
def test_missing_root_configuration(cohort_client, monkeypatch):
"""Pin a 503 on both endpoints. Fail if either silently falls back to a different root."""
client, _ = cohort_client
monkeypatch.delenv("TEA_REFERENCE_ROOT")
for response in (client.get(COHORTS), client.post(f"{COHORTS}/sample/files")):
assert response.status_code == 503
assert response.json["error"]
def test_upload_uses_app_size_limit(cohort_client):
"""Pin the existing JSON 413. Fail if multipart parsing bypasses the configured size limit."""
client, root = cohort_client
client.application.config["MAX_CONTENT_LENGTH"] = 1024
response = client.post(f"{COHORTS}/sample/files", data={"file": (BytesIO(b"x" * 1024), "study.edf")})
assert response.status_code == 413
assert response.json["error"]
assert not root.exists()
+155
View File
@@ -0,0 +1,155 @@
"""Cover governance EEG reads with SQLite recordings and a stub baseline registry.
Fails if the routes misreport analysis outcomes, FHIR counts or drawable metrics.
"""
from datetime import date
from types import SimpleNamespace
from unittest.mock import Mock
import pandas as pd
import pytest
from core.tea.models import Eeg, EegMetrica
from flask import Flask
from persistance import tea
from persistance.repository import Repository
from sqlalchemy import create_engine, event
from sqlmodel import Session
from webapi.blueprints.governance import governance_bp
from webapi.fhir.eeg_curves import BaselineCurves
from webapi.tea import eeg_queries
EEG_URL = "/governance/tea/eeg"
BASELINE_URL = "/governance/tea/baselines/eeg-posterior-rhythm/3"
UUID = "a62321cf-515e-4883-b1b3-48e4202f790c"
CURVE = {"edad_meses": [16.0, 24.0], "p5": [4.0, 5.0], "p25": [5.0, 6.0],
"mediana": [6.0, 7.0], "p75": [7.0, 8.0], "p95": [8.0, 9.0]}
@pytest.fixture
def client():
"""Mount the governance routes so incorrect paths or response handling fail requests."""
app = Flask(__name__)
app.config["TESTING"] = True
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.fixture
def database(monkeypatch):
"""Seed pending, failed, valid and invalid EEGs with scored and unscored metrics to expose miscounts."""
engine = create_engine("sqlite://")
Eeg.__table__.create(engine)
EegMetrica.__table__.create(engine)
with Session(engine) as session:
session.add_all([
Eeg(eeg_id="1", eeg_estudio=b"EDF"),
Eeg(eeg_id="2", eeg_valido=0),
Eeg(eeg_id="10", eeg_error="read failed"),
Eeg(eeg_id=UUID, eeg_valido=1, eeg_nivel="completo", eeg_edad_meses=23.5,
eeg_id_registro_laboratorio="LAB-4", eeg_pac_id=12, eeg_fecha_estudio=date(2025, 4, 3)),
EegMetrica(met_eeg_id=UUID, met_codigo="RITMO_POSTERIOR", met_valor=8.1, met_z=2.5,
met_fuera=1, met_modelo="tea-eeg-posterior-rhythm/3"),
EegMetrica(met_eeg_id=UUID, met_codigo="HUSOS_SUENO_N2", met_valor=0.4),
EegMetrica(met_eeg_id="2", met_codigo="RITMO_POSTERIOR", met_valor=3.1, met_z=-2.5, met_fuera=-1),
EegMetrica(met_eeg_id="2", met_codigo="HUSOS_SUENO_N2"),
])
session.commit()
monkeypatch.setattr(tea, "eeg_repository", Repository(lambda: Session(engine), Eeg))
yield engine
engine.dispose()
@pytest.fixture
def registry(monkeypatch):
"""Resolve one concrete version with one feature curve, so incorrect labels or feature lookups fail."""
expected = ("tea", "eeg-posterior-rhythm", "3")
registry = Mock()
registry.resolve.side_effect = lambda *args: {expected: SimpleNamespace(model_uri="models:/posterior/3")}[args]
module = SimpleNamespace(baselines={"posterior_rhythm_hz": SimpleNamespace(curva=pd.DataFrame(CURVE))})
curves = BaselineCurves(registry=registry, loader=lambda uri: {"models:/posterior/3": module}[uri])
monkeypatch.setattr(eeg_queries, "baseline_curves", lambda: curves)
return registry
def test_recordings_page_without_edf_bytes(client, database):
"""Pin descending IDs, pagination and analysis flags. Fail if the query projects EDF bytes or counts errors as pending."""
statements = []
@event.listens_for(database, "before_cursor_execute")
def capture_sql(connection, cursor, statement, parameters, context, executemany):
statements.append(statement)
response = client.get(EEG_URL)
assert response.status_code == 200
assert response.json == [
{"id": UUID, "lab_id": "LAB-4", "patient_id": 12, "study_date": "2025-04-03", "valid": True,
"analysed": True},
{"id": 10, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": True},
{"id": 2, "lab_id": None, "patient_id": None, "study_date": None, "valid": False, "analysed": True},
{"id": 1, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": False},
]
assert client.get(EEG_URL, query_string={"limit": 2, "offset": 1}).json == response.json[1:3]
assert all("eeg_estudio" not in statement for statement in statements)
def test_recording_page_size(client, database):
"""Pin the default and maximum page sizes. Fail if oversized requests return more than 500 rows."""
with Session(database) as session:
session.add_all(Eeg(eeg_id=str(key)) for key in range(1000, 1501))
session.commit()
assert len(client.get(EEG_URL).json) == 200
assert len(client.get(EEG_URL, query_string={"limit": 1000}).json) == 500
def test_recording_metrics(client, database):
"""Pin metric values and EEG metadata. Fail if UUIDs, null scores or the pinned model label are lost."""
response = client.get(f"{EEG_URL}/{UUID}/metrics")
assert response.status_code == 200
assert response.json == {
"eeg_id": UUID, "valid": True, "level": "completo", "age_months": 23.5,
"metrics": [
{"name": "husos_sueno_n2", "value": 0.4, "z": None, "outside": None, "model": None},
{"name": "ritmo_posterior", "value": 8.1, "z": 2.5, "outside": 1, "model": "tea-eeg-posterior-rhythm/3"},
],
}
assert client.get(f"{EEG_URL}/2/metrics").json == {
"eeg_id": 2, "valid": False, "level": None, "age_months": None,
"metrics": [{"name": "ritmo_posterior", "value": 3.1, "z": -2.5, "outside": -1, "model": None}],
}
missing = client.get(f"{EEG_URL}/999/metrics")
assert missing.status_code == 404 and missing.json["error"]
def test_summary(client, database):
"""Pin stored and FHIR counts. Fail if one missing view hides the other or pending EEGs count as analysed."""
expected = {"eegs": 4, "analysed": 3, "valid": 1, "not_valid": 1, "failed": 1, "metrics": 4,
"metrics_with_z": 2, "high": 1, "low": 1, "fhir_eegs": 0, "fhir_metrics": 0}
assert client.get(f"{EEG_URL}/summary").json == expected
with database.begin() as connection:
connection.exec_driver_sql("CREATE VIEW tea_paciente_eegs AS SELECT eeg_id FROM eeg WHERE eeg_valido = 1")
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1}
with database.begin() as connection:
connection.exec_driver_sql("CREATE VIEW tea_paciente_eeg_metricas AS SELECT met_id FROM eeg_metrica")
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1, "fhir_metrics": 4}
def test_baseline_metrics_and_curve(client, registry):
"""Pin drawable names and the pinned version's series. Fail if routes include missing features or lose metadata."""
assert client.get(f"{BASELINE_URL}/metrics").json == ["ritmo_posterior"]
response = client.get(f"{BASELINE_URL}/curve", query_string={"metric": "ritmo_posterior"})
assert response.status_code == 200
assert response.json == {"scenario": "eeg-posterior-rhythm", "version": 3, "metric": "ritmo_posterior", **CURVE}
registry.resolve.assert_called_once_with("tea", "eeg-posterior-rhythm", "3")
@pytest.mark.parametrize(("scenario", "version", "metric"), [
("eeg-unknown", 3, "ritmo_posterior"),
("eeg-posterior-rhythm", 9, "ritmo_posterior"),
("eeg-posterior-rhythm", 3, "unknown"),
])
def test_missing_curve(client, registry, scenario, version, metric):
"""Pin missing curve responses. Fail if unknown scenarios, versions or metrics return a successful curve."""
response = client.get(f"/governance/tea/baselines/{scenario}/{version}/curve", query_string={"metric": metric})
assert response.status_code == 404 and response.json["error"]
+51
View File
@@ -0,0 +1,51 @@
"""Cover progress lookup with a Flask client and temporary training and analysis folders.
Fails if the route selects the wrong directory or changes the progress response status or shape.
"""
import json
import pytest
from flask import Flask
from webapi.blueprints.governance import governance_bp
@pytest.fixture
def progress_client(tmp_path, monkeypatch):
"""Set up isolated job folders so reading the configured indicator root is required."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.mark.parametrize(("kind", "base"), [("train", "entrenamientos"), ("analyze", "analisis_eeg")])
def test_progress_snapshot(progress_client, tmp_path, kind, base):
"""Pin progress lookup for both job kinds. Fail if missing files succeed or the snapshot is wrapped."""
url = f"/governance/tea/jobs/{kind}/example/progress"
response = progress_client.get(url)
assert response.status_code == 404 and set(response.json) == {"error"}
folder = tmp_path / base / "example"
folder.mkdir(parents=True)
(folder / "job.json").write_text("{}", encoding="utf-8")
response = progress_client.get(url)
assert response.status_code == 404 and set(response.json) == {"error"}
snapshot = {"updated_at": "2026-01-01T00:00:00+00:00", "phase": "midiendo", "done": 2, "total": 10,
"elapsed_s": 1, "eta_s": None, "tasks": None, "cluster": None, "history": []}
(folder / "progress.json").write_text(json.dumps(snapshot), encoding="utf-8")
response = progress_client.get(url)
assert response.status_code == 200
assert response.json == snapshot
response = progress_client.get(f"/governance/tea/jobs/{kind}/nested%2F..%2Fexample/progress")
assert response.status_code == 404 and set(response.json) == {"error"}
def test_unknown_kind(progress_client):
"""Pin invalid kind handling. Fail if an unsupported job kind becomes a missing job."""
response = progress_client.get("/governance/tea/jobs/other/example/progress")
assert response.status_code == 400
assert set(response.json) == {"error"}
+97
View File
@@ -0,0 +1,97 @@
"""What this module covers: `POST /governance/tea/eeg/upload`, which registers one EDF as an EEG through the import
pipeline (`tea.Eeg`, upsert on the laboratory id).
Fixtures: `app_client`, a migrated empty TEA database (`base_de`) behind the real app; `edf`, a synthetic EDF of two
minutes from `models/tests/tea/synth_edf.py` (nothing comes from a patient).
"""
import importlib.util
from pathlib import Path
import pytest
from sqlalchemy import text
SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py"
@pytest.fixture(scope="module")
def edf() -> bytes:
"""A synthetic two-minute EDF, the same file for every test."""
spec = importlib.util.spec_from_file_location("synth_edf", SYNTH)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.edf_bytes(minutes=2)
@pytest.fixture
def app_client(tmp_path):
"""The real app over an empty migrated TEA database; yields (client, engine)."""
from conftest import base_de
from webapi import create_app
base = base_de("tea", tmp_path, datos=lambda session: None)
app = create_app()
app.config.update(TESTING=True)
try:
with app.test_client() as client:
yield client, base.motor
finally:
base.motor.dispose()
def _post(client, edf, name="estudio-1.edf", **form):
from io import BytesIO
return client.post("/governance/tea/eeg/upload", data={"file": (BytesIO(edf), name), **form},
content_type="multipart/form-data")
def test_an_uploaded_edf_becomes_an_eeg_row(app_client, edf):
"""Pins down: a valid EDF is stored in `eeg` with its file, and the answer carries the new id and the lab id.
Fails if the route stops going through the `tea.Eeg` import (no row, no bytes, or no id in the answer).
"""
client, engine = app_client
response = _post(client, edf)
assert response.status_code == 201, response.get_json()
body = response.get_json()
assert body["created"] is True and body["eeg_id"] is not None and body["lab_id"]
with engine.connect() as connection:
stored = connection.execute(text("select length(eeg_estudio), eeg_pac_id from eeg")).one()
assert stored[0] == len(edf) and stored[1] is None
def test_uploading_the_same_study_twice_updates_it(app_client, edf):
"""Pins down: the laboratory id is the natural key, so a second upload updates the row and does not add one.
Fails if the upsert policy is lost and the study is duplicated or rejected.
"""
client, engine = app_client
first = _post(client, edf).get_json()
second = _post(client, edf)
assert second.status_code == 201
assert second.get_json()["created"] is False and second.get_json()["eeg_id"] == first["eeg_id"]
with engine.connect() as connection:
assert connection.execute(text("select count(*) from eeg")).scalar() == 1
def test_a_file_that_is_not_an_edf_is_refused(app_client):
"""Pins down: bytes MNE cannot open answer 400 with a message and write nothing.
Fails if the connector's validation is bypassed and garbage reaches the table.
"""
client, engine = app_client
response = _post(client, b"not an edf at all")
assert response.status_code == 400 and response.get_json()["error"]
with engine.connect() as connection:
assert connection.execute(text("select count(*) from eeg")).scalar() == 0
def test_the_request_needs_a_file_and_a_numeric_patient(app_client, edf):
"""Pins down: a missing `file` and a non-numeric `patient_id` are 400s before any import runs.
Fails if the form is read without checking, which would turn bad input into a 500.
"""
client, _ = app_client
assert client.post("/governance/tea/eeg/upload", data={}).status_code == 400
assert _post(client, edf, patient_id="abc").status_code == 400
+86
View File
@@ -0,0 +1,86 @@
"""What this module covers: the cluster choice of an indicator recomputation: how `POST /reportes/indicadores/<d>/recalcular`
validates it, how the queue carries it in the pending marker, and how the worker applies it to one run only.
Fixtures: `queue`, a `RecomputationQueue` over a temporary folder.
"""
import json
import os
import pytest
from flask import Flask
from webapi.blueprints.reports import reports_bp
from webapi.recomputation import RecomputationQueue, _cluster_override
@pytest.fixture
def queue(tmp_path, monkeypatch):
"""A queue over an empty temporary folder, which the route also uses through INDICADORES_DIR."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
return RecomputationQueue(tmp_path)
@pytest.fixture
def client(queue):
"""The reports blueprint alone, over the same folder as `queue`."""
app = Flask(__name__)
app.register_blueprint(reports_bp, url_prefix="/reportes")
return app.test_client()
def test_a_request_carries_its_cluster_choice_to_the_worker(queue):
"""Pins down: the marker keeps the choice, `requested_cluster` reads it back, and a plain request has none.
Fails if `request_run` drops the choice or the marker stops being readable after a plain request.
"""
queue.request_run("tea", {"mode": "local"})
assert queue.requested_cluster("tea") == {"mode": "local"}
queue.request_run("tea")
assert queue.requested_cluster("tea") is None
assert queue.requested_cluster("cacu") is None
def test_a_marker_written_as_plain_text_still_counts_as_pending(queue):
"""Pins down: a marker left by an older version (a bare timestamp) is pending and has no cluster choice.
Fails if the worker starts to crash on, or ignore, markers that are not JSON.
"""
queue._pending.mkdir(parents=True)
(queue._pending / "tea").write_text("2026-01-01T00:00:00+00:00", encoding="utf-8")
assert queue.pending() == ["tea"] and queue.requested_cluster("tea") is None
def test_the_route_validates_and_queues_the_choice(client, queue):
"""Pins down: a valid choice is queued (202), a bad mode, a non-object body and `remote` without a scheduler are
400s that queue nothing, and no body keeps working.
Fails if the route queues unchecked input, or stops accepting the body-less call the UI used before.
"""
ok = client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "local"}})
assert ok.status_code == 202 and queue.requested_cluster("tea") == {"mode": "local"}
for bad in ({"cluster": {"mode": "nope"}}, ["x"]):
assert client.post("/reportes/indicadores/tea/recalcular", json=bad).status_code == 400
os.environ.pop("DASK_SCHEDULER_ADDRESS", None)
assert client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "remote"}}).status_code == 400
assert client.post("/reportes/indicadores/tea/recalcular").status_code == 202
def test_a_run_applies_the_choice_and_then_restores_the_environment(monkeypatch):
"""Pins down: during the run the choice is in the environment (`local` drops the scheduler), and afterwards the
process environment is exactly as before, even when the run fails.
Fails if one run's choice leaks into the next runs of the worker.
"""
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:1")
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
before = dict(os.environ)
with _cluster_override({"mode": "local"}):
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "local" and "DASK_SCHEDULER_ADDRESS" not in os.environ
assert dict(os.environ) == before
with pytest.raises(RuntimeError):
with _cluster_override({"mode": "remote", "scheduler": "tcp://other:2"}):
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://other:2"
raise RuntimeError("boom")
assert dict(os.environ) == before
with _cluster_override(None):
assert dict(os.environ) == before
+146
View File
@@ -0,0 +1,146 @@
"""Cover the analysis job routes with captured launches and saved job files.
Fixtures: analysis_client supplies the Flask routes, a temporary job directory and EEG rows.
Fails if scope or cluster options are lost, or persisted jobs change their API shape or order.
"""
import json
import os
import sys
from types import SimpleNamespace
import pytest
from flask import Flask
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine
from core.tea.models import Eeg
from persistance.tea import eeg_repository
from webapi import detached_jobs
from webapi.blueprints.governance import governance_bp
URL = "/governance/tea/eeg/analyze-jobs"
SUMMARY = {"pending": 3, "valid": 1, "not_valid": 1, "failed": 1}
@pytest.fixture
def analysis_client(tmp_path, monkeypatch):
"""Supply EEG IDs 1 and 2 (numeric) and two UUID ids, and capture child launches to detect invalid launches and lost options."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
monkeypatch.delenv("DASK_SCHEDULER_ADDRESS", raising=False)
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
launches = []
engine = create_engine("sqlite://", poolclass=StaticPool)
Eeg.__table__.create(engine)
with Session(engine) as session:
session.add_all([Eeg(eeg_id="1", eeg_estudio=b"edf"), Eeg(eeg_id="2"),
Eeg(eeg_id="ed257fbd-61d5-4c9c-bb72-00c4ec550961", eeg_estudio=b"edf"),
Eeg(eeg_id="a735a43f-376a-403a-b19f-13670130152a", eeg_estudio=b"edf")])
session.commit()
def popen(argv, **kwargs):
launches.append((argv[4:], kwargs["env"]))
return SimpleNamespace(pid=os.getpid())
monkeypatch.setattr(detached_jobs.subprocess, "Popen", popen)
monkeypatch.setattr(eeg_repository, "open_session", lambda: Session(engine))
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
yield app.test_client(), launches
engine.dispose()
@pytest.mark.parametrize("body,flags", [
({}, []),
({"all": False}, []),
({"all": True}, ["--all"]),
({"limit": 4}, ["--limit", "4"]),
({"ids": [1, 2]}, ["--ids", "1,2"]),
({"ids": ["ed257fbd-61d5-4c9c-bb72-00c4ec550961", "a735a43f-376a-403a-b19f-13670130152a"]},
["--ids", "ed257fbd-61d5-4c9c-bb72-00c4ec550961,a735a43f-376a-403a-b19f-13670130152a"]),
])
def test_launch_scope(analysis_client, tmp_path, body, flags):
"""Pin scope flags, response fields and the progress directory. Fail if launch wiring changes."""
client, launches = analysis_client
response = client.post(URL, json=body)
assert response.status_code == 202
assert launches[0][0] == [sys.executable, "-m", "models", "tea", "analyze", *flags, "--cluster", "auto"]
assert response.json.keys() == {"id", "iniciado", "estado", "codigo", "salida", "error", "cluster", "ids", "summary"}
folder = tmp_path / "analisis_eeg" / response.json["id"]
assert launches[0][1]["RUN_PROGRESS_DIR"] == str(folder)
assert response.json["ids"] == ([str(i) for i in body["ids"]] if "ids" in body else None)
assert response.json["cluster"] is response.json["summary"] is None
@pytest.mark.parametrize("choice,mode,scheduler", [
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
({"mode": "local"}, "local", None),
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
])
def test_cluster_choice(analysis_client, monkeypatch, choice, mode, scheduler):
"""Pin the cluster flag and training-style child environment. Fail if either loses the requested choice."""
client, launches = analysis_client
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
response = client.post(URL, json={"cluster": choice})
assert response.status_code == 202
argv, env = launches[0]
assert argv[-2:] == ["--cluster", choice["mode"]]
assert env["EEG_ANALYSIS_CLUSTER"] == mode
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
assert response.json["cluster"] == (dict(choice, scheduler=scheduler) if mode == choice["mode"] == "remote" else choice)
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
@pytest.mark.parametrize("body", [
[], {"all": 1}, {"limit": 0}, {"limit": True}, {"ids": []}, {"ids": [True]}, {"ids": None}, {"ids": ["a,b"]}, {"ids": [" "]}, {"ids": ["x" * 65]},
{"ids": [1], "all": True}, {"ids": [1], "limit": 2}, {"all": True, "limit": 2},
{"cluster": {"mode": "remote"}}, {"cluster": {"mode": "invalid"}},
])
def test_invalid_options(analysis_client, body):
"""Pin 400 for invalid options. Fail if malformed scopes or cluster choices launch a child."""
client, launches = analysis_client
assert client.post(URL, json=body).status_code == 400
assert not launches
def test_unknown_eeg_ids(analysis_client):
"""Pin 404 and the missing IDs. Fail if an unknown EEG reaches the child."""
client, launches = analysis_client
response = client.post(URL, json={"ids": [1, 99, 98]})
assert response.status_code == 404
assert "98, 99" in response.json["error"]
assert not launches
def test_refuses_second_analysis(analysis_client):
"""Pin the running-job conflict. Fail if a blank request can launch a concurrent analysis."""
client, launches = analysis_client
assert client.post(URL).status_code == 202
assert client.post(URL).status_code == 409
assert len(launches) == 1
def test_saved_jobs_report_summary_and_list_newest_first(analysis_client, tmp_path):
"""Pin summary parsing after exit and descending job order. Fail if a running job exposes counts."""
client, _ = analysis_client
older, newer = "20260101T000000-aaaaaa", "20260102T000000-bbbbbb"
for job_id in (newer, older):
folder = tmp_path / "analisis_eeg" / job_id
folder.mkdir(parents=True)
(folder / "job.json").write_text(json.dumps({"id": job_id, "pid": os.getpid(), "iniciado": job_id}))
(folder / "stdout.log").write_text(f"analysis output\nsummary: {json.dumps(SUMMARY)}\n")
if job_id == older:
(folder / "exit").write_text("1\n")
jobs = client.get(URL).json
assert [job["id"] for job in jobs] == [newer, older]
assert jobs[0]["estado"] == "en_curso" and jobs[0]["summary"] is None
assert jobs[1]["estado"] == "fallido" and jobs[1]["summary"] == SUMMARY
assert client.get(f"{URL}/{older}").json == jobs[1]
assert client.get(f"{URL}/unknown").status_code == 404
+228
View File
@@ -0,0 +1,228 @@
"""Cover TEA training options and compatibility through the governance route.
Fixtures: training_client uses a temporary job directory and captures subprocess launches.
Fails if request options stop controlling argv, the child environment, or persisted state.
"""
import json
import os
import sys
from types import SimpleNamespace
import pytest
from flask import Flask
from webapi import training_jobs
from webapi.blueprints.governance import governance_bp
TRAIN_URL = "/governance/model-versions/tea/eeg/train-jobs"
@pytest.fixture
def training_client(tmp_path, monkeypatch):
"""Capture training launches. Real subprocesses would bypass the captured argv and environment."""
for variable in (*training_jobs.REFERENCE_ENV.values(), "TEA_REFERENCE_ROOT",
"DASK_SCHEDULER_ADDRESS", "EEG_ANALYSIS_CLUSTER"):
monkeypatch.delenv(variable, raising=False)
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
launches = []
def popen(argv, **kwargs):
launches.append((argv[4:], kwargs["env"]))
return SimpleNamespace(pid=os.getpid())
monkeypatch.setattr(training_jobs.subprocess, "Popen", popen)
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client(), launches
def test_body_overrides_reference_environment(training_client, monkeypatch, tmp_path):
"""Pin body precedence and persisted choices. Fail if an override or flag is lost."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
monkeypatch.setenv("TEA_REFERENCE_NAME", "fallback")
monkeypatch.setenv("TEA_REFERENCE_DIR", str(tmp_path / "fallback"))
monkeypatch.setenv("TEA_REFERENCE_AGES", str(tmp_path / "fallback.csv"))
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "60")
body = {
"reference_name": "cohort-1",
"reference_dir": str(tmp_path / "cohort"),
"reference_ages": str(tmp_path / "ages.csv"),
"line_hz": 50,
"promote": False,
"cluster": {"mode": "local"},
}
response = client.post(TRAIN_URL, json=body)
assert response.status_code == 202
job = response.json["job"]
assert job["cluster"] == body["cluster"]
argv, _ = launches[0]
assert argv == [
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train",
"--reference-dir", body["reference_dir"], "--reference-ages", body["reference_ages"],
"--line-hz", "50", "--reference-name", "cohort-1",
]
folder = tmp_path / "entrenamientos" / job["id"]
saved = json.loads((folder / "job.json").read_text())
assert saved["parameters"] == {key: value for key, value in body.items() if key != "cluster"}
assert saved["cluster"] == body["cluster"]
assert client.get(f"/governance/training-jobs/{job['id']}").json["job"]["cluster"] == body["cluster"]
def test_reference_name_can_be_passed_without_a_directory(training_client):
"""Pin a name-only request. Fail if the flag becomes conditional on a reference directory."""
client, launches = training_client
response = client.post(TRAIN_URL, json={"reference_name": "cohort-1", "promote": True})
assert response.status_code == 202
argv, _ = launches[0]
assert argv[-2:] == ["--reference-name", "cohort-1"]
assert "--reference-dir" not in argv
assert "--promote" in argv
@pytest.mark.parametrize("cluster,mode,scheduler", [
(None, "remote", "tcp://inherited:8786"),
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
({"mode": "local"}, "local", None),
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
])
def test_cluster_changes_only_the_child_environment(training_client, monkeypatch, cluster, mode, scheduler):
"""Pin cluster variables and scheduler fallback. Fail if mode leaks into argv or the parent."""
client, launches = training_client
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
response = client.post(TRAIN_URL, json={"cluster": cluster} if cluster else {})
assert response.status_code == 202
choice = {"mode": "remote", "scheduler": scheduler} if cluster == {"mode": "remote"} else cluster
assert response.json["job"]["cluster"] == choice
argv, env = launches[0]
assert argv == [sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote"]
assert env["EEG_ANALYSIS_CLUSTER"] == mode
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "remote"
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
@pytest.mark.parametrize("field", ["reference_dir", "reference_ages"])
def test_reference_paths_must_resolve_inside_root(training_client, monkeypatch, tmp_path, field):
"""Pin containment after symlink resolution. Fail if a local path can escape the root."""
client, launches = training_client
root = tmp_path / "reference"
root.mkdir()
(root / "escape").symlink_to(tmp_path, target_is_directory=True)
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
response = client.post(TRAIN_URL, json={field: str(root / "escape")})
assert response.status_code == 400
assert field in response.json["error"]
assert not launches
def test_remote_reference_can_be_outside_root(training_client, monkeypatch, tmp_path):
"""Pin the remote path exemption. Fail if worker paths are rejected by the API root check."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
response = client.post(TRAIN_URL, json={
"reference_dir": "/worker/reference",
"cluster": {"mode": "remote", "scheduler": "tcp://chosen:8786"},
})
assert response.status_code == 202
assert "/worker/reference" in launches[0][0]
def test_remote_requires_a_scheduler(training_client):
"""Pin the missing-scheduler response. Fail if an unconfigured remote job starts."""
client, launches = training_client
response = client.post(TRAIN_URL, json={"cluster": {"mode": "remote"}})
assert response.status_code == 400
assert "DASK_SCHEDULER_ADDRESS" in response.json["error"]
assert not launches
@pytest.mark.parametrize("request_options", [{}, {"json": {}}])
def test_empty_body_keeps_environment_defaults(training_client, monkeypatch, tmp_path, request_options):
"""Pin launch defaults and the progress folder. Fail if either is lost for an empty request."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_DIR", "/reference")
monkeypatch.setenv("TEA_REFERENCE_AGES", "/reference/ages.csv")
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "50")
response = client.post(TRAIN_URL, **request_options)
assert response.status_code == 202
assert response.json["job"]["cluster"] is None
argv, env = launches[0]
folder = tmp_path / "entrenamientos" / response.json["job"]["id"]
assert env == {**os.environ, "RUN_PROGRESS_DIR": str(folder)}
assert argv == [
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote",
"--reference-dir", "/reference", "--reference-ages", "/reference/ages.csv", "--line-hz", "50",
]
@pytest.mark.parametrize("body", [
{"reference_name": "nested/cohort"},
{"reference_name": "a" * 65},
{"reference_dir": "relative"},
{"line_hz": 55},
{"promote": "false"},
{"cluster": {"mode": "unknown"}},
[],
])
def test_invalid_body_options_are_rejected(training_client, body):
"""Pin JSON and option validation. Fail if an invalid value reaches the subprocess."""
client, launches = training_client
response = client.post(TRAIN_URL, json=body)
assert response.status_code == 400
assert response.json["error"]
assert not launches
def test_a_named_cohort_is_trained_from_its_folder_and_ages(training_client, monkeypatch, tmp_path):
"""Pin that a cohort name with a folder under `TEA_REFERENCE_ROOT` launches with that folder, its `edades.csv`
and the chosen line frequency. Fail if the name stays a bare label, which the child rejects without a directory."""
client, launches = training_client
cohort = tmp_path / "tiny"
cohort.mkdir()
(cohort / "edades.csv").write_text("archivo,edad_meses\na.edf,20\n")
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
response = client.post(TRAIN_URL, json={"reference_name": "tiny", "line_hz": 50, "promote": False})
assert response.status_code == 202
argv, _ = launches[0]
assert argv[argv.index("--reference-dir") + 1] == str(cohort.resolve())
assert argv[argv.index("--reference-ages") + 1] == str((cohort / "edades.csv").resolve())
assert argv[argv.index("--line-hz") + 1] == "50"
assert argv[argv.index("--reference-name") + 1] == "tiny"
def test_an_explicit_directory_wins_over_the_cohort_folder(training_client, monkeypatch, tmp_path):
"""Pin that a request giving `reference_dir` is never redirected to the cohort named beside it.
Fail if resolving a name overrides a directory the caller chose."""
client, launches = training_client
(tmp_path / "tiny").mkdir()
(tmp_path / "other").mkdir()
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
client.post(TRAIN_URL, json={"reference_name": "tiny", "reference_dir": str(tmp_path / "other")})
argv, _ = launches[0]
assert argv[argv.index("--reference-dir") + 1] == str((tmp_path / "other").resolve())
assert "--reference-ages" not in argv