"""Bookkeeping around a training run (ML-01..ML-05). Does not train anything. It opens an MLflow run, records which cohort build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped methods instead of the fluent API's global active run, so two runs in one process never interfere. `MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their 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`: 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 import mlflow.pyfunc from core.governance.enums import ArtifactKind, Environment from mlflow import MlflowClient, MlflowException from persistance.repository import Repository from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name from models.io.repositories import resolve_repository 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: """sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left out because it carries ids and dates, so the same model saved twice has the same sha.""" return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest() class ReadOnlyRepository: """ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`. Write methods raise `PermissionError` so a training routine cannot modify clinical data.""" _WRITE_METHODS = {"create", "bulk_upsert", "open_session"} def __init__(self, repository: Repository): self._repository = repository self.model = repository.model def get(self, id_): return self._repository.get(id_) def list(self, *, limit: int = 100, offset: int = 0, **filters): return self._repository.list(limit=limit, offset=offset, **filters) def count(self, **filters) -> int: return self._repository.count(**filters) def __getattr__(self, name: str): if name in self._WRITE_METHODS: raise PermissionError( f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository." ) raise AttributeError(name) class TrainingRun: """One instance per training execution, wrapping one MLflow run. PROD runs require `cohorte_armado_id`, the indicator kit cohort build they were trained on, so their metrics trace back to that data (ML-03); dev runs may omit it. """ def __init__( self, *, domain: str, scenario: str, environment: Environment | str, cohorte_armado_id: int | None = None, ): if domain not in DOMAINS: raise ValueError(f"dominio desconocido: {domain!r}") environment = Environment(environment) if environment is Environment.PROD and cohorte_armado_id is None: raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).") self.domain = domain self.scenario = scenario self.environment = environment self.cohorte_armado_id = cohorte_armado_id self.client = MlflowClient() experiment_id = self._experiment_id() run = self.client.create_run( experiment_id, tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()}, ) self.run_id = run.info.run_id self.modelo_sha: str | None = None if cohorte_armado_id is not None: self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id)) def _experiment_id(self) -> str: name = registered_name(self.domain, self.scenario) experiment = self.client.get_experiment_by_name(name) if experiment: return experiment.experiment_id root = os.environ.get(ARTIFACT_ROOT_ENV) return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None) def repository(self, entity: str) -> ReadOnlyRepository: """ML-04: read-only access to `persistance.._repository`.""" return ReadOnlyRepository(resolve_repository(self.domain, entity)) def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None: """ML-01a/ML-01b: logs an artifact file to the run, under a folder named for its kind.""" kind = ArtifactKind(kind) self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value) if metadata: self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json") def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str: """Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its `modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input 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) sha = model_sha(path) self.client.log_artifacts(self.run_id, str(path), MODEL_PATH) self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha) self.modelo_sha = sha return sha def finish( self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None, **reports: str | None, ) -> str: """Logs metrics/params to the run, registers it as a new version of `-` tagged with `models.io.registry`'s promotion inputs (environment, cohort link, report URIs), and returns the new version string. Call once, after training (and artifact logging) completes.""" unknown = set(reports) - set(REPORT_TAGS) if unknown: raise ValueError(f"campos desconocidos: {sorted(unknown)}") for key, value in (metrics or {}).items(): self.client.log_metric(self.run_id, key, value) for key, value in (hyperparameters or {}).items(): self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str)) name = registered_name(self.domain, self.scenario) try: self.client.create_registered_model(name) except MlflowException as exc: if exc.error_code != "RESOURCE_ALREADY_EXISTS": raise version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value} if self.cohorte_armado_id is not None: version_tags[ARMADO_TAG] = str(self.cohorte_armado_id) if self.modelo_sha is not None: version_tags[MODEL_SHA_TAG] = self.modelo_sha version_tags.update({key: uri for key, uri in reports.items() if uri}) source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}" model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags) self.client.set_terminated(self.run_id) return str(model_version.version)