"""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 lineage from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG from models.io.registry import registry from models.io.tracking import 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/` 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, registry.register_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://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:/` 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(lineage.__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(lineage.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))