"""What this module covers: the registry's promotion checks, promotion and retirement, the scenarios in production, the lineage of a version, and what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`). Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model; `governance_db`, `cacu_db` and `mlflow_tracking` (from `conftest.py`); `trained_run` and `armado` (from `conftest.py`) build runs missing a routine or the model. """ import io import json import zipfile import pytest from conftest import armado, trained_run from core.governance.enums import ArtifactKind, Environment from models.io.registry import PromotionBlocked, registry def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking): version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV) assert registry.status("cacu", "tamizaje", version) == "desarrollo" with pytest.raises(PromotionBlocked) as blocked: registry.promote("cacu", "tamizaje", version) failed = {check.code for check in blocked.value.checks if not check.passed} assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"} def test_promotion_retires_the_previous_version_of_the_scenario(production_ready): domain, scenario, first = production_ready("v1") _, _, second = production_ready("v2", metrics={"auc": 0.84}) assert registry.status(domain, scenario, first) == "candidata" registry.promote(domain, scenario, first) registry.promote(domain, scenario, second) assert registry.status(domain, scenario, first) == "retirada" assert registry.status(domain, scenario, second) == "produccion" other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico") registry.promote(other_domain, other_scenario, other_version) assert registry.status(domain, scenario, second) == "produccion" def test_reports_can_be_attached_after_training(production_ready): domain, scenario, version = production_ready("v1") registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None) assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf") assert all(c.passed for c in registry.checks(domain, scenario, version)) with pytest.raises(ValueError): registry.attach_reports(domain, scenario, version, metrics="{}") def test_lineage_lists_every_stored_file_and_each_routine_record(production_ready): """The lineage lists files inside folders (the saved model) and reads back each routine's record. Fails if `run_files` stops descending into folders or `routines` stops reading `rutinas/`.""" domain, scenario, version = production_ready("v1") lineage = registry.lineage(domain, scenario, version) paths = {item["path"] for item in lineage["artifacts"]} assert "model/MLmodel" in paths and "rutinas/MUESTREO.json" in paths assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8} def test_promotion_needs_the_model_the_training_run_itself_saved(governance_db, cacu_db, mlflow_tracking): """A run that saved no model is not promoted, whatever else is in order. Fails if the ML-01b check stops requiring `modelo_sha`.""" run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=None, model=False) version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c", interpretability_report_uri="i") failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed] assert [check.code for check in failed] == ["ML-01b"] @pytest.mark.parametrize("routines, recorded", [([], "0 de 5"), ([ArtifactKind.MUESTREO], "1 de 5 (MUESTREO)")]) def test_the_training_run_is_the_registered_routine_and_its_records_are_reported(governance_db, cacu_db, mlflow_tracking, routines, recorded): """ML-01a: the version's training run is the registered routine, so a model without some routine records (a prevalence-incidence mixture has no class balance) can still be promoted; the check reports which records the run holds. Fails if ML-01a goes back to requiring every kind in `ROUTINE_KINDS`, or stops reporting them.""" run = trained_run("cacu", "parcial", armado("huella-x"), {"auc": 0.8}, routines=routines, model=True) version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c", interpretability_report_uri="i") checks = {check.code: check for check in registry.checks("cacu", "parcial", version)} assert checks["ML-01a"].passed and recorded in checks["ML-01a"].detail assert all(check.passed for check in checks.values()) def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready): """ML-01b: a stored file comes back as itself; the model folder as a zip of its files. Fails if `run_file` stops zipping folders or starts accepting a path the run doesn't list.""" domain, scenario, version = production_ready("v1") name, data = registry.artifact(domain, scenario, version, "rutinas/MUESTREO.json") assert name == "MUESTREO.json" and json.loads(data)["n"] == 8 name, data = registry.artifact(domain, scenario, version, "model") assert name == "model.zip" and "model/MLmodel" in zipfile.ZipFile(io.BytesIO(data)).namelist() for wrong in ("../mlflow.db", "", "rutinas/OTRO.json"): with pytest.raises(LookupError): registry.artifact(domain, scenario, version, wrong) 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["cohorte_armado"]["huella"] == "huella-v2" assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"] assert lineage["model_version"]["status"] == "produccion" registry.retire(domain, scenario, second) assert registry.status(domain, scenario, second) == "retirada" with pytest.raises(ValueError): registry.retire(domain, scenario, second) def test_in_production_lists_the_scenarios_holding_the_alias(production_ready): """Only scenarios of the domain with a version in production are listed; a candidate or a retired one is not. Fails if `in_production` stops reading the `produccion` alias or leaks another domain's models.""" domain, scenario, version = production_ready("v1") production_ready("v1-dx", scenario="diagnostico") assert registry.in_production(domain) == [] registry.promote(domain, scenario, version) assert registry.in_production(domain) == [scenario] assert registry.in_production("cama") == [] registry.retire(domain, scenario, version) assert registry.in_production(domain) == [] @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)