diff --git a/README.md b/README.md index 0e717cc..32fa680 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ WebApi. | `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). | | `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. | | `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | -| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | +| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | diff --git a/models/training.py b/models/training.py index cbdc847..d25e0a7 100644 --- a/models/training.py +++ b/models/training.py @@ -11,11 +11,17 @@ process never interfere. artifacts (MLflow's own default is `./mlruns`, relative to the working directory). A run that logs a model (`log_model`) registers `runs://model`, tagged -with its `modelo_sha`; one that doesn't registers the run itself. +with its `modelo_sha`: the hash of the stored artifact, which identifies the exact +model that produced a risk. Which code trained it is recorded apart: every run is +tagged with the git commit of this package's repository and whether it had +uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the +delivered images). A PROD run only logs models whose class lives in a module, at a +known commit, never one defined in a notebook. """ import hashlib import json import os +import subprocess import tempfile from pathlib import Path from typing import Any @@ -30,6 +36,25 @@ from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, reg ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" MODEL_PATH = "model" +GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets +GIT_DIRTY_TAG = "models.git.dirty" +GIT_COMMIT_ENV = "MODELS_GIT_COMMIT" + + +def code_version() -> dict[str, str]: + """The git commit of this package's repository and whether tracked files have uncommitted changes. + Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither, + nothing is recorded.""" + root = Path(__file__).resolve().parent + try: + commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, + check=True).stdout.strip() + changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"], + capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + commit = os.environ.get(GIT_COMMIT_ENV) + return {GIT_COMMIT_TAG: commit} if commit else {} + return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()} def model_sha(model_dir: str | Path) -> str: @@ -95,7 +120,7 @@ class TrainingRun: experiment_id = self._experiment_id() run = self.client.create_run( experiment_id, - tags={"domain": domain, "scenario": scenario, "environment": environment.value}, + tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()}, ) self.run_id = run.info.run_id self.modelo_sha: str | None = None @@ -128,6 +153,9 @@ class TrainingRun: example, so no patient data reaches MLflow.""" if self.modelo_sha is not None: raise RuntimeError("this run already logged its model") + if self.environment is Environment.PROD and type(python_model).__module__ == "__main__": + raise ValueError("a PROD run only logs models whose class lives in a module; " + f"{type(python_model).__name__} was defined in a notebook or script") with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / MODEL_PATH mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature) diff --git a/tests/test_model_versions.py b/tests/test_model_versions.py index cb47c86..505e23a 100644 --- a/tests/test_model_versions.py +++ b/tests/test_model_versions.py @@ -1,20 +1,24 @@ -"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`) and -choosing the version to use (`registry.resolve`). +"""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. +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 import training from models.registry import MODEL_SHA_TAG, registry -from models.training import TrainingRun +from models.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun class Constant(mlflow.pyfunc.PythonModel): @@ -122,3 +126,58 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready): 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)) +