199 lines
9.2 KiB
Python
199 lines
9.2 KiB
Python
"""What this module covers: `models.io.adapters` and the generic driver of `models.dags.training`: the loaders feed the
|
|
graph from any cohort source, the saver logs, registers and describes a version from `fitted_model` and `metrics`, the
|
|
registered model runs without this repository, metrics that aren't numbers fail the run and register nothing, and a
|
|
failing node's inputs never reach the log.
|
|
|
|
Fixtures: `scenario`, a throwaway scenario package (`model.py`, `model.toml`) under `tmp_path`, whose model gives every
|
|
member the same risk at two horizons; `cohort_file`, kit build 5's file with members 987654301 to 987654303;
|
|
`mlflow_tracking` and `predict_without_repository` (conftest).
|
|
"""
|
|
|
|
import importlib
|
|
import logging
|
|
import sys
|
|
import textwrap
|
|
from datetime import date, datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
import pyarrow.parquet as pq
|
|
import pytest
|
|
from hamilton import ad_hoc_utils, driver
|
|
from hamilton.io.materialization import from_
|
|
from mlflow.entities import RunStatus
|
|
|
|
from models.dags import training
|
|
from models.io.contracts import COHORT_SCHEMA
|
|
from models.io.registry import registry
|
|
from models.io.storage import CohortFile
|
|
|
|
MEMBERS = (987654301, 987654302, 987654303)
|
|
|
|
SCENARIO_TOML = """
|
|
domain = "cacu"
|
|
scenario = "fake_scenario"
|
|
cohort = "cacu/cohorte_vigilancia"
|
|
outcome = "fake"
|
|
modules = ["fake_scenario_pkg.model"]
|
|
requirements = ["scikit-learn", "numpy"]
|
|
description = "A scenario for tests."
|
|
|
|
[config]
|
|
risk = 0.25
|
|
horizons_years = [0.0, 2.0]
|
|
"""
|
|
|
|
SCENARIO_MODEL = '''
|
|
import numpy as np
|
|
import pandas as pd
|
|
from sklearn.base import BaseEstimator
|
|
|
|
|
|
def member_count(cohort: pd.DataFrame) -> int:
|
|
return int(cohort["pac_id"].nunique())
|
|
|
|
|
|
def metrics(member_count: int, risk: float) -> dict:
|
|
return {"n_members": member_count, "risk": risk}
|
|
|
|
|
|
class ConstantRisk(BaseEstimator):
|
|
def __init__(self, risk=0.25, horizons_years=(0.0, 2.0)):
|
|
self.risk, self.horizons_years = risk, horizons_years
|
|
|
|
def fit(self, X, y=None):
|
|
return self
|
|
|
|
def predict_proba(self, X):
|
|
return np.full((X["pac_id"].nunique(), len(self.horizons_years)), float(self.risk))
|
|
|
|
|
|
def fitted_model(risk: float, horizons_years: list) -> ConstantRisk:
|
|
return ConstantRisk(risk, horizons_years)
|
|
'''
|
|
|
|
|
|
def _write_scenario(root, model_source=SCENARIO_MODEL):
|
|
package = root / "fake_scenario_pkg"
|
|
package.mkdir(exist_ok=True)
|
|
(package / "__init__.py").write_text("")
|
|
(package / "model.py").write_text(textwrap.dedent(model_source))
|
|
(package / "model.toml").write_text(SCENARIO_TOML)
|
|
for name in ("fake_scenario_pkg.model", "fake_scenario_pkg"):
|
|
sys.modules.pop(name, None)
|
|
importlib.invalidate_caches()
|
|
return training.Scenario.from_toml(package / "model.toml")
|
|
|
|
|
|
@pytest.fixture
|
|
def scenario(tmp_path, monkeypatch):
|
|
"""The throwaway scenario, its module importable as `fake_scenario_pkg.model`."""
|
|
monkeypatch.syspath_prepend(str(tmp_path))
|
|
return _write_scenario(tmp_path)
|
|
|
|
|
|
@pytest.fixture
|
|
def cohort_file(tmp_path):
|
|
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, day), "fecha": date(2025, 1, day),
|
|
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
|
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "t",
|
|
"fuente_id": str(pac_id)} for day, pac_id in enumerate(MEMBERS, start=1)]
|
|
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA,
|
|
preserve_index=False)
|
|
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": "2026-12-31", "armado_id": "5"}
|
|
path = tmp_path / "5.parquet"
|
|
pq.write_table(table.replace_schema_metadata(lineage), path)
|
|
return path
|
|
|
|
|
|
def test_the_loaders_feed_the_graph_from_a_source(cohort_file):
|
|
"""Pins down: `cohort_source` and `cohort_source_lineage` give the nodes the build's frame and its lineage, from the
|
|
source they're given. Fails if a loader's name changes or it stops asking its source."""
|
|
def members(cohort: pd.DataFrame) -> int:
|
|
return len(cohort)
|
|
|
|
def build_number(cohort_lineage: dict) -> str:
|
|
return cohort_lineage["armado_id"]
|
|
|
|
module = ad_hoc_utils.create_temporary_module(members, build_number)
|
|
dr = driver.Builder().with_modules(module).with_materializers(
|
|
from_.cohort_source(target="cohort", source=CohortFile(cohort_file)),
|
|
from_.cohort_source_lineage(target="cohort_lineage", source=CohortFile(cohort_file))).build()
|
|
|
|
assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"}
|
|
|
|
|
|
def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scenario, cohort_file, mlflow_tracking):
|
|
"""Pins down: the saver logs the fitted model, records the metrics, the config and the `models` version, registers
|
|
the version with its build and describes it. Fails if the saver stops being reached from `registered_model`, or
|
|
drops any of those."""
|
|
version = training.train(scenario, CohortFile(cohort_file))
|
|
|
|
stored = registry.get("cacu", "fake_scenario", version)
|
|
run = registry.client.get_run(stored.run_id)
|
|
assert stored.description == "A scenario for tests." and stored.tags["kit.armado_id"] == "5"
|
|
assert run.data.metrics == {"n_members": 3.0, "risk": 0.25}
|
|
assert run.data.params["risk"] == "0.25" and "models.version" in run.data.params
|
|
assert run.info.status == RunStatus.to_string(RunStatus.FINISHED)
|
|
assert training.find_trained(scenario, CohortFile(cohort_file)) == version
|
|
|
|
|
|
def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking,
|
|
predict_without_repository):
|
|
"""Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the
|
|
scenario still loads the version and gives a probability per member and horizon. Fails if the model's classes go
|
|
back to being pickled by reference."""
|
|
version = training.train(scenario, CohortFile(cohort_file))
|
|
|
|
output = predict_without_repository(registry.resolve("cacu", "fake_scenario", version).model_uri,
|
|
pd.read_parquet(cohort_file))
|
|
|
|
assert output.shape == (3, 2) and (output == 0.25).all().all()
|
|
|
|
|
|
def test_metrics_that_are_not_numbers_fail_the_run_and_register_nothing(tmp_path, monkeypatch, cohort_file,
|
|
mlflow_tracking):
|
|
"""Pins down: a `metrics` value that isn't a number (a frame put there by mistake) stops the saver before MLflow
|
|
receives it, marks the run failed and registers no version. Fails if the check goes, or a failed graph leaves a
|
|
run open or a version behind."""
|
|
monkeypatch.syspath_prepend(str(tmp_path))
|
|
leaking = SCENARIO_MODEL.replace('return {"n_members": member_count, "risk": risk}',
|
|
'return {"n_members": member_count, "rows": pd.DataFrame({"pac_id": [1]})}')
|
|
scenario = _write_scenario(tmp_path, leaking)
|
|
|
|
with pytest.raises(TypeError, match="rows"):
|
|
training.train(scenario, CohortFile(cohort_file))
|
|
|
|
runs = registry.client.search_runs([e.experiment_id for e in registry.client.search_experiments()])
|
|
assert [r.info.status for r in runs] == [RunStatus.to_string(RunStatus.FAILED)]
|
|
assert not registry.client.search_model_versions("name='cacu-fake_scenario'")
|
|
|
|
|
|
def test_a_failing_node_does_not_log_its_inputs(tmp_path, monkeypatch, cohort_file, mlflow_tracking, caplog):
|
|
"""Pins down: when a node fails during training, the exception reaches the caller but Hamilton's log of the node's
|
|
inputs, which would show the first rows of the cohort, isn't written. Fails if the driver stops silencing
|
|
`hamilton.execution.graph_functions` or Hamilton moves that message to another logger."""
|
|
monkeypatch.syspath_prepend(str(tmp_path))
|
|
scenario = _write_scenario(tmp_path, SCENARIO_MODEL.replace('return int(cohort["pac_id"].nunique())',
|
|
'return int(cohort["missing"].sum())'))
|
|
|
|
with caplog.at_level(logging.DEBUG), pytest.raises(KeyError):
|
|
training.train(scenario, CohortFile(cohort_file))
|
|
|
|
assert not any(str(pac_id) in caplog.text for pac_id in MEMBERS)
|
|
|
|
|
|
def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohort_file, mlflow_tracking):
|
|
"""Pins down: the version's `requirements.txt` holds the scenario's `requirements`, each pinned to the installed
|
|
version, and no path or editable install of this repository. Fails if MLflow goes back to inferring them from the
|
|
environment, which copies the whole lock with `-e ../Persistance` and the like."""
|
|
import mlflow
|
|
from importlib.metadata import version as installed
|
|
|
|
run_id = registry.get("cacu", "fake_scenario", training.train(scenario, CohortFile(cohort_file))).run_id
|
|
lines = Path(mlflow.artifacts.download_artifacts(f"runs:/{run_id}/model/requirements.txt")).read_text().split()
|
|
|
|
assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines
|
|
assert not [line for line in lines if line.startswith("-e") or "/" in line]
|