Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking

This commit is contained in:
2026-11-05 16:12:23 -06:00
parent 0fdab3651c
commit 9808701c46
35 changed files with 1710 additions and 719 deletions
+155 -16
View File
@@ -1,7 +1,9 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own: the promotion checks tied to the cohort a version was
trained on and to the validation-report convention.
trained on and to the validation-report convention, and `PredictionService`,
which stores each single prediction with the version in production (MLD-4/5,
EL-04b).
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
@@ -11,26 +13,28 @@ Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
database). A version points to its build with the `kit.armado_id` tag, and
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
"""
import hashlib
import json
import re
import tempfile
from collections.abc import Callable
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any
from typing import Any, Protocol
from core.governance.enums import ArtifactKind, Environment
from core.governance.models import ModelPrediction
from mlflow import MlflowClient, MlflowException
from persistance.governance import model_prediction_repository
from sqlmodel import select
from models.io.export import inspect_onnx_metadata
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name
from models.io.tracking import MODEL_PATH, TrainingRun, inspect_onnx_metadata, log_artifact_file
DOMAINS = ("cacu", "cama", "tea")
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
ARMADO_TAG = "kit.armado_id"
MODEL_SHA_TAG = "modelo_sha"
@dataclass(frozen=True)
@@ -48,10 +52,6 @@ class PromotionBlocked(Exception):
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
@dataclass(frozen=True)
class ResolvedVersion:
"""The version a caller will use, with what it needs to load it and to say where risks came from.
@@ -141,12 +141,34 @@ class ModelRegistry:
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.io.training.TrainingRun` directly."""
from models.io.training import TrainingRun
"""For training code that runs elsewhere and reports over the API: a run with these metrics, registered.
In-process training opens its own `TrainingRun` and calls `register_run`."""
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports)
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
cohort link, `modelo_sha`, report URIs), and returns the version."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(run.domain, run.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
if run.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
if run.modelo_sha is not None:
version_tags[MODEL_SHA_TAG] = run.modelo_sha
version_tags.update({key: uri for key, uri in reports.items() if uri})
source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}"
return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version)
def set_description(self, domain: str, scenario: str, version: str, description: str) -> None:
self.client.update_model_version(registered_name(domain, scenario), version, description=description)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
@@ -169,7 +191,7 @@ class ModelRegistry:
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
log_artifact_file(self.client, mv.run_id, kind_value, path)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
@@ -280,3 +302,120 @@ def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
"armado_en": armado.armado_en.isoformat()},
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
class Predictor(Protocol):
"""What the service needs from a model."""
def predict(self, data: Any) -> Any: ...
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a model and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: Predictor,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction