diff --git a/tests/test_governance_tea_baselines.py b/tests/test_governance_tea_baselines.py new file mode 100644 index 0000000..4fb00a9 --- /dev/null +++ b/tests/test_governance_tea_baselines.py @@ -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"] diff --git a/tests/test_governance_tea_cluster.py b/tests/test_governance_tea_cluster.py new file mode 100644 index 0000000..a2bc144 --- /dev/null +++ b/tests/test_governance_tea_cluster.py @@ -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) diff --git a/tests/test_governance_tea_cohorts.py b/tests/test_governance_tea_cohorts.py new file mode 100644 index 0000000..e0bea66 --- /dev/null +++ b/tests/test_governance_tea_cohorts.py @@ -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() diff --git a/tests/test_governance_tea_eeg_queries.py b/tests/test_governance_tea_eeg_queries.py new file mode 100644 index 0000000..79dd5d2 --- /dev/null +++ b/tests/test_governance_tea_eeg_queries.py @@ -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"] diff --git a/tests/test_governance_tea_progress.py b/tests/test_governance_tea_progress.py new file mode 100644 index 0000000..7c9a97f --- /dev/null +++ b/tests/test_governance_tea_progress.py @@ -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"} diff --git a/tests/test_governance_tea_upload.py b/tests/test_governance_tea_upload.py new file mode 100644 index 0000000..a167b13 --- /dev/null +++ b/tests/test_governance_tea_upload.py @@ -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 diff --git a/tests/test_recomputation_cluster.py b/tests/test_recomputation_cluster.py new file mode 100644 index 0000000..c707346 --- /dev/null +++ b/tests/test_recomputation_cluster.py @@ -0,0 +1,86 @@ +"""What this module covers: the cluster choice of an indicator recomputation: how `POST /reportes/indicadores//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 diff --git a/tests/test_tea_analyze_jobs.py b/tests/test_tea_analyze_jobs.py new file mode 100644 index 0000000..74ec040 --- /dev/null +++ b/tests/test_tea_analyze_jobs.py @@ -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 diff --git a/tests/test_training_jobs_params.py b/tests/test_training_jobs_params.py new file mode 100644 index 0000000..2b99705 --- /dev/null +++ b/tests/test_training_jobs_params.py @@ -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 diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index 34f867d..6bb5aaf 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -18,6 +18,7 @@ import os from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict from pathlib import Path +from tempfile import NamedTemporaryFile from urllib.parse import quote from core.governance.enums import EstatusExtraccion @@ -32,6 +33,10 @@ from models.reports import experiment from persistance.governance import extraction_run_repository from persistance.repository import Repository from persistance.settings import settings +from werkzeug.wsgi import wrap_file + +from webapi.tea.analyze_jobs import AnalysisRunning, AnalyzeJobs +from webapi.tea.reference_cohorts import ReferenceCohortStore governance_bp = Blueprint("governance", __name__) @@ -57,6 +62,108 @@ def _pk_name(repository: Repository) -> str: return next(iter(repository.model.__table__.primary_key.columns)).name +@governance_bp.get("/tea/cluster") +def tea_cluster_status(): + """Report health for a configured TEA cluster.""" + from tea.pipeline.cluster_status import ClusterStatus + + scheduler = request.args.get("scheduler") + if scheduler is not None: + allowed = { + address.strip() + for address in os.environ.get("TEA_DASK_SCHEDULERS", "").split(",") + if address.strip() + } + if not scheduler or ( + scheduler != os.environ.get("DASK_SCHEDULER_ADDRESS") and scheduler not in allowed + ): + raise ValueError("El planificador Dask no está autorizado.") + + return jsonify(ClusterStatus().check( + mode=request.args.get("mode", "auto"), + scheduler=scheduler, + reference_name=request.args.get("reference"), + )) + + +@governance_bp.get("/tea/reference-cohorts") +def list_reference_cohorts(): + """List the stored TEA reference cohorts.""" + root = os.environ.get("TEA_REFERENCE_ROOT") + if not root: + return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503 + return jsonify(ReferenceCohortStore(root).list_cohorts()) + + +@governance_bp.post("/tea/reference-cohorts//files") +def upload_reference_cohort_file(name: str): + """Add an EDF or an age table to a reference cohort.""" + root = os.environ.get("TEA_REFERENCE_ROOT") + if not root: + return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503 + upload = request.files.get("file") + if upload is None or not upload.filename: + return jsonify({"error": "Se requiere el campo file."}), 400 + return jsonify(ReferenceCohortStore(root).save_file(name, upload.filename, upload.stream)), 201 + + +@governance_bp.get("/tea/baselines/export") +def export_baselines(): + """Download trained EEG baselines as a ZIP.""" + from webapi.tea.baselines import BaselineBundles + + production = request.args.get("production", "0") + if production not in ("0", "1"): + return jsonify({"error": "production debe ser 0 o 1."}), 400 + + archive = NamedTemporaryFile(suffix=".zip") + try: + exported = BaselineBundles().export( + Path(archive.name), environment=request.args.get("environment", "prod"), production=production == "1" + ) + response = Response(wrap_file(request.environ, archive), mimetype="application/zip") + response.headers["Content-Disposition"] = "attachment; filename=baselines.zip" + response.headers["X-Baselines-Sha256"] = exported.sha256 + response.headers["X-Baselines-Versions"] = str(len(exported.versions)) + return response + except BaseException: + archive.close() + raise + + +@governance_bp.post("/tea/baselines/import") +def import_baselines(): + """Register trained EEG baselines from an uploaded ZIP.""" + from webapi.tea.baselines import BaselineBundles, BaselineConflict + + upload = request.files.get("file") + if upload is None or not upload.filename: + return jsonify({"error": "Se requiere el campo file."}), 400 + try: + return jsonify(BaselineBundles().import_(upload.stream)) + except BaselineConflict as error: + return jsonify({"error": str(error)}), 409 + + +@governance_bp.post("/tea/eeg/upload") +def upload_eeg(): + """Register one EDF file as an EEG through the import pipeline.""" + from webapi.imports.services.import_service import ImportRequestError + from webapi.tea.edf_intake import EdfIntake + + upload = request.files.get("file") + if upload is None or not upload.filename: + return jsonify({"error": "Se requiere el campo file."}), 400 + patient = request.form.get("patient_id", "").strip() + if patient and not patient.isdigit(): + return jsonify({"error": "patient_id debe ser un entero."}), 400 + try: + added = EdfIntake().add(upload.filename, upload.read(), int(patient) if patient else None) + except (ImportRequestError, ValueError) as error: + return jsonify({"error": str(error)}), 400 + return jsonify(added), 201 + + # -- model versions ---------------------------------------------------------------- @@ -142,6 +249,11 @@ def start_training_job(domain: str, scenario: str): return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.", "job": training_jobs.running(domain, scenario)}), 409 try: + if domain == "tea" and request.get_data(): + body = request.get_json(silent=True) + if not isinstance(body, dict): + raise ValueError("El cuerpo debe ser un objeto JSON.") + return jsonify({"job": training_jobs.start(domain, scenario, body)}), 202 return jsonify({"job": training_jobs.start(domain, scenario)}), 202 except RuntimeError as error: return jsonify({"error": str(error)}), 503 @@ -441,6 +553,49 @@ def correct_ocr_row(domain: str, entity: str, pk: int): return jsonify(updated) +@governance_bp.post("/tea/eeg/analyze-jobs") +def start_analyze_job(): + """Start a detached EEG analysis.""" + body = request.get_json(silent=True) if request.get_data() else {} + try: + return jsonify(AnalyzeJobs().start(body)), 202 + except AnalysisRunning as error: + return jsonify({"error": str(error)}), 409 + + +@governance_bp.get("/tea/eeg/analyze-jobs") +def list_analyze_jobs(): + """List detached EEG analyses.""" + return jsonify(AnalyzeJobs().jobs()) + + +@governance_bp.get("/tea/eeg/analyze-jobs/") +def analyze_job(job_id: str): + """Read a detached EEG analysis.""" + return jsonify(AnalyzeJobs().get(job_id)) + + +@governance_bp.get("/tea/jobs///progress") +def tea_job_progress(kind: str, job_id: str): + """Read the latest progress snapshot for a detached TEA job.""" + from webapi import training_jobs + + if kind == "train": + base = training_jobs._base() + elif kind == "analyze": + base = AnalyzeJobs().base + else: + raise ValueError("Tipo de trabajo TEA no válido.") + + folder = base / job_id + if "/" not in job_id and job_id not in {".", ".."} and (folder / "job.json").is_file(): + try: + return jsonify(json.loads((folder / "progress.json").read_text(encoding="utf-8"))) + except FileNotFoundError: + pass + raise LookupError(f"No se encontró el progreso del trabajo {job_id}.") + + @governance_bp.post("/eeg/run") def run_eeg_analysis(): """Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most @@ -495,3 +650,47 @@ def run_ocr(): "needs_review": summary.needs_review, } ) + + +@governance_bp.get("/tea/baselines///metrics") +def tea_baseline_metrics(scenario: str, version: int): + """List the metrics with a curve in the baseline version.""" + from webapi.tea.eeg_queries import BaselineQueries + + return jsonify(BaselineQueries(scenario, version).metrics()) + + +@governance_bp.get("/tea/baselines///curve") +def tea_baseline_curve(scenario: str, version: int): + """Read a metric's curve from the baseline version.""" + from webapi.tea.eeg_queries import BaselineQueries + + return jsonify(BaselineQueries(scenario, version).curve(request.args.get("metric", "").lower())) + + +@governance_bp.get("/tea/eeg") +def tea_eeg_recordings(): + """List EEG recordings with their analysis status.""" + from webapi.tea.eeg_queries import EegQueries + + limit = int(request.args.get("limit", 200)) + offset = int(request.args.get("offset", 0)) + if limit < 0 or offset < 0: + raise ValueError("El límite y el desplazamiento deben ser mayores o iguales a cero.") + return jsonify(EegQueries().recordings(limit, offset)) + + +@governance_bp.get("/tea/eeg//metrics") +def tea_eeg_metrics(eeg_id: str): + """Read one EEG's verdict and metric values.""" + from webapi.tea.eeg_queries import EegQueries + + return jsonify(EegQueries().metrics(eeg_id)) + + +@governance_bp.get("/tea/eeg/summary") +def tea_eeg_summary(): + """Count EEG analysis outcomes and FHIR view rows.""" + from webapi.tea.eeg_queries import EegQueries + + return jsonify(EegQueries().summary()) diff --git a/webapi/blueprints/reports.py b/webapi/blueprints/reports.py index 74a587a..2b23ee6 100644 --- a/webapi/blueprints/reports.py +++ b/webapi/blueprints/reports.py @@ -1,7 +1,10 @@ """Aggregate reports: the log of import attempts and the state of the live indicator recomputation. Nothing here returns row-level data.""" +import os + from flask import Blueprint, Response, jsonify, request +from webapi.detached_jobs import cluster_environment from webapi.imports import audit as import_audit from webapi.recomputation import DOMAINS, RecomputationQueue @@ -45,5 +48,12 @@ def recomputation_status(): def recompute(dominio: str): if dominio not in DOMAINS: return jsonify({"error": f"dominio desconocido: {dominio}"}), 404 - RecomputationQueue().request_run(dominio) + body = request.get_json(silent=True) if request.get_data() else {} + if not isinstance(body, dict): + return jsonify({"error": "El cuerpo debe ser un objeto JSON."}), 400 + try: + cluster = cluster_environment(body, dict(os.environ)) + except ValueError as error: + return jsonify({"error": str(error)}), 400 + RecomputationQueue().request_run(dominio, cluster) return jsonify({"pendiente": True}), 202 diff --git a/webapi/detached_jobs.py b/webapi/detached_jobs.py new file mode 100644 index 0000000..00ac5e2 --- /dev/null +++ b/webapi/detached_jobs.py @@ -0,0 +1,90 @@ +"""File-backed state and launch support for detached jobs.""" + +import json +import os +import subprocess +import uuid +from datetime import datetime, timezone +from pathlib import Path + +TAIL_CHARS = 4000 + + +def cluster_environment(body: dict, env: dict[str, str]) -> dict | None: + """Apply a cluster choice to the child environment.""" + if "cluster" not in body: + return None + cluster = body["cluster"] + if not isinstance(cluster, dict) or cluster.get("mode") not in ("auto", "local", "remote", "sync"): + raise ValueError("cluster.mode debe ser auto, local, remote o sync.") + mode = cluster["mode"] + scheduler = cluster.get("scheduler") + if "scheduler" in cluster and (not isinstance(scheduler, str) or not scheduler.strip() or "\0" in scheduler): + raise ValueError("cluster.scheduler debe ser texto no vacío.") + if mode == "auto": + return {"mode": mode} + env["EEG_ANALYSIS_CLUSTER"] = mode + if mode == "local": + env.pop("DASK_SCHEDULER_ADDRESS", None) + if mode == "remote": + scheduler = scheduler or env.get("DASK_SCHEDULER_ADDRESS") + if not scheduler: + raise ValueError("El modo remote requiere cluster.scheduler o DASK_SCHEDULER_ADDRESS.") + env["DASK_SCHEDULER_ADDRESS"] = scheduler + return {"mode": mode, "scheduler": scheduler} + return {"mode": mode} + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +def _tail(path: Path) -> str: + return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else "" + + +def state(folder: Path) -> dict: + """Read job metadata, logs, and process state.""" + job = json.loads((folder / "job.json").read_text(encoding="utf-8")) + exit_file = folder / "exit" + code = int(exit_file.read_text().strip() or 1) if exit_file.exists() else None + out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log") + if code == 0: + status = "completado" + elif code is not None: + status = "fallido" + else: + status = "en_curso" if _alive(job["pid"]) else "interrumpido" + return {**job, "estado": status, "codigo": code, "salida": out, "error": err} + + +def launch(base: Path, argv: list[str], env: dict[str, str], metadata: dict, *, + precise_id: bool = False, cwd: Path | None = None) -> Path: + """Start a detached command and publish its job metadata.""" + now = datetime.now(timezone.utc) + timestamp = now.strftime("%Y%m%dT%H%M%S%f" if precise_id else "%Y%m%dT%H%M%S") + job_id = f"{timestamp}-{uuid.uuid4().hex[:6]}" + folder = base / job_id + folder.mkdir(parents=True) + shell = '{ "$@" > "$0/stdout.log" 2> "$0/stderr.log"; echo $? > "$0/exit.tmp"; mv "$0/exit.tmp" "$0/exit"; }' + process = subprocess.Popen(["sh", "-c", shell, str(folder.resolve()), *argv], + cwd=cwd or folder, env={**env, "RUN_PROGRESS_DIR": str(folder.resolve())}, + start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + job = {**metadata, "id": job_id, "pid": process.pid, + "iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")} + temporary = folder / "job.json.tmp" + temporary.write_text(json.dumps(job), encoding="utf-8") + temporary.replace(folder / "job.json") + return folder + + +def folders(base: Path) -> list[Path]: + """List published jobs newest first by their timestamped IDs.""" + return sorted((path for path in base.glob("*") if (path / "job.json").exists()), reverse=True) diff --git a/webapi/recomputation.py b/webapi/recomputation.py index a6b8370..5c29275 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -24,6 +24,7 @@ import os import signal import threading import time +from contextlib import contextmanager from datetime import date, datetime, timezone from pathlib import Path from typing import Any @@ -48,34 +49,21 @@ def _short(value: Any) -> str: return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…" -def _warm_models(dominio: str) -> dict[str, Any]: - """Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build, - and their scenario points computed by the pipeline over those members.""" - from webapi.model_analysis import refresh_subgroups, warm +@contextmanager +def _cluster_override(cluster: dict | None): + """Applies a cluster choice to this process's environment while a run lasts, then restores it.""" + if not cluster: + yield + return + from webapi.detached_jobs import cluster_environment - started = time.monotonic() + saved = dict(os.environ) try: - resumen = {"cargados": warm(dominio), "escenarios_recalculados": refresh_subgroups(dominio)} - except Exception as exc: # the indicators are already saved - log.exception("no se pudieron preparar los modelos de %s", dominio) - resumen = f"error: {type(exc).__name__}" - return {"paso": "modelos", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)} - - -def _answer_measures(dominio: str) -> dict[str, Any]: - """Leaves each measure's latest periods answered with what this run loaded (`webapi.kpis.answer_latest`).""" - from importlib import import_module - - from webapi.kpis import answer_latest - - started = time.monotonic() - manifest = os.environ.get("DBT_MANIFEST") - try: - resumen = answer_latest(dominio, import_module(f"persistance.{dominio}"), Path(manifest)) if manifest else "sin DBT_MANIFEST" - except Exception as exc: # the indicators are already saved - log.exception("no se pudieron responder los indicadores de %s", dominio) - resumen = f"error: {type(exc).__name__}" - return {"paso": "respuestas", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)} + cluster_environment({"cluster": cluster}, os.environ) + yield + finally: + os.environ.clear() + os.environ.update(saved) class RecomputationQueue: @@ -92,11 +80,20 @@ class RecomputationQueue: def _status_path(self) -> Path: return self.base / "estado.json" - def request_run(self, dominio: str) -> None: + def request_run(self, dominio: str, cluster: dict | None = None) -> None: + """Queues a run; `cluster` (`{mode, scheduler?}`) picks where the EEG analysis of that run executes.""" if dominio not in DOMAINS: raise ValueError(f"dominio desconocido: {dominio!r}") self._pending.mkdir(parents=True, exist_ok=True) - (self._pending / dominio).write_text(_now(), encoding="utf-8") + (self._pending / dominio).write_text(json.dumps({"at": _now(), "cluster": cluster}), encoding="utf-8") + + def requested_cluster(self, dominio: str) -> dict | None: + """The cluster choice of the queued request, or none for a plain one.""" + try: + marker = json.loads((self._pending / dominio).read_text(encoding="utf-8")) + except (FileNotFoundError, json.JSONDecodeError): + return None + return marker.get("cluster") if isinstance(marker, dict) else None def pending(self) -> list[str]: if not self._pending.exists(): @@ -133,8 +130,10 @@ class RecomputationQueue: tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8") tmp.replace(self._status_path) - def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: - """Runs the domain's graph (without `migrate`: the API migrates on startup).""" + def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None, + cluster: dict | None = None) -> dict[str, Any]: + """Runs the domain's graph (without `migrate`: the API migrates on startup). `cluster` overrides where the + EEG analysis runs, for this run only.""" from webapi.orchestration import Context, run, steps_of from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis from webapi.orchestration.estimators import live_estimators @@ -146,10 +145,11 @@ class RecomputationQueue: self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: - ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio), - eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio), - ados2_scoring=live_ados2_scoring(dominio)) - pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) + with _cluster_override(cluster): + ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio), + eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio), + ados2_scoring=live_ados2_scoring(dominio)) + pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok", pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos], @@ -171,8 +171,9 @@ class RecomputationQueue: """Runs every pending domain once; returns the ones it ran.""" ran = [] for dominio in self.pending(): + choice = self.requested_cluster(dominio) if self.take(dominio): - self.run(dominio) + self.run(dominio, cluster=choice) ran.append(dominio) return ran diff --git a/webapi/tea/__init__.py b/webapi/tea/__init__.py new file mode 100644 index 0000000..81e2cf2 --- /dev/null +++ b/webapi/tea/__init__.py @@ -0,0 +1 @@ +"""TEA governance storage services.""" diff --git a/webapi/tea/analyze_jobs.py b/webapi/tea/analyze_jobs.py new file mode 100644 index 0000000..626c3c0 --- /dev/null +++ b/webapi/tea/analyze_jobs.py @@ -0,0 +1,100 @@ +"""Detached analysis jobs for stored TEA EEGs.""" + +import fcntl +import json +import os +import sys +from pathlib import Path + +from webapi import detached_jobs + +SUMMARY_FIELDS = {"pending", "valid", "not_valid", "failed"} + + +class AnalysisRunning(RuntimeError): + """An EEG analysis job is already running.""" + + +class AnalyzeJobs: + """Launch and read EEG analysis jobs from the indicator directory.""" + + def __init__(self): + self.base = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "analisis_eeg" + + def start(self, body: dict) -> dict: + """Validate analysis options and launch one job at a time.""" + if not isinstance(body, dict) or body.keys() - {"all", "limit", "ids", "cluster"}: + raise ValueError("El cuerpo debe ser un objeto JSON con opciones de análisis válidas.") + + everything = body.get("all", False) + limit = body.get("limit") + ids = body.get("ids") + if type(everything) is not bool: + raise ValueError("all debe ser un valor booleano.") + if "limit" in body and (type(limit) is not int or limit < 1): + raise ValueError("limit debe ser un entero positivo.") + if "ids" in body: + if (not isinstance(ids, list) or not ids + or any(type(value) not in (int, str) or not str(value).strip() or len(str(value)) > 64 + or any(mark in str(value) for mark in ",\0") for value in ids)): + raise ValueError("ids debe ser una lista no vacía de identificadores de EEG.") + ids = [str(value).strip() for value in ids] + if sum((everything, limit is not None, ids is not None)) > 1: + raise ValueError("Elija solo una opción entre all, limit e ids.") + + env = os.environ.copy() + cluster = detached_jobs.cluster_environment(body, env) + argv = [sys.executable, "-m", "models", "tea", "analyze"] + if everything: + argv.append("--all") + elif limit is not None: + argv.extend(("--limit", str(limit))) + elif ids is not None: + argv.extend(("--ids", ",".join(map(str, ids)))) + argv.extend(("--cluster", cluster["mode"] if cluster else "auto")) + + self.base.mkdir(parents=True, exist_ok=True) + with (self.base / ".start.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if any(self._state(folder)["estado"] == "en_curso" for folder in detached_jobs.folders(self.base)): + raise AnalysisRunning("Ya hay un análisis de EEG en curso.") + if ids is not None: + from models.eeg_analysis import selected_ids + from persistance.tea import eeg_repository + + with eeg_repository.open_session() as session: + selected_ids(session, ids) + folder = detached_jobs.launch(self.base, argv, env, {"cluster": cluster, "ids": ids}, + precise_id=True, cwd=Path.cwd()) + return self._state(folder) + + def get(self, job_id: str) -> dict: + """Read one analysis job by ID.""" + folder = self.base / job_id + if "/" in job_id or not (folder / "job.json").is_file(): + raise LookupError(f"No se encontró el análisis de EEG {job_id}.") + return self._state(folder) + + def jobs(self) -> list[dict]: + """List analysis jobs newest first.""" + return [self._state(folder) for folder in detached_jobs.folders(self.base)] + + @staticmethod + def _state(folder: Path) -> dict: + job = detached_jobs.state(folder) + job.pop("pid", None) + job.setdefault("cluster", None) + job.setdefault("ids", None) + job["summary"] = None + if job["codigo"] is not None: + for line in reversed(job["salida"].splitlines()): + if line.startswith("summary:"): + try: + summary = json.loads(line.removeprefix("summary:")) + except ValueError: + break + if (isinstance(summary, dict) and summary.keys() == SUMMARY_FIELDS + and all(type(value) is int and value >= 0 for value in summary.values())): + job["summary"] = summary + break + return job diff --git a/webapi/tea/baselines.py b/webapi/tea/baselines.py new file mode 100644 index 0000000..3b2da4a --- /dev/null +++ b/webapi/tea/baselines.py @@ -0,0 +1,44 @@ +"""Transfer trained EEG baselines between registries.""" + +import hashlib +import shutil +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import BinaryIO +from zipfile import BadZipFile + +from models.tea.eeg import bundle +from models.tea.eeg.bundle import BundleError +from models.tea.eeg.settings import settings + + +class BaselineConflict(BundleError): + """Every baseline in the bundle already exists in the registry.""" + + +class BaselineBundles: + """Export and register bundles using the configured EEG scenarios.""" + + def export(self, path: Path, *, environment: str, production: bool) -> bundle.Exported: + return bundle.export(settings(), path, environment=environment.upper(), production=production) + + def import_(self, stream: BinaryIO) -> dict: + config = settings() + with NamedTemporaryFile(suffix=".zip") as upload: + shutil.copyfileobj(stream, upload, length=1024 * 1024) + upload.flush() + upload.seek(0) + sha256 = hashlib.file_digest(upload, "sha256").hexdigest() + try: + versions = bundle.import_(config, upload.name) + except (BadZipFile, KeyError, TypeError, AttributeError, FileNotFoundError) as error: + raise BundleError(f"Paquete de baselines inválido: {error}") from error + + imported = [ + {"scenario": scenario, "version": int(version)} + for scenario, (version, new) in versions.items() if new + ] + if versions and not imported: + existing = ", ".join(f"{scenario}: {version}" for scenario, (version, _) in versions.items()) + raise BaselineConflict(f"Las versiones ya están registradas: {existing}") + return {"sha256": sha256, "imported": imported} diff --git a/webapi/tea/edf_intake.py b/webapi/tea/edf_intake.py new file mode 100644 index 0000000..a4758e5 --- /dev/null +++ b/webapi/tea/edf_intake.py @@ -0,0 +1,70 @@ +"""Add an EEG recording to TEA through the import pipeline. + +The recording goes through the `edf` connector and the `tea.Eeg` target, the same path an import takes, so the +validation, the natural key (`eeg_id_registro_laboratorio`) and the audit trail are the import's own. +""" + +import base64 + +from sqlalchemy import select + +from persistance.tea import eeg_repository +from webapi.imports import audit as import_audit +from webapi.imports.services.import_service import ImportRequestError, ImportSource, commit_sources + +TARGET = "tea.Eeg" +COLUMNS = { + "id_registro_laboratorio": "eeg_id_registro_laboratorio", + "fecha_estudio": "eeg_fecha_estudio", + "canales": "eeg_canales", + "duracion_min": "eeg_duracion_min", + "estudio": "eeg_estudio", +} + + +class EdfIntake: + """Registers one EDF file as an EEG, optionally linked to a patient.""" + + def add(self, filename: str, raw: bytes, patient_id: int | None = None) -> dict: + """`ImportRequestError` for a file that is not a readable EDF or that the import rejects.""" + source = { + "source_type": "edf", + "target": TARGET, + "payload": {"file_base64": base64.b64encode(raw).decode("ascii"), "options": {"file_name": filename}}, + "column_mapping": COLUMNS, + "defaults": {} if patient_id is None else {"eeg_pac_id": patient_id}, + "label": filename, + } + lab_id = self._lab_id(source) + audit = import_audit.ImportAudit("carga", {"on_conflict": "upsert", "merge_duplicates": False}) + try: + (result,) = commit_sources([source], on_conflict="upsert", audit=audit) + except Exception as exc: + audit.fail(exc, "solicitud_invalida" if isinstance(exc, ImportRequestError) else "fallida") + raise + else: + audit.succeed() + finally: + import_audit.record(audit) + if result.rejected: + raise ImportRequestError("; ".join(error["message"] for error in result.errors) or "el EEG fue rechazado") + return {"eeg_id": self._eeg_id(lab_id), "lab_id": lab_id, "created": bool(result.created)} + + @staticmethod + def _lab_id(source: dict) -> str | None: + (row,) = ImportSource.parse(source).rows() + return row.get("eeg_id_registro_laboratorio") + + @staticmethod + def _eeg_id(lab_id: str | None): + if lab_id is None: + return None + model = eeg_repository.model + session = eeg_repository.open_session() + try: + found = session.execute( + select(model.eeg_id).where(model.eeg_id_registro_laboratorio == lab_id) + ).scalars().first() + finally: + session.close() + return found diff --git a/webapi/tea/eeg_queries.py b/webapi/tea/eeg_queries.py new file mode 100644 index 0000000..350aaab --- /dev/null +++ b/webapi/tea/eeg_queries.py @@ -0,0 +1,112 @@ +"""Read EEG analysis results and registered baseline curves for governance.""" + +from core.tea.models import Eeg, EegMetrica +from sqlalchemy import case, func, inspect, or_, select + +from webapi.fhir.eeg_curves import baseline_curves +from webapi.fhir.tea import EEGS, METRICS + + +class BaselineQueries: + """Use the analysis metric catalog to find drawable curves.""" + + def __init__(self, scenario: str, version: int): + self.scenario = scenario + self.version = version + self.label = f"tea-{scenario}/{version}" + self.curves = baseline_curves() + + def metrics(self) -> list[str]: + from models.tea.eeg.settings import settings + + candidates = {metric.code.lower() for metric in settings().metrics if metric.scenario == self.scenario} + return [name for name in sorted(candidates) if self.curves.curve(self.label, name) is not None] + + def curve(self, metric: str) -> dict: + curve = self.curves.curve(self.label, metric) + if curve is None: + raise LookupError("No se encontró una curva para la métrica y la versión solicitadas.") + return {"scenario": self.scenario, "version": self.version, "metric": metric, **curve} + + +def _public_id(key: str) -> int | str: + if key.isascii() and key.isdecimal() and str(int(key)) == key: + return int(key) + return key + + +def _valid(value: int | None) -> bool | None: + return None if value is None else value == 1 + + +def _count_where(condition): + return func.count(case((condition, 1))) + + +class EegQueries: + """Read projected EEG fields and aggregate counts from the TEA database.""" + + def __init__(self): + from persistance.tea import eeg_repository + + self.repository = eeg_repository + + def recordings(self, limit: int, offset: int) -> list[dict]: + query = select( + Eeg.eeg_id, Eeg.eeg_id_registro_laboratorio, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, + Eeg.eeg_valido, case((Eeg.eeg_error.is_not(None), 1), else_=0), + ).order_by(func.length(Eeg.eeg_id).desc(), Eeg.eeg_id.desc()).limit(min(limit, 500)).offset(offset) + with self.repository.open_session() as session: + return [ + {"id": _public_id(key), "lab_id": lab_id, "patient_id": patient_id, + "study_date": study_date.isoformat() if study_date is not None else None, + "valid": _valid(valid), "analysed": valid is not None or bool(failed)} + for key, lab_id, patient_id, study_date, valid, failed in session.execute(query) + ] + + def metrics(self, eeg_id: str) -> dict: + header = select(Eeg.eeg_valido, Eeg.eeg_nivel, Eeg.eeg_edad_meses).where(Eeg.eeg_id == eeg_id) + metrics = select( + EegMetrica.met_codigo, EegMetrica.met_valor, EegMetrica.met_z, EegMetrica.met_fuera, EegMetrica.met_modelo, + ).where( + EegMetrica.met_eeg_id == eeg_id, EegMetrica.met_codigo.is_not(None), EegMetrica.met_valor.is_not(None), + ).order_by(EegMetrica.met_codigo, EegMetrica.met_id) + with self.repository.open_session() as session: + row = session.execute(header).one_or_none() + if row is None: + raise LookupError(f"No se encontró el EEG {eeg_id}.") + valid, level, age_months = row + return { + "eeg_id": _public_id(eeg_id), "valid": _valid(valid), "level": level, "age_months": age_months, + "metrics": [ + {"name": code.lower(), "value": value, "z": z, "outside": outside, "model": model} + for code, value, z, outside, model in session.execute(metrics) + ], + } + + def summary(self) -> dict: + failed = Eeg.eeg_error.is_not(None) + eeg_counts = select( + func.count().label("eegs"), + _count_where(or_(Eeg.eeg_valido.is_not(None), failed)).label("analysed"), + _count_where(Eeg.eeg_valido == 1).label("valid"), + _count_where(Eeg.eeg_valido == 0).label("not_valid"), + _count_where(failed).label("failed"), + ).select_from(Eeg) + metric_counts = select( + func.count().label("metrics"), + _count_where(EegMetrica.met_z.is_not(None)).label("metrics_with_z"), + _count_where(EegMetrica.met_fuera == 1).label("high"), + _count_where(EegMetrica.met_fuera == -1).label("low"), + ).select_from(EegMetrica) + with self.repository.open_session() as session: + relations = inspect(session.connection()) + return { + **session.execute(eeg_counts).mappings().one(), + **session.execute(metric_counts).mappings().one(), + **{ + name: session.scalar(select(func.count()).select_from(view)) + if relations.has_table(view.name) else 0 + for name, view in (("fhir_eegs", EEGS), ("fhir_metrics", METRICS)) + }, + } diff --git a/webapi/tea/reference_cohorts.py b/webapi/tea/reference_cohorts.py new file mode 100644 index 0000000..ba0c692 --- /dev/null +++ b/webapi/tea/reference_cohorts.py @@ -0,0 +1,74 @@ +"""Store reference cohorts on the local filesystem.""" + +import re +import shutil +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import BinaryIO + +COHORT_NAME = re.compile(r"[A-Za-z0-9._-]{1,64}") +AGES_FILE = "edades.csv" + + +def _safe_component(value: str) -> bool: + return bool(value) and value != "." and not any(char in value for char in ("/", "\\", "..", "\0", ":")) + + +class ReferenceCohortStore: + """List cohorts and atomically publish uploads under a configured root.""" + + def __init__(self, root: str | Path): + self.root = Path(root).resolve() + + def list_cohorts(self) -> list[dict]: + if not self.root.exists(): + return [] + + cohorts = [] + for folder in sorted(self.root.iterdir()): + if (not COHORT_NAME.fullmatch(folder.name) or not _safe_component(folder.name) + or folder.is_symlink() or not folder.is_dir()): + continue + edfs = [ + path for path in folder.rglob("*") + if path.suffix.lower() == ".edf" and not path.is_symlink() and path.is_file() + ] + ages = folder / AGES_FILE + has_ages = not ages.is_symlink() and ages.is_file() + size = sum(path.stat().st_size for path in edfs) + if has_ages: + size += ages.stat().st_size + cohorts.append({ + "name": folder.name, + "edfs": len(edfs), + "size_bytes": size, + "has_ages": has_ages, + "path": str(folder), + }) + return cohorts + + def save_file(self, name: str, filename: str, stream: BinaryIO) -> dict: + if not COHORT_NAME.fullmatch(name) or not _safe_component(name): + raise ValueError("Nombre de cohorte inválido.") + if not _safe_component(filename): + raise ValueError("Nombre de archivo inválido.") + if filename != AGES_FILE and Path(filename).suffix.lower() != ".edf": + raise ValueError("Solo se admite un archivo EDF o edades.csv.") + + folder = self.root / name + target = folder / filename + if folder.is_symlink() or target.is_symlink(): + raise ValueError("Ruta de archivo inválida.") + folder.mkdir(parents=True, exist_ok=True) + + temporary = None + try: + with NamedTemporaryFile(dir=folder, suffix=".tmp", delete=False) as output: + temporary = Path(output.name) + shutil.copyfileobj(stream, output, length=1024 * 1024) + size = output.tell() + temporary.replace(target) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return {"name": name, "file": filename, "size_bytes": size} diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py index 0a65af4..7bdf403 100644 --- a/webapi/training_jobs.py +++ b/webapi/training_jobs.py @@ -7,17 +7,23 @@ worker of the server answers for any job and a restart does not lose them. A job code is `interrumpido`. """ -import json import os -import subprocess +import re +import subprocess as subprocess import sys import tomllib -import uuid -from datetime import datetime, timezone from pathlib import Path -TAIL_CHARS = 4000 -# A domain whose scenarios train on a reference cohort and not on a dbt cohort build. +from webapi import detached_jobs +from webapi.detached_jobs import cluster_environment as _training_cluster +REFERENCE_ENV = { + "reference_name": "TEA_REFERENCE_NAME", + "reference_dir": "TEA_REFERENCE_DIR", + "reference_ages": "TEA_REFERENCE_AGES", + "line_hz": "TEA_REFERENCE_LINE_HZ", +} +# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its +# `model.toml` does too, whatever its domain. OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."} @@ -50,68 +56,111 @@ def _base() -> Path: return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos" -def _command(domain: str, scenario: str) -> list[str]: - argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] +def _tea_parameters(body: dict, env: dict[str, str]) -> dict: + parameters = {key: body.get(key, env.get(variable) or None) for key, variable in REFERENCE_ENV.items()} + if not parameters["reference_dir"]: + for key in ("reference_ages", "line_hz"): + if key not in body: + parameters[key] = None + + for key in ("reference_name", "reference_dir", "reference_ages"): + if key in body and (not isinstance(body[key], str) or not body[key] or "\0" in body[key]): + raise ValueError(f"{key} debe ser texto no vacío.") + name = parameters["reference_name"] + if name is not None and not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name): + raise ValueError("reference_name debe tener de 1 a 64 caracteres de A-Z, a-z, 0-9, punto, guion o guion bajo.") + if "reference_dir" in body and not Path(body["reference_dir"]).is_absolute(): + raise ValueError("reference_dir debe ser una ruta absoluta.") + if "line_hz" in body and (type(body["line_hz"]) not in (int, float) or body["line_hz"] not in (50, 60)): + raise ValueError("line_hz debe ser 50 o 60.") + promote = body.get("promote", True) + if not isinstance(promote, bool): + raise ValueError("promote debe ser un valor booleano.") + return {**parameters, "promote": promote} + + +def _resolve_cohort(parameters: dict, body: dict, root: str) -> None: + """Point a named cohort at its folder (and ages table) under `root`, when the request gave no directory.""" + name = parameters["reference_name"] + if "reference_dir" in body or not name or not root: + return + folder = Path(root) / name + if not folder.is_dir(): + return + parameters["reference_dir"] = str(folder) + ages = folder / "edades.csv" + if "reference_ages" not in body and ages.is_file(): + parameters["reference_ages"] = str(ages) + + +def _check_reference_paths(parameters: dict, root: str) -> None: + for key in ("reference_dir", "reference_ages"): + value = parameters[key] + if value is None: + continue + try: + path = Path(value).resolve() + inside_root = path.is_relative_to(Path(root).resolve()) + except (OSError, RuntimeError, ValueError): + raise ValueError(f"No se pudo resolver la ruta de {key}.") from None + if not inside_root: + raise ValueError(f"{key} debe estar dentro de TEA_REFERENCE_ROOT.") + parameters[key] = str(path) + + +def _command(domain: str, scenario: str, parameters: dict | None = None) -> list[str]: + argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train"] + if domain == "tea" and parameters is None: + parameters = _tea_parameters({}, os.environ) + if parameters is None or parameters["promote"]: + argv.append("--promote") external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) if not external: argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] - elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"): - # A reference cohort on this machine's disk, instead of the configured one in the cluster's storage. - argv += ["--reference-dir", os.environ["TEA_REFERENCE_DIR"]] - if os.environ.get("TEA_REFERENCE_AGES"): - argv += ["--reference-ages", os.environ["TEA_REFERENCE_AGES"]] - if os.environ.get("TEA_REFERENCE_LINE_HZ"): - argv += ["--line-hz", os.environ["TEA_REFERENCE_LINE_HZ"]] + elif parameters is not None: + for key in ("reference_dir", "reference_ages", "line_hz", "reference_name"): + if parameters[key] is not None: + argv += [f"--{key.replace('_', '-')}", str(parameters[key])] return argv -def _alive(pid: int) -> bool: - try: - os.kill(pid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True - return True - - -def _tail(path: Path) -> str: - return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else "" - - def _state(folder: Path) -> dict: - job = json.loads((folder / "job.json").read_text(encoding="utf-8")) - out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log") - exit_file = folder / "exit" - if exit_file.exists(): - code = int(exit_file.read_text().strip() or 1) - state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido") - elif _alive(job["pid"]): - code, state = None, "en_curso" - else: - code, state = None, "interrumpido" - return {**job, "estado": state, "codigo": code, "salida": out, "error": err} + job = detached_jobs.state(folder) + if job["estado"] == "fallido" and "not promoted, missing" in job["error"]: + job["estado"] = "entrenado_sin_promover" + job.pop("parameters", None) + job.setdefault("cluster", None) + return job def running(domain: str, scenario: str) -> dict | None: return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None) -def start(domain: str, scenario: str) -> dict: +def start(domain: str, scenario: str, body: dict | None = None) -> dict: """Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest.""" if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}: raise LookupError(f"no such model: {domain}/{scenario}") if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"): raise RuntimeError("No hay un manifest de dbt configurado.") - job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}" - folder = _base() / job_id - folder.mkdir(parents=True) - shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }' - process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True, - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid, - "iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")} - (folder / "job.json").write_text(json.dumps(job), encoding="utf-8") + env = os.environ.copy() + cluster = None + if domain == "tea": + body = {} if body is None else body + cluster = _training_cluster(body, env) + parameters = _tea_parameters(body, env) + if env.get("TEA_REFERENCE_ROOT") and (cluster is None or cluster["mode"] != "remote"): + _resolve_cohort(parameters, body, env["TEA_REFERENCE_ROOT"]) + _check_reference_paths(parameters, env["TEA_REFERENCE_ROOT"]) + argv = _command(domain, scenario, parameters) + if parameters["line_hz"] is None and parameters["reference_dir"]: + parameters["line_hz"] = 60 + else: + parameters = None + argv = _command(domain, scenario) + folder = detached_jobs.launch(_base(), argv, env, { + "domain": domain, "scenario": scenario, "cluster": cluster, "parameters": parameters, + }) return _state(folder) @@ -124,5 +173,4 @@ def get(job_id: str) -> dict: def jobs(limit: int = 50) -> list[dict]: """The latest jobs, newest first.""" - folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else [] - return [_state(p) for p in folders[:limit]] + return [_state(folder) for folder in detached_jobs.folders(_base())[:limit]]