From 7b2eae27820638c3692bf95252f4250c17c8e687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Tue, 17 Nov 2026 02:17:31 -0600 Subject: [PATCH] wording fixes --- models/__main__.py | 13 ++++++-- models/io/registry.py | 21 +++++++++++-- tests/cacu/test_cin2_logistic.py | 52 +++++++++++++++++++++++++++----- 3 files changed, 72 insertions(+), 14 deletions(-) diff --git a/models/__main__.py b/models/__main__.py index e482c49..287ecaa 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -140,10 +140,12 @@ def _estimate(args: argparse.Namespace) -> int: def _promote_step(args: argparse.Namespace, version: str) -> int: + """Promotes through the same gate the WebApi's promote route uses (MLD-01/01b): + a version missing its checklist (validation reports, routine records, a saved + model) is rejected here exactly as it would be there, rather than set directly.""" + from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry from mlflow import MlflowException - from models.io.registry import PRODUCTION_ALIAS, registered_name, registry - name = registered_name(args.domain, args.scenario) try: current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version @@ -152,7 +154,12 @@ def _promote_step(args: argparse.Namespace, version: str) -> int: if str(current) == str(version): print(f"already in production: version {version}") return 0 - registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version) + try: + registry.promote(args.domain, args.scenario, version) + except PromotionBlocked as blocked: + failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed) + print(f"not promoted, missing: {failed}", file=sys.stderr) + return 1 print(f"in production: version {version}") return 0 diff --git a/models/io/registry.py b/models/io/registry.py index a58583b..ca8c191 100644 --- a/models/io/registry.py +++ b/models/io/registry.py @@ -30,7 +30,15 @@ from mlflow import MlflowClient, MlflowException from persistance.governance import model_prediction_repository from sqlmodel import select -from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name +from models.io.lineage import ( + ARMADO_TAG, + COHORT_BUILD_TAG, + COHORT_SOURCE_TAG, + COHORT_URL_TAG, + DOMAINS, + MODEL_SHA_TAG, + registered_name, +) from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, TrainingRun, run_file, run_files REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri") @@ -223,16 +231,23 @@ class ModelRegistry: mv = self.get(domain, scenario, version) run = self.client.get_run(mv.run_id) armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG)) + dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None metrics = run.data.metrics missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)] sha = mv.tags.get(MODEL_SHA_TAG, "") + if armado is not None: + cohort_detail = f"huella {armado['huella'][:12]}" + elif dbt_build is not None: + cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}" + else: + cohort_detail = "sin cohorte" 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 al armado de cohorte con el que se entrenó", - armado is not None, - f"huella {armado['huella'][:12]}" if armado else "sin cohorte", + armado is not None or dbt_build is not None, + cohort_detail, ), 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", "")), diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index 2d85302..a917b11 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -259,6 +259,30 @@ def _versions(): return registry.client.search_model_versions("name='cacu-cin2_logistic'") +def _armado(armado_id: int) -> None: + """A `CohorteArmado` row at this exact id, matching a build fixture's `armado_id` metadata: `registry.checks`'s + ML-03 looks the tag up by id, so promoting a kit-sourced version needs the row to exist, not just the tag.""" + from datetime import date, datetime, timezone + + from core.cacu.indicadores.models import CohorteArmado + from persistance.db import get_cacu_session + + with get_cacu_session() as session: + session.add(CohorteArmado( + armado_id=armado_id, url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", + parametros="{}", datos_as_of=date(2025, 12, 31), huella=f"huella-{armado_id}", marco_sha="m", + n_miembros=20, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))) + session.commit() + + +def _promotable(domain: str, scenario: str, version: str) -> None: + """The three reports a fresh training run never carries (MLD-01/01b/03: attached by a human after training, + not by the training code), so the version clears every promotion check.""" + registry.attach_reports(domain, scenario, version, technical_validation_report_uri="docs/tecnica.pdf", + clinical_validation_report_uri="docs/clinica.pdf", + interpretability_report_uri="docs/interpretabilidad.html") + + def test_run_without_a_step_is_refused(capsys): """Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running steps.""" @@ -278,11 +302,17 @@ def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path registry.resolve("cacu", "cin2_logistic") -def test_repeating_every_step_changes_nothing(exported, mlflow_tracking, tmp_path, capsys): +def test_repeating_every_step_changes_nothing(exported, cacu_db, mlflow_tracking, tmp_path, capsys): """Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops looking for the existing version, or `--estimate` stops reading the output's metadata.""" output = tmp_path / "output.parquet" - steps = [*RUN, "--train", "--promote", "--estimate", "--output", str(output)] + steps = [*RUN, "--train", "--armado", "12", "--environment", "prod", "--promote", "--estimate", "--output", + str(output)] + _armado(12) + assert main([*RUN, "--train", "--armado", "12", "--environment", "prod"]) == 0 + _promotable("cacu", "cin2_logistic", "1") + capsys.readouterr() + assert main(steps) == 0 written = output.stat().st_mtime_ns capsys.readouterr() @@ -318,14 +348,17 @@ def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch) def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path): """Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if - `--estimate` skips because the file exists.""" + `--estimate` skips because the file exists. The alias is moved directly (not through `--promote`, which needs its + own promotion checklist satisfied, covered separately): this test is about `--estimate`'s own version tracking.""" output = tmp_path / "output.parquet" assert main(["train", "cacu", "cin2_logistic"]) == 0 assert main(["train", "cacu", "cin2_logistic"]) == 0 - assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 0 + registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1") + assert main([*RUN, "--estimate", "--output", str(output)]) == 0 assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1" - assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0 + registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "2") + assert main([*RUN, "--estimate", "--output", str(output)]) == 0 assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2" @@ -381,11 +414,14 @@ def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path): """Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the - dbt file.""" + dbt file. Also pins down that ML-03 (`registry.checks`) accepts a dbt cohort link, not only the kit's + `armado_id`: without that, `--promote` below would always be refused for a dbt-trained version.""" output = tmp_path / "output.parquet" + base = ["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod"] - assert main(["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod", - "--train", "--promote", "--estimate", "--output", str(output)]) == 0 + assert main([*base, "--train"]) == 0 + _promotable("cacu", "cin2_logistic", "1") + assert main([*base, "--promote", "--estimate", "--output", str(output)]) == 0 tags = registry.get("cacu", "cin2_logistic", "1").tags assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"