diff --git a/README.md b/README.md index de51761..52c1490 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,26 @@ # models -Python package with the standard `train()`/`predict()` interface for the -three screening models — CaCu, CaMa and TEA. Consumed by `WebApi`, but -independent of it: this package can read its own training/inference data -directly from `Persistance`, without going through `WebApi` at all. +Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de +versiones en MLflow con requisitos de promoción, registro de predicciones y +los trabajos de OCR de reportes. Las cohortes con que se entrena son los +armados del kit de indicadores (`cohorte_armado`, en la base de cada +dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa +WebApi. -## Structure +| Módulo | Qué hace | +|---|---| +| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | +| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | +| `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). | +| `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). | +| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | -- `models/base.py` — `ScreeningModel`, the abstract base every model - implements (`train(data)` / `predict(data)`). -- `models/cacu.py`, `models/cama.py`, `models/tea.py` — one concrete - class per domain. +MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`). +`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos +guardan sus artefactos. -## How entities are accessed from models - -This package depends on `../Persistance` (a local `uv` path dependency — -see `pyproject.toml`), and through it on `../Core`. **As of now this is -wiring, not usage**: `train()`/`predict()` in `cacu.py`/`cama.py`/`tea.py` -just raise `NotImplementedError` — no model imports `persistance` yet. - -When real training/inference logic is added, the access pattern is the -same repository instances `WebApi` reads from — no separate data layer -for `models` to maintain: - -```python -# models/models/cacu.py -from typing import Any - -from persistance.cacu import citologia_cervical_repository - -from models.base import ScreeningModel - - -class CaCuModel(ScreeningModel): - def train(self, data: Any = None) -> None: - if data is None: - data = citologia_cervical_repository.list(limit=10_000) - # ... fit on `data` - - def predict(self, data: Any) -> Any: - raise NotImplementedError("CaCu prediction is not implemented yet.") +```bash +uv run pytest -q ``` - -The `data: Any = None` default on `train()`/`predict()` is what lets a -caller (e.g. `WebApi`) optionally hand over already-fetched rows instead -of forcing every call to hit the database — but a model implementation is -just as free to call `persistance.` itself when `data` is `None`, -exactly like the example above. - -Each domain's available repositories (`paciente_repository`, -`citologia_cervical_repository`, etc.) and how to extend one with -table-specific business logic are documented in -`../Persistance/README.md`. diff --git a/models/base.py b/models/base.py index 00b6c46..b6773f5 100644 --- a/models/base.py +++ b/models/base.py @@ -29,16 +29,8 @@ class ScreeningModel(ABC): return resolve_repository(self.domain, entity) def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]: - """Every row of `entity` as plain dicts, paged through the - repository so a large table is never loaded in one go.""" - repository = self.repository(entity) - offset = 0 - while True: - page = repository.list(limit=batch_size, offset=offset, **filters) - yield from (row.model_dump() for row in page) - if len(page) < batch_size: - return - offset += batch_size + """Every row of `entity` as plain dicts, read in batches.""" + return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters)) @abstractmethod def train(self, data: Any = None) -> None: diff --git a/models/cohort.py b/models/cohort.py deleted file mode 100644 index e4ff9b4..0000000 --- a/models/cohort.py +++ /dev/null @@ -1,196 +0,0 @@ -"""Cohort construction, versioning and exclusion tracking (EL-01..EL-07, -TRIPOD+AI 20a). A `CohortBuilder` turns a domain's clinical episodes into a -frozen, hashed cohort (`CohortVersion` + `CohortMember`) that training -reads instead of the live tables, which may change later. - -- `build()` (training time, EL-04a) applies every `ExclusionCriterion`, - logs each exclusion with its reason (EL-05) and the per-criterion counts - (EL-07). -- `evaluate_applicability()` (production, EL-04b) checks one new row - against the criteria marked `applicable_in_production` only; criteria - that need future follow-up are never among them. It writes nothing. -""" -import hashlib -import json -from dataclasses import dataclass -from typing import Any, Callable, Sequence - -from models.base import resolve_repository -from persistance.governance import ( - cohort_exclusion_count_repository, - cohort_exclusion_repository, - cohort_member_repository, - cohort_version_repository, -) -from core.governance.models import CohortExclusion, CohortExclusionCount, CohortMember, CohortVersion - - -@dataclass -class ExclusionCriterion: - code: str - reason_code: str - predicate: Callable[[dict[str, Any]], bool] - """Returns True when the row should be EXCLUDED.""" - applicable_in_production: bool = False - """EL-04b: whether this criterion is also checked on new rows in - production. Leave False for criteria that depend on future follow-up, - which can only be evaluated when building the training table.""" - - -def compute_version_hash(*, criteria_version: str, criterion_codes: Sequence[str], episode_ids: Sequence[int]) -> str: - """EL-02/EL-03: deterministic hash of the criteria version, the - criterion codes applied and the source episode ids. A change in any of - them, such as new patients or a longer analysis period, yields a new - version.""" - payload = json.dumps( - { - "criteria_version": criteria_version, - "criterion_codes": sorted(criterion_codes), - "episode_ids": sorted(episode_ids), - }, - sort_keys=True, - ) - return hashlib.sha256(payload.encode("utf-8")).hexdigest() - - -class CohortBuilder: - """Builds the cohort for one clinical scenario (one model per scenario, - one cohort table per model). Subclasses set `criteria` and may override - `fetch_episodes` (EL-01).""" - - domain: str - scenario: str - criteria_version: str - criteria: Sequence[ExclusionCriterion] = () - - def fetch_episodes(self) -> list[dict[str, Any]]: - """Episode rows as plain dicts (EL-01). The default pages through - `persistance..episodio_clinico_repository`; override it when - a scenario needs extra joins to build its features.""" - repository = resolve_repository(self.domain, "episodio_clinico") - episodes: list[dict[str, Any]] = [] - offset = 0 - while True: - page = repository.list(limit=500, offset=offset) - episodes.extend(row.model_dump() for row in page) - if len(page) < 500: - break - offset += 500 - return episodes - - def build(self, *, description: str | None = None) -> CohortVersion: - episodes = self.fetch_episodes() - n_source = len(episodes) - - excluded_ids: set[int] = set() - exclusion_rows: list[CohortExclusion] = [] - exclusion_counts: dict[tuple[str, str], int] = {} - - for episode in episodes: - episode_id = episode.get("episodio_id") - for criterion in self.criteria: - if episode_id in excluded_ids: - break - if criterion.predicate(episode): - excluded_ids.add(episode_id) - exclusion_rows.append( - CohortExclusion( - cohort_version_id=0, # filled in once the CohortVersion exists - pac_id_hospital=episode.get("pac_id_hospital", ""), - episodio_id=episode_id, - criterion_code=criterion.code, - reason_code=criterion.reason_code, - ) - ) - key = (criterion.code, criterion.reason_code) - exclusion_counts[key] = exclusion_counts.get(key, 0) + 1 - - included = [e for e in episodes if e.get("episodio_id") not in excluded_ids] - - version_hash = compute_version_hash( - criteria_version=self.criteria_version, - criterion_codes=[c.code for c in self.criteria], - episode_ids=[e.get("episodio_id") for e in episodes if e.get("episodio_id") is not None], - ) - - cohort_version = cohort_version_repository.create( - CohortVersion( - domain=self.domain, - scenario=self.scenario, - criteria_version=self.criteria_version, - version_hash=version_hash, - source_table=f"{self.domain}.episodioclinico", - description=description, - n_source=n_source, - n_included=len(included), - ) - ) - - for row in exclusion_rows: - row.cohort_version_id = cohort_version.cohort_version_id - if exclusion_rows: - with cohort_exclusion_repository.open_session() as session: - for row in exclusion_rows: - session.add(row) - session.commit() - - if exclusion_counts: - with cohort_exclusion_count_repository.open_session() as session: - for (criterion_code, reason_code), count in exclusion_counts.items(): - session.add( - CohortExclusionCount( - cohort_version_id=cohort_version.cohort_version_id, - criterion_code=criterion_code, - reason_code=reason_code, - count=count, - ) - ) - session.commit() - - if included: - with cohort_member_repository.open_session() as session: - for episode in included: - session.add( - CohortMember( - cohort_version_id=cohort_version.cohort_version_id, - pac_id_hospital=episode.get("pac_id_hospital", ""), - episodio_id=episode.get("episodio_id"), - feature_snapshot=json.dumps(episode, default=str, sort_keys=True), - ) - ) - session.commit() - - return cohort_version - - def evaluate_applicability(self, row: dict[str, Any]) -> bool: - """EL-04b: production gate. Returns False if any criterion marked - `applicable_in_production` would exclude the row. Writes nothing; - exclusion logs belong to the training-time build (EL-04a).""" - return not any(c.predicate(row) for c in self.criteria if c.applicable_in_production) - - -COHORT_BUILDERS: dict[tuple[str, str], type[CohortBuilder]] = {} - - -def register_cohort_builder(cls: type[CohortBuilder]) -> type[CohortBuilder]: - """Registers a scenario's builder so the API can list and run it: - - @register_cohort_builder - class TamizajeCaCu(CohortBuilder): - domain, scenario, criteria_version = "cacu", "tamizaje", "v1" - criteria = [ExclusionCriterion("EDAD", "fuera_de_rango", lambda e: ..., applicable_in_production=True)] - """ - COHORT_BUILDERS[(cls.domain, cls.scenario)] = cls - return cls - - -def describe_builder(cls: type[CohortBuilder]) -> dict[str, Any]: - return { - "domain": cls.domain, - "scenario": cls.scenario, - "criteria_version": cls.criteria_version, - "criteria": [ - {"code": c.code, "reason_code": c.reason_code, "applicable_in_production": c.applicable_in_production} - for c in cls.criteria - ], - } diff --git a/models/ocr.py b/models/ocr.py index 49fb089..e54b671 100644 --- a/models/ocr.py +++ b/models/ocr.py @@ -22,6 +22,9 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, ClassVar +from sqlalchemy import func, or_ +from sqlmodel import select + from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH from core.cama.enums import GradoHistologicoMama from core.ocr import OcrEstatus @@ -208,18 +211,16 @@ def run_pending_extractions( from core.governance.models import ExtractionRun summary = OcrRunSummary() - pk_name = next(iter(repository.model.__table__.primary_key.columns)).name - candidates = repository.list(limit=limit) + model = repository.model + primary_key = list(model.__table__.primary_key.columns) + estatus = getattr(model, spec.estatus_field) + with_report = getattr(model, spec.blob_field).is_not(None) + done = estatus == OcrEstatus.REALIZADO.value with repository.open_session() as session: - for row in candidates: - pk_value = getattr(row, pk_name) - tracked = session.get(repository.model, pk_value) - if tracked is None or getattr(tracked, spec.blob_field, None) is None: - continue - if getattr(tracked, spec.estatus_field, None) == OcrEstatus.REALIZADO: - summary.skipped_already_done += 1 - continue - + summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one() + pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit) + for tracked in session.exec(pending).all(): + pk_value = getattr(tracked, primary_key[0].name) started_at = datetime.now(timezone.utc) try: result = extractor.extract(getattr(tracked, spec.blob_field)) diff --git a/models/prediction.py b/models/prediction.py index 61cc349..fc00737 100644 --- a/models/prediction.py +++ b/models/prediction.py @@ -1,27 +1,26 @@ """MLD-4/MLD-5: every prediction is stored with the MLflow model version that -produced it. WebApi's `/predict` routes go through `PredictionService` -rather than calling `model.predict(...)` directly. +produced it. Callers go through `PredictionService` rather than calling +`model.predict(...)` directly. """ import hashlib import json +from collections.abc import Callable from dataclasses import dataclass from typing import Any -from mlflow import MlflowException - from core.governance.models import ModelPrediction -from models.base import ScreeningModel -from models.cohort import CohortBuilder -from models.registry import PRODUCTION_ALIAS, registered_name, registry +from mlflow import MlflowException from persistance.governance import model_prediction_repository +from models.base import ScreeningModel +from models.registry import PRODUCTION_ALIAS, registered_name, registry + @dataclass class Interpretability: - """MLD-03: campos mínimos que toda estimación debe poder reportar para - interpretabilidad clínica. Todos opcionales: cada modelo llena los que - apliquen a su método (p. ej. odds_ratio en una regresión logística, - hazard_ratio en un modelo de supervivencia).""" + """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 @@ -46,10 +45,9 @@ class PredictionService: """Runs a `ScreeningModel` and records its predictions against the MLflow version holding the `produccion` alias for `(domain, scenario)`. - If `cohort_builder` is given, each row is checked with - `evaluate_applicability` (EL-04b). Inapplicable rows are still scored - but stored with `applicability_passed=False`, unless - `reject_inapplicable` is set. + 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__( @@ -58,13 +56,13 @@ class PredictionService: *, domain: str, scenario: str, - cohort_builder: CohortBuilder | None = None, + aplicable: Callable[[dict], bool] | None = None, reject_inapplicable: bool = False, ): self.model = model self.domain = domain self.scenario = scenario - self.cohort_builder = cohort_builder + self.aplicable = aplicable self.reject_inapplicable = reject_inapplicable def active_model_version(self): @@ -86,26 +84,27 @@ class PredictionService: ) -> 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; WebApi maps it to 501. + propagated unchanged. """ applicability_passed = True - if self.cohort_builder is not None: - row = data if isinstance(data, dict) else {} - applicability_passed = self.cohort_builder.evaluate_applicability(row) + 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 before looking up the version so an unimplemented model - # surfaces as NotImplementedError even with no ModelVersion seeded. + # 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 — " - "promueve una con models.registry.registry.promote antes de predecir" + f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; " + "promueva una con models.registry.registry.promote antes de predecir" ) input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest() diff --git a/models/registry.py b/models/registry.py index 2c9368c..cf104c5 100644 --- a/models/registry.py +++ b/models/registry.py @@ -1,25 +1,35 @@ """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 our cohort versioning and -validation-report convention. +about on its own: the promotion checks tied to the cohort a version was +trained on and to the validation-report convention. Training, versioning, artifact storage and stage live in MLflow itself (`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is named `-`; "production" is the `produccion` alias on one -of its versions — never stored here, read from MLflow on every call. -`models.cohort`'s own `CohorteArmadoBase`/`EvaluacionRiesgoLoteBase` reference -MLflow the same way: by `mlflow_run_id`, never by copying its rows. +of its versions, never stored here and read from MLflow on every call. +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 re +import tempfile from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from importlib import import_module +from pathlib import Path from typing import Any -from mlflow import MlflowException, MlflowClient +from core.governance.enums import ArtifactKind, Environment +from mlflow import MlflowClient, MlflowException +from persistance.governance import model_prediction_repository +from sqlmodel import select -from core.governance.enums import Environment -from persistance.governance import cohort_exclusion_count_repository, cohort_version_repository, model_prediction_repository +from models.export import inspect_onnx_metadata +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" @dataclass(frozen=True) @@ -42,10 +52,7 @@ def registered_name(domain: str, scenario: str) -> str: class ModelRegistry: - """`registry` below is a module-level singleton, so `client` is resolved - fresh on every access instead of cached at construction time — otherwise - it would permanently bind to whatever `MLFLOW_TRACKING_URI` was set at - import time, ignoring any later change (every test sets its own).""" + """`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`.""" def __init__(self, client: MlflowClient | None = None): self._client = client @@ -54,8 +61,6 @@ class ModelRegistry: def client(self) -> MlflowClient: return self._client or MlflowClient() - # -- reading -------------------------------------------------------------- - def get(self, domain: str, scenario: str, version: str): try: return self.client.get_model_version(registered_name(domain, scenario), version) @@ -66,6 +71,10 @@ class ModelRegistry: """Every version, newest first. `scenario` needs `domain`; `domain` alone matches every scenario of that domain (MLflow's own `search_registered_models` LIKE filter); neither matches everything.""" + if domain and domain not in DOMAINS: + raise ValueError(f"dominio desconocido: {domain!r}") + if scenario and not re.fullmatch(r"[\w-]+", scenario): + raise ValueError(f"escenario inválido: {scenario!r}") if domain and scenario: names = [registered_name(domain, scenario)] elif domain: @@ -88,15 +97,13 @@ class ModelRegistry: def status(self, domain: str, scenario: str, version: str) -> str: return self._status(self.get(domain, scenario, version)) - # -- registering -------------------------------------------------------------- - def register( self, *, domain: str, scenario: str, environment: Environment | str, - cohort_version_id: int | None = None, + cohorte_armado_id: int | None = None, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None, **reports: str | None, @@ -105,7 +112,7 @@ class ModelRegistry: In-process training uses `models.training.TrainingRun` directly.""" from models.training import TrainingRun - run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohort_version_id=cohort_version_id) + run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id) return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports) def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None: @@ -119,15 +126,9 @@ class ModelRegistry: def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None: """Logs an artifact file to the run behind an already-registered - version (ML-01a/b) — e.g. a checkpoint exported after training. + version (ML-01a/b), e.g. a checkpoint exported after training. An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is rejected (400) instead of silently stored.""" - import tempfile - from pathlib import Path - - from core.governance.enums import ArtifactKind - from models.export import inspect_onnx_metadata - mv = self.get(domain, scenario, version) kind_value = kind.value if hasattr(kind, "value") else str(kind) with tempfile.TemporaryDirectory() as tmp: @@ -153,39 +154,32 @@ class ModelRegistry: return self._describe(self.get(domain, scenario, version)) def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]: - """Everything a version came from and produced: its cohort (hash and - exclusion counts), logged artifacts and predictions.""" + """Everything a version came from and produced: its cohort build (with + its attrition), logged artifacts and predictions.""" mv = self.get(domain, scenario, version) - cohort_version_id = mv.tags.get("cohort_version_id") - cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None - exclusions = ( - cohort_exclusion_count_repository.list(limit=500, cohort_version_id=cohort.cohort_version_id) if cohort else [] - ) + armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG)) return { "model_version": self.describe(domain, scenario, version), - "cohort_version": cohort.model_dump() if cohort else None, - "cohort_exclusions": [count.model_dump() for count in exclusions], + "cohorte_armado": armado, + "cohorte_exclusiones": exclusiones, "artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)], "predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)), "checks": [asdict(check) for check in self.checks(domain, scenario, version)], } - # -- promotion -------------------------------------------------------------------- - def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]: mv = self.get(domain, scenario, version) run = self.client.get_run(mv.run_id) - cohort_version_id = mv.tags.get("cohort_version_id") - cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None + armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG)) metrics = run.data.metrics artifacts = self.client.list_artifacts(mv.run_id) return [ PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")), PromotionCheck( "ML-03", - "enlazada a la versión de cohorte con la que se entrenó", - cohort is not None, - f"hash {cohort.version_hash[:12]}" if cohort else "sin cohorte", + "enlazada al armado de cohorte con el que se entrenó", + armado is not None, + f"huella {armado['huella'][:12]}" if armado else "sin cohorte", ), PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))), PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")), @@ -214,7 +208,7 @@ class ModelRegistry: def retire(self, domain: str, scenario: str, version: str): """Withdraws a version from production; its scenario has no active - model until another one is promoted, so predictions stop (503).""" + model until another one is promoted, so predictions stop.""" name = registered_name(domain, scenario) try: active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS) @@ -226,28 +220,30 @@ class ModelRegistry: self.client.set_model_version_tag(name, version, "retirada_en", _now_iso()) return self.get(domain, scenario, version) - def compare(self, domain: str, scenario: str, a: str, b: str) -> dict[str, Any]: - """Metric-by-metric difference (b - a) between two versions.""" - ma = self.client.get_run(self.get(domain, scenario, a).run_id).data.metrics - mb = self.client.get_run(self.get(domain, scenario, b).run_id).data.metrics - rows = [] - for name in sorted(set(ma) | set(mb)): - va, vb = ma.get(name), mb.get(name) - delta = vb - va if va is not None and vb is not None else None - rows.append({"metric": name, "a": va, "b": vb, "delta": delta}) - return {"a": self.describe(domain, scenario, a), "b": self.describe(domain, scenario, b), "metrics": rows} - def _now_iso() -> str: - from datetime import datetime, timezone - return datetime.now(timezone.utc).isoformat() def _iso(epoch_millis: int) -> str: - from datetime import datetime, timezone - return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat() registry = ModelRegistry() + + +def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]: + """The kit cohort build a version was trained on, and its attrition steps.""" + if not armado_id: + return None, [] + cohortes = import_module(f"persistance.{domain}").cohorte_repository + armado = cohortes.get(int(armado_id)) + if armado is None: + return None, [] + exclusion = cohortes.cohortes.CohorteExclusion + pasos = cohortes.leer(lambda sesion: sesion.exec( + select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all()) + return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella, + "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]) diff --git a/models/training.py b/models/training.py index 582c97f..e1305c7 100644 --- a/models/training.py +++ b/models/training.py @@ -1,28 +1,29 @@ """Bookkeeping around a training run (ML-01..ML-05). Does not train anything. It opens an MLflow run, records which cohort -version 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 -itself owns run tracking, metrics and artifact storage — this class only -adds the project-specific tags `finish()` needs for `models.registry`'s -promotion checks. +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. -Uses `MlflowClient`'s run-scoped methods (`log_metric(run_id, ...)`, not the -fluent `mlflow.log_metric(...)`) rather than MLflow's global active-run -stack, so an unfinished run from one `TrainingRun` can never block another -one started elsewhere in the same process. +`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their +artifacts (MLflow's own default is `./mlruns`, relative to the working directory). """ import json +import os from pathlib import Path from typing import Any -from mlflow import MlflowClient, MlflowException - from core.governance.enums import ArtifactKind, Environment -from models.base import resolve_repository -from models.registry import REPORT_TAGS, registered_name +from mlflow import MlflowClient, MlflowException from persistance.repository import Repository +from models.base import resolve_repository +from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name + +ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" + class ReadOnlyRepository: """ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`. @@ -47,15 +48,16 @@ class ReadOnlyRepository: def __getattr__(self, name: str): if name in self._WRITE_METHODS: raise PermissionError( - f"ML-04: un TrainingRun solo tiene permiso de lectura — '{name}' no está disponible en ReadOnlyRepository." + 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 `cohort_version_id` so their metrics can be traced to the - data that produced them (ML-03); dev runs may omit it. + 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__( @@ -64,16 +66,18 @@ class TrainingRun: domain: str, scenario: str, environment: Environment | str, - cohort_version_id: int | None = None, + 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 cohort_version_id is None: - raise ValueError("ML-03: una corrida PROD debe enlazar un cohort_version_id.") + 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.cohort_version_id = cohort_version_id + self.cohorte_armado_id = cohorte_armado_id self.client = MlflowClient() experiment_id = self._experiment_id() run = self.client.create_run( @@ -81,13 +85,16 @@ class TrainingRun: tags={"domain": domain, "scenario": scenario, "environment": environment.value}, ) self.run_id = run.info.run_id - if cohort_version_id is not None: - self.client.set_tag(self.run_id, "cohort_version_id", str(cohort_version_id)) + 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) - return experiment.experiment_id if experiment else self.client.create_experiment(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`.""" @@ -124,11 +131,12 @@ class TrainingRun: name = registered_name(self.domain, self.scenario) try: self.client.create_registered_model(name) - except MlflowException: - pass + 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.cohort_version_id is not None: - version_tags["cohort_version_id"] = str(self.cohort_version_id) + if self.cohorte_armado_id is not None: + version_tags[ARMADO_TAG] = str(self.cohorte_armado_id) version_tags.update({key: uri for key, uri in reports.items() if uri}) model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags) self.client.set_terminated(self.run_id) diff --git a/tests/conftest.py b/tests/conftest.py index 2c35ac1..67f5955 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,6 +11,8 @@ def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str) engine = getattr(persistance_db, f"get_{domain}_engine") engine.cache_clear() importlib.import_module(f"core.{domain}.models") + if domain != "governance": + importlib.import_module(f"core.{domain}.indicadores.models") base = getattr(importlib.import_module(base_module), base_class) base.metadata.create_all(engine()) return engine @@ -32,13 +34,7 @@ def cacu_db(tmp_path, monkeypatch): @pytest.fixture def mlflow_tracking(tmp_path, monkeypatch): - """A local, SQLite-backed MLflow tracking URI — no server, no network, - isolated per test (MLflow's own default local backend; the older plain - file store is deprecated as of MLflow 3). Also `chdir`s into `tmp_path`: - an experiment with no explicit `artifact_location` falls back to - `./mlruns` relative to the CWD, and production never sets one either - (the real MLflow server picks it, e.g. S3) — so this is purely test - isolation, not something `models.training` should set itself.""" + """A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`.""" import mlflow uri = f"sqlite:///{tmp_path / 'mlflow.db'}" @@ -49,24 +45,16 @@ def mlflow_tracking(tmp_path, monkeypatch): @pytest.fixture -def production_ready(governance_db, mlflow_tracking): +def production_ready(governance_db, cacu_db, mlflow_tracking): """Factory: registers a PROD version that passes every promotion check, returns (domain, scenario, version).""" from core.governance.enums import ArtifactKind, Environment - from core.governance.models import CohortVersion from models.registry import registry - from persistance.governance import cohort_version_repository def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None): - cohort = cohort_version_repository.create( - CohortVersion( - domain=domain, scenario=scenario, criteria_version="v1", version_hash=f"hash-{tag}", - source_table=f"{domain}.episodioclinico", n_source=10, n_included=8, - ) - ) version = registry.register( domain=domain, scenario=scenario, environment=Environment.PROD, - cohort_version_id=cohort.cohort_version_id, metrics=metrics or {"auc": 0.8}, + cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8}, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf", interpretability_report_uri="docs/interpretabilidad.html", ) @@ -83,3 +71,23 @@ def tiny_onnx() -> bytes: x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1]) y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1]) return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString() + + +def armado(huella: str) -> int: + """A CaCu cohort build with two attrition steps; returns its `armado_id`.""" + from datetime import date, datetime, timezone + + from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion + from persistance.db import get_cacu_session + + with get_cacu_session() as session: + fila = CohorteArmado( + url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}", + datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8, + armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)) + session.add(fila) + session.flush() + session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10), + CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)]) + session.commit() + return fila.armado_id diff --git a/tests/test_cohort.py b/tests/test_cohort.py deleted file mode 100644 index 5624cb0..0000000 --- a/tests/test_cohort.py +++ /dev/null @@ -1,79 +0,0 @@ -from datetime import date - -import pytest - -from models.cohort import CohortBuilder, ExclusionCriterion, compute_version_hash - - - -def _seed_episodes(): - from core.cacu.episodio_clinico.enums import TipoEpisodio - from core.cacu.models import EpisodioClinico - from persistance.cacu import episodio_clinico_repository - - for i, year in enumerate([2018, 2019, 2021, 2022, 2023]): - episodio_clinico_repository.create( - EpisodioClinico( - pac_id_hospital=f"H-{i}", - tipo_episodio=TipoEpisodio.TAMIZAJE, - evento_fecha=date(year, 6, 1), - ) - ) - - -class FechaVentanaCohortBuilder(CohortBuilder): - domain = "cacu" - scenario = "tamizaje_test" - criteria_version = "v1" - criteria = [ - ExclusionCriterion( - code="FECHA_FUERA_DE_VENTANA", - reason_code="ANTES_2020", - predicate=lambda e: e["evento_fecha"] < date(2020, 1, 1), - applicable_in_production=True, - ), - ] - - -def test_build_excludes_and_materializes_counts(cacu_db, governance_db): - _seed_episodes() - builder = FechaVentanaCohortBuilder() - - cohort_version = builder.build(description="ventana >= 2020") - - assert cohort_version.n_source == 5 - assert cohort_version.n_included == 3 - assert cohort_version.version_hash - - from persistance.governance import cohort_exclusion_count_repository, cohort_exclusion_repository, cohort_member_repository - - members = cohort_member_repository.list(cohort_version_id=cohort_version.cohort_version_id) - assert len(members) == 3 - - exclusions = cohort_exclusion_repository.list(cohort_version_id=cohort_version.cohort_version_id) - assert len(exclusions) == 2 - assert {e.reason_code for e in exclusions} == {"ANTES_2020"} - - counts = cohort_exclusion_count_repository.list(cohort_version_id=cohort_version.cohort_version_id) - assert len(counts) == 1 - assert counts[0].count == 2 - assert counts[0].criterion_code == "FECHA_FUERA_DE_VENTANA" - - -def test_version_hash_is_deterministic_and_order_independent(): - hash_a = compute_version_hash(criteria_version="v1", criterion_codes=["X", "Y"], episode_ids=[3, 1, 2]) - hash_b = compute_version_hash(criteria_version="v1", criterion_codes=["Y", "X"], episode_ids=[1, 2, 3]) - hash_c = compute_version_hash(criteria_version="v2", criterion_codes=["X", "Y"], episode_ids=[1, 2, 3]) - - assert hash_a == hash_b - assert hash_a != hash_c - assert len(hash_a) == 64 - - -def test_evaluate_applicability_uses_only_production_applicable_criteria(): - builder = FechaVentanaCohortBuilder() - old_row = {"evento_fecha": date(2018, 1, 1)} - recent_row = {"evento_fecha": date(2023, 1, 1)} - - assert builder.evaluate_applicability(old_row) is False - assert builder.evaluate_applicability(recent_row) is True diff --git a/tests/test_ocr.py b/tests/test_ocr.py index f3c940a..8ada0c3 100644 --- a/tests/test_ocr.py +++ b/tests/test_ocr.py @@ -1,10 +1,12 @@ -from datetime import date -import pytest from core.ocr import OcrEstatus -from models.ocr import CIT_VPH_COLUMNS, OcrExtractionResult, OcrExtractor, run_pending_extractions - +from models.ocr import ( + CIT_VPH_COLUMNS, + OcrExtractionResult, + OcrExtractor, + run_pending_extractions, +) class StubVphExtractor(OcrExtractor): @@ -95,3 +97,19 @@ def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db): assert len(runs) == 1 assert runs[0].domain == "cacu" assert runs[0].source_description == "HIS export 2026-09-01" + + +def test_done_rows_do_not_use_up_the_batch(cacu_db): + repo, CitologiaCervical = _make_cacu_citologia_repo() + for n in range(3): + repo.create(CitologiaCervical(pac_id_hospital=f"H-{n}", cit_vph_pdf_blob=b"%PDF-fake", + cit_vph_ocr_estatus=OcrEstatus.REALIZADO.value)) + repo.create(CitologiaCervical(pac_id_hospital="H-nuevo", cit_vph_pdf_blob=b"%PDF-fake")) + repo.create(CitologiaCervical(pac_id_hospital="H-sin-pdf")) + + summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", + entity="citologiacervical", limit=1) + + assert (summary.processed, summary.skipped_already_done) == (1, 3) + assert repo.list(pac_id_hospital="H-nuevo")[0].cit_vph_resultado == "POSITIVO" + assert repo.list(pac_id_hospital="H-sin-pdf")[0].cit_vph_ocr_estatus is None diff --git a/tests/test_prediction.py b/tests/test_prediction.py index 79a9e20..9d147b1 100644 --- a/tests/test_prediction.py +++ b/tests/test_prediction.py @@ -3,7 +3,6 @@ import json import pytest from models.base import ScreeningModel -from models.cohort import CohortBuilder, ExclusionCriterion from models.prediction import ApplicabilityRejected, Interpretability, PredictionService from models.registry import registry @@ -18,11 +17,8 @@ class StubModel(ScreeningModel): return {"label": "positivo", "confianza": 0.73} -class AlwaysRejectCohortBuilder(CohortBuilder): - domain = "cacu" - scenario = "tamizaje" - criteria_version = "v1" - criteria = [ExclusionCriterion(code="X", reason_code="siempre", predicate=lambda e: True, applicable_in_production=True)] +def never_applicable(row: dict) -> bool: + return False def _promote_a_version(production_ready): @@ -56,7 +52,7 @@ def test_predict_without_active_version_raises(governance_db, mlflow_tracking): 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", cohort_builder=AlwaysRejectCohortBuilder() + StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable ) prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1") @@ -69,9 +65,16 @@ def test_applicability_gate_can_reject_outright(production_ready): StubModel(), domain="cacu", scenario="tamizaje", - cohort_builder=AlwaysRejectCohortBuilder(), + 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") diff --git a/tests/test_registry.py b/tests/test_registry.py index 28bd352..dc36e00 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -1,5 +1,4 @@ import pytest - from core.governance.enums import ArtifactKind, Environment from models.registry import PromotionBlocked, registry @@ -42,15 +41,14 @@ def test_artifacts_are_logged_to_the_run(production_ready): assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"]) -def test_retire_and_lineage_and_compare(production_ready): +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["cohort_version"]["version_hash"] == "hash-v2" + 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" - diff = {row["metric"]: row for row in registry.compare(domain, scenario, first, second)["metrics"]} - assert diff["auc"]["delta"] == pytest.approx(0.05) and diff["brier"]["delta"] is None registry.retire(domain, scenario, second) assert registry.status(domain, scenario, second) == "retirada" with pytest.raises(ValueError): @@ -68,3 +66,9 @@ def test_invalid_onnx_checkpoint_is_rejected(production_ready): 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) diff --git a/tests/test_training.py b/tests/test_training.py index fe672c0..c4246d2 100644 --- a/tests/test_training.py +++ b/tests/test_training.py @@ -2,17 +2,19 @@ import pytest from core.governance.enums import ArtifactKind, Environment from models.registry import registry +from mlflow import MlflowException + from models.training import ReadOnlyRepository, TrainingRun -def test_prod_run_requires_cohort_version_id(): - with pytest.raises(ValueError, match="cohort_version_id"): +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_cohort_version_id(mlflow_tracking): +def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking): run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) - assert run.cohort_version_id is None + assert run.cohorte_armado_id is None def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path): @@ -49,3 +51,33 @@ def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking): 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)