drop cohort builder plumbing; use kit cohorte_armado builds for MLflow lineage
This commit is contained in:
+25
-17
@@ -11,6 +11,8 @@ def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str)
|
||||
engine = getattr(persistance_db, f"get_{domain}_engine")
|
||||
engine.cache_clear()
|
||||
importlib.import_module(f"core.{domain}.models")
|
||||
if domain != "governance":
|
||||
importlib.import_module(f"core.{domain}.indicadores.models")
|
||||
base = getattr(importlib.import_module(base_module), base_class)
|
||||
base.metadata.create_all(engine())
|
||||
return engine
|
||||
@@ -32,13 +34,7 @@ def cacu_db(tmp_path, monkeypatch):
|
||||
|
||||
@pytest.fixture
|
||||
def mlflow_tracking(tmp_path, monkeypatch):
|
||||
"""A local, SQLite-backed MLflow tracking URI — no server, no network,
|
||||
isolated per test (MLflow's own default local backend; the older plain
|
||||
file store is deprecated as of MLflow 3). Also `chdir`s into `tmp_path`:
|
||||
an experiment with no explicit `artifact_location` falls back to
|
||||
`./mlruns` relative to the CWD, and production never sets one either
|
||||
(the real MLflow server picks it, e.g. S3) — so this is purely test
|
||||
isolation, not something `models.training` should set itself."""
|
||||
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
|
||||
import mlflow
|
||||
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
@@ -49,24 +45,16 @@ def mlflow_tracking(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def production_ready(governance_db, mlflow_tracking):
|
||||
def production_ready(governance_db, cacu_db, mlflow_tracking):
|
||||
"""Factory: registers a PROD version that passes every promotion check,
|
||||
returns (domain, scenario, version)."""
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from core.governance.models import CohortVersion
|
||||
from models.registry import registry
|
||||
from persistance.governance import cohort_version_repository
|
||||
|
||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
||||
cohort = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain=domain, scenario=scenario, criteria_version="v1", version_hash=f"hash-{tag}",
|
||||
source_table=f"{domain}.episodioclinico", n_source=10, n_included=8,
|
||||
)
|
||||
)
|
||||
version = registry.register(
|
||||
domain=domain, scenario=scenario, environment=Environment.PROD,
|
||||
cohort_version_id=cohort.cohort_version_id, metrics=metrics or {"auc": 0.8},
|
||||
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
|
||||
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html",
|
||||
)
|
||||
@@ -83,3 +71,23 @@ def tiny_onnx() -> bytes:
|
||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
|
||||
|
||||
|
||||
def armado(huella: str) -> int:
|
||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
fila = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(fila)
|
||||
session.flush()
|
||||
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
|
||||
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
|
||||
session.commit()
|
||||
return fila.armado_id
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from models.cohort import CohortBuilder, ExclusionCriterion, compute_version_hash
|
||||
|
||||
|
||||
|
||||
def _seed_episodes():
|
||||
from core.cacu.episodio_clinico.enums import TipoEpisodio
|
||||
from core.cacu.models import EpisodioClinico
|
||||
from persistance.cacu import episodio_clinico_repository
|
||||
|
||||
for i, year in enumerate([2018, 2019, 2021, 2022, 2023]):
|
||||
episodio_clinico_repository.create(
|
||||
EpisodioClinico(
|
||||
pac_id_hospital=f"H-{i}",
|
||||
tipo_episodio=TipoEpisodio.TAMIZAJE,
|
||||
evento_fecha=date(year, 6, 1),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class FechaVentanaCohortBuilder(CohortBuilder):
|
||||
domain = "cacu"
|
||||
scenario = "tamizaje_test"
|
||||
criteria_version = "v1"
|
||||
criteria = [
|
||||
ExclusionCriterion(
|
||||
code="FECHA_FUERA_DE_VENTANA",
|
||||
reason_code="ANTES_2020",
|
||||
predicate=lambda e: e["evento_fecha"] < date(2020, 1, 1),
|
||||
applicable_in_production=True,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def test_build_excludes_and_materializes_counts(cacu_db, governance_db):
|
||||
_seed_episodes()
|
||||
builder = FechaVentanaCohortBuilder()
|
||||
|
||||
cohort_version = builder.build(description="ventana >= 2020")
|
||||
|
||||
assert cohort_version.n_source == 5
|
||||
assert cohort_version.n_included == 3
|
||||
assert cohort_version.version_hash
|
||||
|
||||
from persistance.governance import cohort_exclusion_count_repository, cohort_exclusion_repository, cohort_member_repository
|
||||
|
||||
members = cohort_member_repository.list(cohort_version_id=cohort_version.cohort_version_id)
|
||||
assert len(members) == 3
|
||||
|
||||
exclusions = cohort_exclusion_repository.list(cohort_version_id=cohort_version.cohort_version_id)
|
||||
assert len(exclusions) == 2
|
||||
assert {e.reason_code for e in exclusions} == {"ANTES_2020"}
|
||||
|
||||
counts = cohort_exclusion_count_repository.list(cohort_version_id=cohort_version.cohort_version_id)
|
||||
assert len(counts) == 1
|
||||
assert counts[0].count == 2
|
||||
assert counts[0].criterion_code == "FECHA_FUERA_DE_VENTANA"
|
||||
|
||||
|
||||
def test_version_hash_is_deterministic_and_order_independent():
|
||||
hash_a = compute_version_hash(criteria_version="v1", criterion_codes=["X", "Y"], episode_ids=[3, 1, 2])
|
||||
hash_b = compute_version_hash(criteria_version="v1", criterion_codes=["Y", "X"], episode_ids=[1, 2, 3])
|
||||
hash_c = compute_version_hash(criteria_version="v2", criterion_codes=["X", "Y"], episode_ids=[1, 2, 3])
|
||||
|
||||
assert hash_a == hash_b
|
||||
assert hash_a != hash_c
|
||||
assert len(hash_a) == 64
|
||||
|
||||
|
||||
def test_evaluate_applicability_uses_only_production_applicable_criteria():
|
||||
builder = FechaVentanaCohortBuilder()
|
||||
old_row = {"evento_fecha": date(2018, 1, 1)}
|
||||
recent_row = {"evento_fecha": date(2023, 1, 1)}
|
||||
|
||||
assert builder.evaluate_applicability(old_row) is False
|
||||
assert builder.evaluate_applicability(recent_row) is True
|
||||
+22
-4
@@ -1,10 +1,12 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from core.ocr import OcrEstatus
|
||||
from models.ocr import CIT_VPH_COLUMNS, OcrExtractionResult, OcrExtractor, run_pending_extractions
|
||||
|
||||
from models.ocr import (
|
||||
CIT_VPH_COLUMNS,
|
||||
OcrExtractionResult,
|
||||
OcrExtractor,
|
||||
run_pending_extractions,
|
||||
)
|
||||
|
||||
|
||||
class StubVphExtractor(OcrExtractor):
|
||||
@@ -95,3 +97,19 @@ def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db):
|
||||
assert len(runs) == 1
|
||||
assert runs[0].domain == "cacu"
|
||||
assert runs[0].source_description == "HIS export 2026-09-01"
|
||||
|
||||
|
||||
def test_done_rows_do_not_use_up_the_batch(cacu_db):
|
||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
||||
for n in range(3):
|
||||
repo.create(CitologiaCervical(pac_id_hospital=f"H-{n}", cit_vph_pdf_blob=b"%PDF-fake",
|
||||
cit_vph_ocr_estatus=OcrEstatus.REALIZADO.value))
|
||||
repo.create(CitologiaCervical(pac_id_hospital="H-nuevo", cit_vph_pdf_blob=b"%PDF-fake"))
|
||||
repo.create(CitologiaCervical(pac_id_hospital="H-sin-pdf"))
|
||||
|
||||
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu",
|
||||
entity="citologiacervical", limit=1)
|
||||
|
||||
assert (summary.processed, summary.skipped_already_done) == (1, 3)
|
||||
assert repo.list(pac_id_hospital="H-nuevo")[0].cit_vph_resultado == "POSITIVO"
|
||||
assert repo.list(pac_id_hospital="H-sin-pdf")[0].cit_vph_ocr_estatus is None
|
||||
|
||||
@@ -3,7 +3,6 @@ import json
|
||||
import pytest
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.cohort import CohortBuilder, ExclusionCriterion
|
||||
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
||||
from models.registry import registry
|
||||
|
||||
@@ -18,11 +17,8 @@ class StubModel(ScreeningModel):
|
||||
return {"label": "positivo", "confianza": 0.73}
|
||||
|
||||
|
||||
class AlwaysRejectCohortBuilder(CohortBuilder):
|
||||
domain = "cacu"
|
||||
scenario = "tamizaje"
|
||||
criteria_version = "v1"
|
||||
criteria = [ExclusionCriterion(code="X", reason_code="siempre", predicate=lambda e: True, applicable_in_production=True)]
|
||||
def never_applicable(row: dict) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _promote_a_version(production_ready):
|
||||
@@ -56,7 +52,7 @@ def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
|
||||
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
|
||||
_promote_a_version(production_ready)
|
||||
service = PredictionService(
|
||||
StubModel(), domain="cacu", scenario="tamizaje", cohort_builder=AlwaysRejectCohortBuilder()
|
||||
StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable
|
||||
)
|
||||
|
||||
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
||||
@@ -69,9 +65,16 @@ def test_applicability_gate_can_reject_outright(production_ready):
|
||||
StubModel(),
|
||||
domain="cacu",
|
||||
scenario="tamizaje",
|
||||
cohort_builder=AlwaysRejectCohortBuilder(),
|
||||
aplicable=never_applicable,
|
||||
reject_inapplicable=True,
|
||||
)
|
||||
|
||||
with pytest.raises(ApplicabilityRejected):
|
||||
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
||||
|
||||
|
||||
def test_applicability_gate_needs_a_dict(production_ready):
|
||||
_promote_a_version(production_ready)
|
||||
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable)
|
||||
with pytest.raises(TypeError):
|
||||
service.predict_and_record([40], pac_id_hospital="H-1")
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import pytest
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import PromotionBlocked, registry
|
||||
|
||||
@@ -42,15 +41,14 @@ def test_artifacts_are_logged_to_the_run(production_ready):
|
||||
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
|
||||
|
||||
|
||||
def test_retire_and_lineage_and_compare(production_ready):
|
||||
def test_retire_and_lineage(production_ready):
|
||||
domain, scenario, first = production_ready("v1", metrics={"auc": 0.8, "brier": 0.2})
|
||||
_, _, second = production_ready("v2", metrics={"auc": 0.85})
|
||||
registry.promote(domain, scenario, second)
|
||||
lineage = registry.lineage(domain, scenario, second)
|
||||
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"]
|
||||
assert lineage["model_version"]["status"] == "produccion"
|
||||
diff = {row["metric"]: row for row in registry.compare(domain, scenario, first, second)["metrics"]}
|
||||
assert diff["auc"]["delta"] == pytest.approx(0.05) and diff["brier"]["delta"] is None
|
||||
registry.retire(domain, scenario, second)
|
||||
assert registry.status(domain, scenario, second) == "retirada"
|
||||
with pytest.raises(ValueError):
|
||||
@@ -68,3 +66,9 @@ def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||
path = Path(tmp) / "x.onnx"
|
||||
path.write_bytes(b"weights")
|
||||
inspect_onnx_metadata(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
|
||||
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
|
||||
with pytest.raises(ValueError):
|
||||
registry.versions(domain, scenario)
|
||||
|
||||
+36
-4
@@ -2,17 +2,19 @@ import pytest
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
from models.training import ReadOnlyRepository, TrainingRun
|
||||
|
||||
|
||||
def test_prod_run_requires_cohort_version_id():
|
||||
with pytest.raises(ValueError, match="cohort_version_id"):
|
||||
def test_prod_run_requires_a_cohort_build():
|
||||
with pytest.raises(ValueError, match="cohorte_armado_id"):
|
||||
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD)
|
||||
|
||||
|
||||
def test_dev_run_does_not_require_cohort_version_id(mlflow_tracking):
|
||||
def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert run.cohort_version_id is None
|
||||
assert run.cohorte_armado_id is None
|
||||
|
||||
|
||||
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
|
||||
@@ -49,3 +51,33 @@ def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
|
||||
assert isinstance(repo, ReadOnlyRepository)
|
||||
with pytest.raises(PermissionError):
|
||||
repo.create(object())
|
||||
|
||||
|
||||
def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, tmp_path, monkeypatch):
|
||||
root = tmp_path / "artefactos"
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
|
||||
run = TrainingRun(domain="cama", scenario="riesgo", environment=Environment.DEV)
|
||||
experiment = run.client.get_experiment_by_name("cama-riesgo")
|
||||
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
||||
|
||||
|
||||
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert run.finish() == "1"
|
||||
|
||||
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert second.finish() == "2"
|
||||
|
||||
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
def unreachable(name):
|
||||
raise MlflowException("servidor no disponible")
|
||||
|
||||
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
|
||||
with pytest.raises(MlflowException, match="no disponible"):
|
||||
third.finish()
|
||||
|
||||
|
||||
def test_unknown_domain_is_rejected():
|
||||
with pytest.raises(ValueError, match="dominio desconocido"):
|
||||
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
Reference in New Issue
Block a user