342 lines
17 KiB
Python
342 lines
17 KiB
Python
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
|
|
split, that training on a build's file registers a version with its lineage, and the `models train` and
|
|
`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none.
|
|
|
|
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
|
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
|
|
SQLite-backed MLflow.
|
|
"""
|
|
|
|
from datetime import date, datetime, timedelta, timezone
|
|
|
|
import mlflow.pyfunc
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
import pyarrow.parquet as pq
|
|
import pytest
|
|
|
|
from models.__main__ import main
|
|
from models.cacu.cin2_logistic import model
|
|
from models.cacu.cin2_logistic.train import find_trained, train
|
|
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
|
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
|
|
from models.io.registry import PRODUCTION_ALIAS, registry
|
|
|
|
|
|
def _row(pac_id, index, days, valor, tipo="bethesda"):
|
|
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
|
|
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
|
|
"valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
|
"fuente_id": f"{pac_id}-{tipo}-{days}"}
|
|
|
|
|
|
@pytest.fixture
|
|
def cohort_frame():
|
|
"""Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row
|
|
each, which the outcome must ignore."""
|
|
rows = []
|
|
for pac_id in range(1, 21):
|
|
index = date(2025, 1, 1) + timedelta(days=pac_id)
|
|
rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")]
|
|
rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL"))
|
|
return pd.DataFrame(rows, columns=SCHEMA.names)
|
|
|
|
|
|
def _write(frame, path, armado_id):
|
|
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path)
|
|
return path
|
|
|
|
|
|
@pytest.fixture
|
|
def cohort_file(cohort_frame, tmp_path):
|
|
"""The frame as build 7's file."""
|
|
return _write(cohort_frame, tmp_path / "7.parquet", 7)
|
|
|
|
|
|
@pytest.fixture
|
|
def exported(cohort_frame, tmp_path, monkeypatch):
|
|
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
|
|
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
|
|
_write(cohort_frame, folder / "7.parquet", 7)
|
|
_write(cohort_frame, folder / "12.parquet", 12)
|
|
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
|
return folder
|
|
|
|
|
|
def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame):
|
|
"""Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when
|
|
`y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes."""
|
|
prepared = model.prepare(cohort_frame).set_index("pac_id")
|
|
|
|
assert len(prepared) == 20
|
|
assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30]
|
|
assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300]
|
|
|
|
|
|
def test_first_abnormal_result_sets_days_when_there_are_several():
|
|
"""Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails
|
|
if `days` takes the last abnormal result or the first row."""
|
|
index = date(2025, 1, 1)
|
|
frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")])
|
|
|
|
assert model.prepare(frame).loc[0, "days"] == 40
|
|
|
|
|
|
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
|
|
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
|
|
is random or follows another column."""
|
|
parts = model.split(model.prepare(cohort_frame))
|
|
|
|
assert (len(parts["train"]), len(parts["test"])) == (14, 6)
|
|
assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min()
|
|
|
|
|
|
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
|
|
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that
|
|
it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or
|
|
if the driver stops reaching `registered_model`."""
|
|
version = train(cohort_file)
|
|
|
|
resolved = registry.resolve("cacu", "cin2_logistic", version)
|
|
stored = registry.get("cacu", "cin2_logistic", version)
|
|
run = registry.client.get_run(stored.run_id).data
|
|
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
|
|
assert "sin significado clínico" in stored.description
|
|
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
|
|
assert len(run.params["cohort_sha256"]) == 64
|
|
|
|
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
|
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
|
|
|
|
|
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
|
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
|
|
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
|
|
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
|
|
|
assert "version 1" in capsys.readouterr().out
|
|
stored = registry.get("cacu", "cin2_logistic", "1")
|
|
assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV"
|
|
|
|
|
|
def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking):
|
|
"""Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option
|
|
is ignored."""
|
|
assert main(["train", "cacu", "cin2_logistic", "--armado", "7", "--environment", "prod"]) == 0
|
|
|
|
stored = registry.get("cacu", "cin2_logistic", "1")
|
|
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
|
|
|
|
|
|
def test_prod_without_a_build_is_refused(capsys):
|
|
"""Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls
|
|
back to the latest file."""
|
|
with pytest.raises(SystemExit) as stopped:
|
|
main(["train", "cacu", "cin2_logistic", "--environment", "prod"])
|
|
|
|
assert stopped.value.code == 2 and "--build" in capsys.readouterr().err
|
|
|
|
|
|
@pytest.mark.parametrize("arguments, message", [
|
|
(["cacu", "ninguno"], "no such model: cacu/ninguno"),
|
|
(["cacu", "cin2_logistic", "--armado", "99"], "export it"),
|
|
])
|
|
def test_what_is_missing_is_named(exported, arguments, message, capsys):
|
|
"""Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no
|
|
version. Fails if the command lets the import error through, or trains on another file."""
|
|
assert main(["train", *arguments]) == 1
|
|
assert message in capsys.readouterr().err
|
|
|
|
|
|
def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys):
|
|
"""Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per
|
|
member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest
|
|
version instead of the alias, or the output can't be matched to members."""
|
|
main(["train", "cacu", "cin2_logistic"])
|
|
main(["train", "cacu", "cin2_logistic"])
|
|
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
|
output = tmp_path / "risks" / "output.parquet"
|
|
|
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 0
|
|
|
|
assert "version 1" in capsys.readouterr().out
|
|
risks = pd.read_parquet(output)
|
|
assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"]
|
|
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
|
metadata = pq.read_metadata(output).metadata
|
|
assert metadata[b"modelo_version"] == b"1" and metadata[b"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit"
|
|
|
|
|
|
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
|
|
"""Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the
|
|
alias becomes mandatory."""
|
|
main(["train", "cacu", "cin2_logistic"])
|
|
output = tmp_path / "output.parquet"
|
|
|
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0
|
|
|
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
|
|
|
|
|
def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys):
|
|
"""Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes
|
|
nothing. Fails if it falls back to another version or lets the error through."""
|
|
main(["train", "cacu", "cin2_logistic"])
|
|
output = tmp_path / "output.parquet"
|
|
|
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1
|
|
|
|
assert "no version in production" in capsys.readouterr().err and not output.exists()
|
|
|
|
|
|
RUN = ["run", "cacu", "cin2_logistic"]
|
|
|
|
|
|
def _versions():
|
|
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
|
|
|
|
|
|
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."""
|
|
with pytest.raises(SystemExit) as stopped:
|
|
main(RUN)
|
|
|
|
assert stopped.value.code == 2 and "--export" in capsys.readouterr().err
|
|
|
|
|
|
def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path):
|
|
"""Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without
|
|
its option."""
|
|
assert main([*RUN, "--train"]) == 0
|
|
|
|
assert len(_versions()) == 1
|
|
with pytest.raises(LookupError):
|
|
registry.resolve("cacu", "cin2_logistic")
|
|
|
|
|
|
def test_repeating_every_step_changes_nothing(exported, 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)]
|
|
assert main(steps) == 0
|
|
written = output.stat().st_mtime_ns
|
|
capsys.readouterr()
|
|
|
|
assert main(steps) == 0
|
|
|
|
assert len(_versions()) == 1 and output.stat().st_mtime_ns == written
|
|
out = capsys.readouterr().out
|
|
assert "already trained" in out and "already in production" in out and "already estimated" in out
|
|
|
|
|
|
def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
|
|
"""Pins down: what says a training is the same is the file and the environment, so a build with other content or a
|
|
PROD run gets its own version. Fails if the check ignores either and reuses a version from something else."""
|
|
assert main([*RUN, "--train", "--armado", "7"]) == 0
|
|
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
|
|
frame = pd.read_parquet(exported / "12.parquet")
|
|
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12)
|
|
assert main([*RUN, "--train", "--armado", "12"]) == 0
|
|
|
|
assert len(_versions()) == 3
|
|
|
|
|
|
def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch):
|
|
"""Pins down: a version trained by other code isn't reused. Fails if the check stops comparing `code_sha256`."""
|
|
assert main([*RUN, "--train"]) == 0
|
|
assert find_trained(exported / "12.parquet") == "1"
|
|
|
|
monkeypatch.setattr(model, "code_sha256", lambda: "other")
|
|
|
|
assert find_trained(exported / "12.parquet") is None
|
|
|
|
|
|
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."""
|
|
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
|
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
|
|
|
assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0
|
|
|
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
|
|
|
|
|
|
def test_promote_needs_a_version(exported, mlflow_tracking, capsys):
|
|
"""Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias.
|
|
Fails if it promotes some other version."""
|
|
assert main([*RUN, "--promote"]) == 1
|
|
assert "use --train or --version" in capsys.readouterr().err
|
|
|
|
|
|
def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch):
|
|
"""Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if
|
|
the cohort or the build change, or training continues on a stale file."""
|
|
calls = []
|
|
|
|
def refuse(cohorts, read_timeline, root, domain, url, build_id=None):
|
|
calls.append((domain, url, build_id))
|
|
raise LookupError(f"no such build of {url}: {build_id}")
|
|
|
|
monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse)
|
|
|
|
assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1
|
|
|
|
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
|
|
assert not _versions()
|
|
|
|
|
|
@pytest.fixture
|
|
def dbt_exported(cohort_frame, tmp_path, monkeypatch):
|
|
"""Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1."""
|
|
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
|
|
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
|
|
path = folder / f"{number}.parquet"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
|
pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path)
|
|
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
|
return folder
|
|
|
|
|
|
def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys):
|
|
"""Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source,
|
|
number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is
|
|
ignored, or the version loses its cohort file."""
|
|
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt"]) == 0
|
|
|
|
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
|
assert ARMADO_TAG not in tags
|
|
assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia")
|
|
assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out
|
|
|
|
|
|
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."""
|
|
output = tmp_path / "output.parquet"
|
|
|
|
assert main(["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod",
|
|
"--train", "--promote", "--estimate", "--output", str(output)]) == 0
|
|
|
|
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
|
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
|
|
metadata = pq.read_metadata(output).metadata
|
|
assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1"
|
|
assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"]
|
|
|
|
|
|
def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys):
|
|
"""Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's
|
|
command is suggested or another build is used."""
|
|
assert main(["train", "cacu", "cin2_logistic", "--source", "dbt", "--build", "9"]) == 1
|
|
assert "--source dbt" in capsys.readouterr().err
|