"""Endpoint tests for `/governance/*`: model versions and their promotion, downloading what a version's run stored, notebooks run on a cohort build, and the OCR review queue. Fixtures: `client`, the app over a CaCu and a governance database with one patient and a SQLite-backed MLflow in a temporary folder (module scope); `notebooks`, a cohort build's file under a `COHORTS_DIR`, the Jupyter renderer and notebooks run in the request instead of in the background. `_trained` registers a version the way training does: a run that records each routine and saves its model. """ import io import json import os import tempfile from datetime import date import mlflow.pyfunc import pytest @pytest.fixture(scope="module") def client(wire_domain): wire_domain("cacu") wire_domain("governance") # A local, SQLite-backed MLflow tracking store for this module — no # server, no network. `chdir` into the same temp dir: an experiment with # no explicit artifact_location falls back to `./mlruns` relative to the # CWD (production never sets one either; the real MLflow server picks it). import mlflow tmp_dir = tempfile.mkdtemp() uri = f"sqlite:///{os.path.join(tmp_dir, 'mlflow.db')}" os.environ["MLFLOW_TRACKING_URI"] = uri mlflow.set_tracking_uri(uri) previous_cwd = os.getcwd() os.chdir(tmp_dir) from core.cacu.models import Paciente from persistance import db as persistance_db with __import__("sqlmodel").Session(persistance_db.get_cacu_engine()) as session: session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1))) session.commit() from webapi import create_app app = create_app() app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client os.chdir(previous_cwd) del os.environ["MLFLOW_TRACKING_URI"] def test_list_model_versions_empty(client): response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"}) assert response.status_code == 200 assert response.get_json() == {"model_versions": []} def _armado(tag: str) -> int: """A CaCu cohort build with one attrition step; returns its `armado_id`.""" from datetime import datetime, timezone from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion from persistance.db import get_cacu_session with get_cacu_session() as session: armado = CohorteArmado( url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}", datos_as_of=date(2025, 12, 31), huella=f"huella-{tag}", marco_sha="m", n_miembros=5, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)) session.add(armado) session.flush() session.add(CohorteExclusion(armado_id=armado.armado_id, orden=1, paso="candidatas", n=5)) session.commit() return armado.armado_id def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict: body = { "domain": "cacu", "scenario": scenario, "environment": "PROD", "cohorte_armado_id": _armado(tag), "metrics": {"auc": 0.8}, "technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf", "interpretability_report_uri": "docs/interpretabilidad.html", **extra, } response = client.post("/governance/model-versions", json=body) assert response.status_code == 201, response.get_json() return response.get_json() class Echo(mlflow.pyfunc.PythonModel): def predict(self, context, model_input, params=None): return model_input def _trained(tag: str, scenario: str, **reports) -> str: """A PROD version as training leaves it: every routine recorded and the model saved.""" from models.io.registry import registry from models.io.tracking import ROUTINE_KINDS, TrainingRun run = TrainingRun(domain="cacu", scenario=scenario, environment="PROD", cohorte_armado_id=_armado(tag)) for kind in ROUTINE_KINDS: run.log_routine(kind, {"method": "prueba"}) run.log_model(Echo()) return registry.register_run(run.finish(metrics={"auc": 0.8}), **reports) REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf", "interpretability_report_uri": "docs/interpretabilidad.html"} def test_model_version_lifecycle_over_http(client): """A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can, and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared over the API, or promotion stops retiring the previous version.""" declared = _register(client, "v0", scenario="lifecycle") checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json() assert checks["ready"] is False assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"] blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote") assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"]) first = _trained("v1", "lifecycle", **REPORTS) assert client.post(f"/governance/model-versions/cacu/lifecycle/{first}/promote").get_json()["status"] == "produccion" second = _trained("v2", "lifecycle", **REPORTS) client.post(f"/governance/model-versions/cacu/lifecycle/{second}/promote") listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json() statuses = {v["version"]: v["status"] for v in listed["model_versions"]} assert statuses[first] == "retirada" and statuses[second] == "produccion" lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second}/lineage").get_json() assert lineage["cohorte_armado"]["huella"] == "huella-v2" assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31" assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}] assert lineage["routines"]["MUESTREO"] == {"method": "prueba"} retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second}/retire").get_json() assert retired["status"] == "retirada" def test_a_versions_files_download(client): """ML-01b: a routine record downloads as itself, the model folder as a zip, and a path the run doesn't hold is 404. Fails if the endpoint stops going through `registry.artifact`.""" version = _trained("v-desc", "descargas") base = f"/governance/model-versions/cacu/descargas/{version}/artifacts" record = client.get(f"{base}/rutinas/MUESTREO.json") assert record.status_code == 200 and record.get_json(force=True) == {"method": "prueba"} assert "attachment" in record.headers["Content-Disposition"] model = client.get(f"{base}/model") assert model.status_code == 200 and 'model.zip' in model.headers["Content-Disposition"] assert client.get(f"{base}/../../mlflow.db").status_code == 404 assert client.get(f"{base}/rutinas/OTRO.json").status_code == 404 def test_reports_can_be_attached_later(client): version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None) response = client.patch( f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"clinical_validation_report_uri": "docs/clinica-v3.pdf"}, ) assert response.get_json()["tags"]["clinical_validation_report_uri"] == "docs/clinica-v3.pdf" assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400 def test_bad_registrations_are_rejected(client): assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400 def test_model_version_not_found(client): assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404 def test_training_needs_a_dbt_manifest(client, monkeypatch): """Pins down: with no `DBT_MANIFEST`, `/train` refuses before running anything. Fails if it tries to train with no manifest configured instead of failing fast.""" monkeypatch.delenv("DBT_MANIFEST", raising=False) response = client.post("/governance/model-versions/cacu/cin2_logistic/train") assert response.status_code == 503 def test_training_runs_the_same_pipeline_entrenar_does(client, monkeypatch): """Pins down: `/train` calls `models.__main__.main` with exactly the arguments the `entrenar` compose profile runs (export from dbt, PROD, train, promote), reading the manifest path from `DBT_MANIFEST`, and returns its captured output on success. Fails if the route drifts from that one-shot invocation, or stops using the deployment's own manifest.""" monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json") calls = [] def fake_main(argv): calls.append(argv) print("trained: version 1, from dbt/1.parquet") print("in production: version 1") return 0 monkeypatch.setattr("models.__main__.main", fake_main) response = client.post("/governance/model-versions/cacu/cin2_logistic/train") assert response.status_code == 200 assert calls == [["run", "cacu", "cin2_logistic", "--export", "--source", "dbt", "--manifest", "/data/dbt/manifest.json", "--environment", "prod", "--train", "--promote"]] assert "in production: version 1" in response.get_json()["output"] @pytest.mark.parametrize("stderr, expected_status", [ ("no such model: cacu/ninguno\n", 404), ("not promoted, missing: MLD-01 (reporte de pruebas técnicas)\n", 409), ("a query of cacu/cohorte_vigilancia failed (no such table: cohorte_armado)\n", 503), ]) def test_training_failures_map_to_their_status(client, monkeypatch, stderr, expected_status): """Pins down: an unknown model is 404, a trained-but-unpromotable version is 409 (attach reports, then `/promote`), and anything else operational is 503. Fails if a failure that needs a human step (missing reports) reads the same as a hard, transient failure, or either is swallowed as success.""" import sys def fake_main(argv): sys.stderr.write(stderr) return 1 monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json") monkeypatch.setattr("models.__main__.main", fake_main) response = client.post("/governance/model-versions/cacu/cin2_logistic/train") assert response.status_code == expected_status assert response.get_json()["error"] == stderr.strip() def test_ocr_run_unknown_job_is_404(client): response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"}) assert response.status_code == 404 def test_ocr_run_extracts_results_and_flags_unreadable_reports(client): from core.cacu.models import CitologiaCervical from extraction.testing import text_pdf from persistance.cacu import citologia_cervical_repository from persistance.governance import extraction_run_repository report = text_pdf([["LABORATORIO DE BIOLOGIA MOLECULAR", "Expediente: H-OCR-1", "VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"]]) good = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-1", cit_vph_pdf_blob=report)) bad = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-2", cit_vph_pdf_blob=b"%PDF-fake")) body = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json() assert body["processed"] >= 1 and body["failed"] >= 1 good = citologia_cervical_repository.get(good.cit_id) assert (good.cit_vph_resultado, good.cit_vph_genotipo_16, good.cit_vph_genotipo_18) == ("POSITIVO", 0, 1) assert good.cit_vph_ocr_estatus == "REALIZADO" and good.cit_vph_ocr_requiere_revision is False assert good.cit_vph_ocr_metodo_principal == "pdf-texto" and good.cit_vph_ocr_confianza >= 0.8 bad = citologia_cervical_repository.get(bad.cit_id) assert bad.cit_vph_ocr_estatus == "FALLIDO" and bad.cit_vph_ocr_requiere_revision is True assert extraction_run_repository.count(entity_pk=str(good.cit_id)) == 1 again = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json() assert again["skipped_already_done"] >= 1 def test_eeg_run_analyses_at_most_the_limit_with_the_configured_cluster(client, monkeypatch): """Pins down: `POST /governance/eeg/run` runs the EEG analysis in the request with the body's `limit` (5 by default), `all` and the cluster `EEG_ANALYSIS_CLUSTER` names, and answers its summary. Fails if the route stops bounding the batch (a request could then run for hours) or ignores the body. """ import models.eeg_analysis from models.eeg_analysis import Summary calls = [] monkeypatch.setattr(models.eeg_analysis, "analyze_pending", lambda **kwargs: calls.append(kwargs) or Summary(pending=2, valid=1, not_valid=1, failed=0)) monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "sync") body = client.post("/governance/eeg/run", json={}).get_json() assert body == {"pending": 2, "valid": 1, "not_valid": 1, "failed": 0} client.post("/governance/eeg/run", json={"limit": 1, "all": True, "cluster": "local"}) assert calls == [{"everything": False, "limit": 5, "cluster": "sync"}, {"everything": True, "limit": 1, "cluster": "local"}] @pytest.mark.parametrize("body", [{"limit": 0}, {"limit": "many"}, {"cluster": "everywhere"}]) def test_eeg_run_refuses_a_bad_limit_or_cluster(client, body): """Pins down: a limit that isn't a positive whole number, or an unknown cluster, is a 400 before anything runs. Fails if the route starts an analysis on a body it can't honour. """ assert client.post("/governance/eeg/run", json=body).status_code == 400 def test_list_ocr_jobs(client): body = client.get("/governance/ocr/jobs").get_json() keys = {(j["domain"], j["entity"]) for j in body["jobs"]} assert ("cacu", "citologia_cervical") in keys assert ("cacu", "biopsia_cervical") in keys assert ("cama", "biopsia_mama") in keys cacu_vph = next(j for j in body["jobs"] if (j["domain"], j["entity"]) == ("cacu", "citologia_cervical")) assert set(cacu_vph["result_fields"]) == {"cit_vph_resultado", "cit_vph_genotipo_16", "cit_vph_genotipo_18"} def test_ocr_rows_unknown_job_is_404(client): assert client.get("/governance/ocr/cacu/no_such_entity/rows").status_code == 404 def test_ocr_review_queue_blob_and_manual_correction(client): from core.cacu.models import CitologiaCervical from persistance.cacu import citologia_cervical_repository row = citologia_cervical_repository.create( CitologiaCervical( pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-review-me", cit_vph_ocr_estatus="FALLIDO", cit_vph_ocr_requiere_revision=True, ) ) review = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"}) assert review.status_code == 200 review_body = review.get_json() assert row.cit_id in {r["id"] for r in review_body["rows"]} blob_response = client.get(f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/blob") assert blob_response.status_code == 200 assert blob_response.data == b"%PDF-review-me" assert blob_response.content_type == "application/pdf" correction = client.post( f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct", json={"values": {"cit_vph_resultado": "POSITIVO"}, "confianza": 1.0}, ) assert correction.status_code == 200 corrected = correction.get_json() assert corrected["cit_vph_resultado"] == "POSITIVO" assert corrected["cit_vph_ocr_estatus"] == "REALIZADO" assert corrected["cit_vph_ocr_requiere_revision"] is False assert corrected["cit_vph_ocr_metodo_principal"] == "manual" done = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"}) assert row.cit_id not in {r["id"] for r in done.get_json()["rows"]} from persistance.governance import extraction_run_repository runs = extraction_run_repository.list(entity="citologia_cervical") assert any("manual" in (r.transform_description or "").lower() for r in runs) def test_ocr_correct_rejects_unknown_column(client): from core.cacu.models import CitologiaCervical from persistance.cacu import citologia_cervical_repository row = citologia_cervical_repository.create( CitologiaCervical(pac_id_hospital="H-2", cit_vph_pdf_blob=b"%PDF-2") ) response = client.post( f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct", json={"values": {"pac_id_hospital": "HACKED"}}, ) assert response.status_code == 400 def test_ocr_blob_not_found_for_unknown_row(client): assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404 def _notebook(*sources: str) -> bytes: cells = [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": s} for s in sources] return json.dumps({"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5}).encode() @pytest.fixture def notebooks(tmp_path, monkeypatch): """Build 4 of dbt's `cacu/cohorte_vigilancia` under `COHORTS_DIR`, the Jupyter renderer, and `submit` running the notebook before the request answers.""" import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from datetime import datetime, timezone from models.io.contracts import COHORT_SCHEMA from webapi.blueprints import governance row = {"pac_id": 1, "fecha_indice": date(2025, 1, 1), "fecha": date(2025, 1, 1), "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia", "codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical", "fuente_id": "S1"} table = pa.Table.from_pandas(pd.DataFrame([row], columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False) path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "4.parquet" path.parent.mkdir(parents=True) metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "4", "datos_as_of": "2025-12-31", "n_members": "1"} pq.write_table(table.replace_schema_metadata(metadata), path) monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter") monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos")) monkeypatch.setattr(governance, "submit", lambda job, *args: job(*args)) def _run(client, notebook: bytes, *, scenario="exploracion", **fields): form = {"file": (io.BytesIO(notebook), "analisis.ipynb"), "domain": "cacu", "scenario": scenario, "url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "4", **fields} return client.post("/governance/experiments", data=form, content_type="multipart/form-data") def test_the_builds_a_notebook_can_run_on_are_listed(client, notebooks): """Fails if `/cohort-files` stops listing exported builds from their files.""" builds = client.get("/governance/cohort-files", query_string={"domain": "cacu"}).get_json()["builds"] assert builds == [{"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": 4, "datos_as_of": "2025-12-31", "n_members": "1"}] def test_an_uploaded_notebook_runs_on_the_build_and_its_page_is_sandboxed(client, notebooks): """The upload answers 202 with the run; the notebook reads the build through `models.notebook`; its page is served with a sandbox policy and its files download. Fails if the endpoint stops handing the build to the run or serves the notebook's page as part of the app's origin.""" started = _run(client, _notebook("from models.notebook import experiment\n" "print('miembros', experiment().cohort().pac_id.nunique())")) assert started.status_code == 202, started.get_json() run_id = started.get_json()["run_id"] run = client.get(f"/governance/experiments/{run_id}").get_json() assert run["status"] == "terminado" and run["cohort"]["build"] == "4" and run["notebook"] == "analisis" page = client.get(f"/governance/experiments/{run_id}/page") assert "miembros 1" in page.get_data(as_text=True) and "sandbox" in page.headers["Content-Security-Policy"] source = client.get(f"/governance/experiments/{run_id}/artifacts/notebook/analisis.ipynb") assert source.status_code == 200 and "attachment" in source.headers["Content-Disposition"] listed = client.get("/governance/experiments", query_string={"domain": "cacu", "scenario": "exploracion"}).get_json() assert run_id in [r["run_id"] for r in listed["experiments"]] def test_a_failing_notebook_reports_its_error(client, notebooks): """Fails if a notebook whose cell raises is reported as finished or without its error.""" run_id = _run(client, _notebook("raise ValueError('sin datos')")).get_json()["run_id"] run = client.get(f"/governance/experiments/{run_id}").get_json() assert run["status"] == "fallido" and "sin datos" in run["error"] @pytest.mark.parametrize("fields, notebook", [ ({"build": "99"}, None), ({"url": "tea/otra"}, None), ({"build": "x"}, None), ({"version": "999"}, None), ({}, b"no es json"), ({}, b'{"cells": [], "nbformat": 3}'), ]) def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook): """A build that isn't exported, a cohort of another domain, an unknown version, or a file that isn't a notebook is refused before anything runs. Fails if `/experiments` stops checking any of them.""" response = _run(client, notebook or _notebook("1"), **fields) assert response.status_code in (400, 404)