Layout: per-domain folders, io, steps and pipelines, and one command line

This commit is contained in:
2026-11-04 12:48:41 -06:00
parent ec85cae5aa
commit 2d22409e1f
36 changed files with 164 additions and 200 deletions
+63
View File
@@ -0,0 +1,63 @@
"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it
returns, `Risk` and `Provenance`.
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
"""
from models.io.contract import Provenance, Risk, RiskEstimator
class ConstantEstimator:
"""Meets the contract with a fixed probability for every member and horizon."""
cohort_url = "cacu/cohorte_vigilancia"
outcome = "cin2_mas"
def provenance(self) -> Provenance:
return Provenance(modelo_nombre="constant", modelo_version="1", mlflow_run_id="none", modelo_sha="sha")
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]:
i_pac = columns.index("pac_id")
return [Risk(row[i_pac], h, 0.1) for row in rows for h in (0.0, 1.0)]
class Incomplete:
"""Has everything but `provenance`."""
cohort_url = "cacu/cohorte_vigilancia"
outcome = "cin2_mas"
def estimate(self, columns, rows):
return []
def test_a_class_with_the_four_members_meets_the_contract():
"""Pins down: `RiskEstimator` is checked at run time by its members (`cohort_url`, `outcome`,
`provenance`, `estimate`), not by inheritance; missing one fails the check.
Fails if the protocol stops being `runtime_checkable` or a member is renamed.
"""
assert isinstance(ConstantEstimator(), RiskEstimator)
assert not isinstance(Incomplete(), RiskEstimator)
def test_provenance_has_the_four_keys_a_batch_stores():
"""Pins down: `Provenance.as_dict()` has exactly the four keys of the risk batch's provenance columns.
Fails if a field is renamed or added: the batch columns wouldn't match.
"""
assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id",
"modelo_sha"}
def test_a_risk_keeps_the_column_names_and_its_interval_is_optional():
"""Pins down: `Risk` fields are named after the columns they're saved to, in that order, and the
interval defaults to `None`.
Fails if a field is renamed or reordered, or the interval becomes required.
"""
risk = Risk(1, 0.0, 0.25)
assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
assert (risk.ic_bajo, risk.ic_alto) == (None, None)
+60
View File
@@ -0,0 +1,60 @@
import onnx
import onnx.helper
import pytest
from models.io.export import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
return model.SerializeToString()
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
path = tmp_path / "model.onnx"
path.write_bytes(_tiny_onnx_bytes())
metadata = inspect_onnx_metadata(path)
assert metadata["available"] is True
assert metadata["producer_name"] == "pytest-fixture"
assert metadata["graph_inputs"] == ["x"]
assert metadata["graph_outputs"] == ["y"]
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
"""A protobuf-valid but structurally broken graph (a node reading an
input the graph never declares) must be rejected: `onnx.load` alone
only parses the protobuf and would let this through."""
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "broken", [], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
path = tmp_path / "model.onnx"
path.write_bytes(model.SerializeToString())
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
inspect_onnx_metadata(path)
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "onnx":
raise ImportError("onnx not installed")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
path = tmp_path / "model.onnx"
path.write_bytes(b"irrelevant")
assert inspect_onnx_metadata(path) == {
"available": False,
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
}
+183
View File
@@ -0,0 +1,183 @@
"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`), the
code version every run records (`code_version`), and choosing the version to use (`registry.resolve`).
Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready`
(from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a
pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a
logged model; `_git` asks git about this repository, to compare with what the run recorded.
"""
import subprocess
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
import pytest
from core.governance.enums import Environment
from mlflow import MlflowClient
from models.io import training
from models.io.registry import MODEL_SHA_TAG, registry
from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
class Constant(mlflow.pyfunc.PythonModel):
"""Returns `p` for every row."""
def __init__(self, p: float):
self.p = p
def predict(self, context, model_input: pd.DataFrame, params=None) -> list[float]:
return [self.p] * len(model_input)
def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[TrainingRun, str]:
"""A dev run of `cacu/<scenario>` that logs `model` (if any) and is registered; returns the run and
its version."""
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
if model is not None:
run.log_model(model)
return run, run.finish(metrics={"auc": 0.7})
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
"""Pins down: a run that logs a model registers `runs:/<run_id>/model`, and loading the version gives
back that model, tagged with its `modelo_sha` on the run and on the version.
Fails if `finish` registers the run instead of its model folder, or the sha isn't tagged.
"""
run, version = _train(Constant(0.25))
loaded = mlflow.pyfunc.load_model(registry.resolve("cacu", "tamizaje", version).model_uri)
mv = registry.get("cacu", "tamizaje", version)
assert list(loaded.predict(pd.DataFrame({"x": [1, 2]}))) == [0.25, 0.25]
assert mv.source == f"runs:/{run.run_id}/model"
assert mv.tags[MODEL_SHA_TAG] == run.modelo_sha
assert MlflowClient().get_run(run.run_id).data.tags[MODEL_SHA_TAG] == run.modelo_sha
def test_the_sha_is_the_model_not_the_run(mlflow_tracking):
"""Pins down: the same model logged in two runs has the same `modelo_sha`; a different model has
another one.
Fails if `model_sha` starts covering files with ids or dates (`MLmodel`), or stops covering the model.
"""
first, _ = _train(Constant(0.25))
second, _ = _train(Constant(0.25))
other, _ = _train(Constant(0.30))
assert first.modelo_sha == second.modelo_sha != other.modelo_sha
def test_a_run_logs_one_model(mlflow_tracking):
"""Pins down: a second `log_model` in the same run is refused.
Fails if a run could hold two models, so its version wouldn't say which one it is.
"""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_model(Constant(0.25))
with pytest.raises(RuntimeError, match="already logged"):
run.log_model(Constant(0.30))
def test_a_run_without_a_model_still_registers_the_run(mlflow_tracking):
"""Pins down: a run that doesn't log a model registers `runs:/<run_id>` with no `modelo_sha`, as
before `log_model` existed.
Fails if `finish` requires a model.
"""
run, version = _train()
resolved = registry.resolve("cacu", "tamizaje", version)
assert registry.get("cacu", "tamizaje", version).source == f"runs:/{run.run_id}"
assert resolved.modelo_sha is None
def test_without_a_version_resolve_takes_production(production_ready):
"""Pins down: with no version, `resolve` returns the one holding `produccion`, with that status; with
none in production it raises `LookupError`.
Fails if `resolve` falls back to the latest version instead of failing.
"""
domain, scenario, version = production_ready("v1")
with pytest.raises(LookupError, match="no version in production"):
registry.resolve(domain, scenario)
registry.promote(domain, scenario, version)
resolved = registry.resolve(domain, scenario)
assert (resolved.version, resolved.status) == (version, "produccion")
assert resolved.model_uri == f"models:/{domain}-{scenario}/{version}"
def test_an_explicit_version_is_returned_with_its_status(production_ready):
"""Pins down: with a version, `resolve` returns it whatever its status (a candidate can be tested),
and says which status it has; an unknown version raises `LookupError`.
Fails if an explicit version is refused for not being in production, or its status is lost.
"""
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2")
registry.promote(domain, scenario, first)
assert registry.resolve(domain, scenario, second).status == "candidata"
assert registry.resolve(domain, scenario, first).status == "produccion"
with pytest.raises(LookupError):
registry.resolve(domain, scenario, "99")
def _git(*args: str) -> str:
return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True,
check=True).stdout.strip()
def test_every_run_records_the_commit_of_the_code(mlflow_tracking):
"""Pins down: a run is tagged with the git commit of the `models` repository (MLflow's own tag name) and
whether tracked files had uncommitted changes; untracked files (notebooks, data) don't count.
Fails if the tags are dropped or renamed, or the dirty flag counts untracked files.
"""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
tags = MlflowClient().get_run(run.run_id).data.tags
assert tags[GIT_COMMIT_TAG] == _git("rev-parse", "HEAD")
assert tags[GIT_DIRTY_TAG] == str(bool(_git("status", "--porcelain", "--untracked-files=no"))).lower()
def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_tracking, monkeypatch):
"""Pins down: where git or the repository is missing (a delivered image), the commit is read from
`MODELS_GIT_COMMIT`, with no dirty flag; with neither, the run records no commit rather than a guess.
Fails if a missing repository raises, or a commit is invented.
"""
def no_git(*args, **kwargs):
raise FileNotFoundError("git")
monkeypatch.setattr(training.subprocess, "run", no_git)
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
assert tags[GIT_COMMIT_TAG] == "abc123" and GIT_DIRTY_TAG not in tags
monkeypatch.delenv(GIT_COMMIT_ENV)
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
assert GIT_COMMIT_TAG not in tags
def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking):
"""Pins down: a PROD run only logs a model whose class lives in a module; one defined in a notebook or
script (`__main__`) is refused, because its code has no commit to trace. A dev run accepts it.
Fails if the check is dropped, or starts refusing dev runs or module classes.
"""
InNotebook = type("InNotebook", (Constant,), {"__module__": "__main__"})
prod = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD, cohorte_armado_id=1)
with pytest.raises(ValueError, match="defined in a notebook"):
prod.log_model(InNotebook(0.25))
prod.log_model(Constant(0.25))
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).log_model(InNotebook(0.25))
+74
View File
@@ -0,0 +1,74 @@
import json
import pytest
from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.io.registry import registry
class StubModel:
def predict(self, data):
return {"label": "positivo", "confianza": 0.73}
def never_applicable(row: dict) -> bool:
return False
def _promote_a_version(production_ready):
domain, scenario, version = production_ready("v1-prod")
return registry.promote(domain, scenario, version)
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
version = _promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
prediction = service.predict_and_record(
{"edad": 40},
pac_id_hospital="H-1",
interpretability=Interpretability(odds_ratio=1.8),
)
assert prediction.mlflow_run_id == version.run_id
assert prediction.modelo_version == str(version.version)
assert prediction.applicability_passed is True
assert json.loads(prediction.output)["label"] == "positivo"
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
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", aplicable=never_applicable
)
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
assert prediction.applicability_passed is False
def test_applicability_gate_can_reject_outright(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(),
domain="cacu",
scenario="tamizaje",
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")
+74
View File
@@ -0,0 +1,74 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.io.registry import PromotionBlocked, registry
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert registry.status("cacu", "tamizaje", version) == "desarrollo"
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2", metrics={"auc": 0.84})
assert registry.status(domain, scenario, first) == "candidata"
registry.promote(domain, scenario, first)
registry.promote(domain, scenario, second)
assert registry.status(domain, scenario, first) == "retirada"
assert registry.status(domain, scenario, second) == "produccion"
other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico")
registry.promote(other_domain, other_scenario, other_version)
assert registry.status(domain, scenario, second) == "produccion"
def test_reports_can_be_attached_after_training(production_ready):
domain, scenario, version = production_ready("v1")
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None)
assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf")
assert all(c.passed for c in registry.checks(domain, scenario, version))
with pytest.raises(ValueError):
registry.attach_reports(domain, scenario, version, metrics="{}")
def test_artifacts_are_logged_to_the_run(production_ready):
domain, scenario, version = production_ready("v1")
lineage = registry.lineage(domain, scenario, version)
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
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["cohorte_armado"]["huella"] == "huella-v2"
assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"]
assert lineage["model_version"]["status"] == "produccion"
registry.retire(domain, scenario, second)
assert registry.status(domain, scenario, second) == "retirada"
with pytest.raises(ValueError):
registry.retire(domain, scenario, second)
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.io.export import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
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)
+28
View File
@@ -0,0 +1,28 @@
"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name.
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
"""
import pytest
from models.io.repositories import resolve_repository
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
"""A repository found by name reads what was written through it, in batches and with filters. Fails if
`resolve_repository` looks in another module or stops returning a working repository."""
from datetime import date
from core.cacu.models import Paciente
repository = resolve_repository("cacu", "paciente")
for i in range(7):
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
assert [r.pac_id_hospital for r in repository.iter_all(batch_size=3)] == [f"M-{i}" for i in range(7)]
assert list(repository.iter_all(pac_id_hospital="M-3"))[0].pac_sexo == "Femenino"
def test_unknown_entity_is_a_clear_error():
"""An unknown name raises `ValueError` naming it. Fails if the `AttributeError` is no longer translated."""
with pytest.raises(ValueError, match="no nope_repository"):
resolve_repository("tea", "nope")
+83
View File
@@ -0,0 +1,83 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.io.registry import registry
from mlflow import MlflowException
from models.io.training import ReadOnlyRepository, TrainingRun
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_a_cohort_build(mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.cohorte_armado_id is None
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
checkpoint = tmp_path / "model.onnx"
checkpoint.write_bytes(b"fake-onnx-bytes")
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
metrics = registry.client.get_run(mv.run_id).data.metrics
assert metrics["auc"] == 0.81
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
assert any(path.endswith("model.onnx") for path in artifacts)
def test_read_only_repository_blocks_writes(cacu_db):
from persistance.cacu import paciente_repository
read_only = ReadOnlyRepository(paciente_repository)
assert read_only.list() == []
with pytest.raises(PermissionError, match="ML-04"):
read_only.create(object())
with pytest.raises(PermissionError, match="ML-04"):
read_only.open_session()
def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
repo = run.repository("paciente")
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)