Files
models/tests/test_store_risks.py
T

122 lines
6.1 KiB
Python

"""What this module covers: storing an estimate file as a batch of risks (`models.steps.risks`,
`models.io.storage.store_risk_batch`, `models.pipelines.store_risks`) and the `models store` command: one risk per
member at the model's horizon, the batch's MLflow keys, no duplicate batch, and builds without a `cohorte_armado` row
refused.
Fixtures: `cacu_db` (conftest), an empty CaCu schema on SQLite; `kit_build`, kit build 1 with members 1 to 3;
`estimate_file`, an estimate of those members with the metadata `models estimate` writes.
"""
from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from sqlmodel import select
from models.__main__ import main
from models.pipelines.store_risks import store_estimate
from models.steps.risks import risk_rows
METADATA = {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "3", "mlflow_run_id": "run-a", "modelo_sha": "sha-a",
"desenlace": "cin2_12m", "horizonte_anios": "1.0", "cohort.url": "cacu/cohorte_vigilancia",
"cohort.source": "kit", "cohort.build": "1", "cohort.file_sha256": "f" * 64}
def _estimate(pac_ids=(1, 2, 3)):
return pd.DataFrame({"pac_id": list(pac_ids), "fecha_indice": [date(2025, 1, i) for i in pac_ids],
"probabilidad": [0.1 * i for i in pac_ids]})
def _write(frame, path, **metadata):
table = pa.Table.from_pandas(frame, preserve_index=False)
pq.write_table(table.replace_schema_metadata({**table.schema.metadata, **METADATA, **metadata}), path)
return path
@pytest.fixture
def kit_build(cacu_db):
"""Kit build 1 of the surveillance cohort, with members 1, 2 and 3 (and their `persona` rows)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, Persona
from persistance.db import get_cacu_session
with get_cacu_session() as session:
session.add_all(Persona(pac_id=i, pac_id_hospital=f"H{i}") for i in (1, 2, 3))
session.add(CohorteArmado(armado_id=1, url="cacu/cohorte_vigilancia", version="1", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="h", marco_sha="m", n_miembros=3,
armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)))
session.add_all(CohorteMiembro(armado_id=1, pac_id=i, fecha_indice=date(2025, 1, i), indice_fuente_tabla="t",
indice_fuente_id=str(i)) for i in (1, 2, 3))
session.commit()
return 1
@pytest.fixture
def estimate_file(tmp_path):
return _write(_estimate(), tmp_path / "estimate.parquet")
def _stored():
from core.cacu.indicadores.models import EvaluacionRiesgo, EvaluacionRiesgoLote
from persistance.db import get_cacu_session
with get_cacu_session() as session:
return session.exec(select(EvaluacionRiesgoLote)).all(), session.exec(select(EvaluacionRiesgo)).all()
def test_each_member_becomes_one_risk_at_the_horizon():
"""Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member. Fails if the horizon is
dropped or the interval is filled with something the model didn't give."""
assert risk_rows(_estimate((1, 2)), 1.0) == [(1, 1.0, 0.1, None, None), (2, 1.0, 0.2, None, None)]
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),
_estimate().rename(columns={"probabilidad": "p"})])
def test_a_malformed_estimate_stops_the_batch(frame):
"""Pins down: a member scored twice, a probability outside 0..1, or other columns stop the batch before anything is
written. Fails if any of them reaches the database."""
with pytest.raises(ValueError):
risk_rows(frame, 1.0)
def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_file):
"""Pins down: the batch points to the kit build and to the MLflow version and run, holds the outcome, and its risks
are preliminary version 1 at the horizon. Fails if a key is lost or a risk is stored at another horizon."""
batch, written = store_estimate(estimate_file, "cacu")
batches, risks = _stored()
assert written and [b.lote_id for b in batches] == [batch]
assert (batches[0].armado_id, batches[0].modelo_version, batches[0].mlflow_run_id, batches[0].desenlace) == (1, "3", "run-a", "cin2_12m")
assert sorted((r.pac_id, r.horizonte_anios, r.estado, r.version) for r in risks) == [
(1, 1.0, "preliminary", 1), (2, 1.0, "preliminary", 1), (3, 1.0, "preliminary", 1)]
def test_storing_the_same_estimate_again_adds_nothing(kit_build, estimate_file, capsys):
"""Pins down: the command is idempotent: the second time it reports the existing batch. Fails if Persistance's
content check stops matching what this module sends."""
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert "already stored: batch 1" in capsys.readouterr().out
assert len(_stored()[0]) == 1
def test_a_dbt_build_has_no_batch_to_point_to(kit_build, tmp_path, capsys):
"""Pins down: an estimate of a dbt build is refused with the reason, since a batch needs a `cohorte_armado` row.
Fails if a dbt build's number is taken for a kit `armado_id`, which would point the batch to another build."""
path = _write(_estimate(), tmp_path / "dbt.parquet", **{"cohort.source": "dbt"})
assert main(["store", "cacu", "cin2_logistic", "--input", str(path)]) == 1
assert "cohorte_armado" in capsys.readouterr().err and not _stored()[0]
def test_an_estimate_without_its_keys_is_refused(kit_build, tmp_path):
"""Pins down: a file without the version's keys (a hand-made one, or one from an older `estimate`) isn't stored.
Fails if a batch could be written without knowing which model produced it."""
path = tmp_path / "bare.parquet"
pq.write_table(pa.Table.from_pandas(_estimate(), preserve_index=False), path)
with pytest.raises(ValueError, match="lacks"):
store_estimate(path, "cacu")