Files
WebApi/tests/test_orquestacion_riesgos.py
edgar 2fe4101982 Cycle: estimate with every scenario in production, one batch per model
The scenarios come from the registry instead of a fixed list, and a cohort can carry several estimators.
2026-11-22 20:34:38 -06:00

112 lines
4.3 KiB
Python

"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba.
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
"""
from dataclasses import dataclass
import pytest
from sqlalchemy import text
from webapi.orchestration.__main__ import confirm_risks, main
URL = "cacu/cohorte_vigilancia"
@dataclass(frozen=True)
class Procedencia:
modelo_nombre: str = "prueba"
modelo_version: str = "1"
mlflow_run_id: str = "sin-mlflow"
modelo_sha: str = "sha-de-prueba"
def como_dict(self):
return dict(self.__dict__)
class EstimadorFijo:
"""Cumple el contrato: un riesgo por miembro, `probabilidad` (0.1) al `horizonte` (0)."""
desenlace = "cin2_mas"
def __init__(self, cohorte_url=URL, horizonte=0.0, probabilidad=0.1):
self.cohorte_url, self.horizonte, self.probabilidad = cohorte_url, horizonte, probabilidad
self.columnas = None
def procedencia(self):
return Procedencia()
def estimar(self, columnas, filas):
self.columnas = columnas
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
@pytest.fixture
def cacu(base):
base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True)
return base
def cuenta(base, sql):
with base.motor.connect() as con:
return con.execute(text(sql)).scalar_one()
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
estimador = EstimadorFijo()
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: [estimador]})["estimate"][URL][0]
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
assert nuevo and miembros > 0
assert estimador.columnas[:2] == ["pac_id", "fecha_indice"] # el marco ancho de `leer_marco`
assert cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") == miembros
assert cuenta(cacu, "SELECT COUNT(DISTINCT estado) FROM evaluacion_riesgo") == 1
assert cuenta(cacu, "SELECT MIN(estado) FROM evaluacion_riesgo") == "preliminary"
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
assert cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0] == (primero, False)
assert cacu.run("estimate")["estimate"] == {}
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_dos_modelos_de_una_cohorte_dejan_un_lote_cada_uno(cacu):
"""Two estimators on one cohort (two scenarios in production on the same build) write one batch each. Fails if
`estimate` keeps only one estimator per cohort or folds two models into one batch."""
class OtroModelo(EstimadorFijo):
def procedencia(self):
return Procedencia(modelo_nombre="cacu-otro")
lotes = cacu.run("estimate", estimators={URL: [EstimadorFijo(), OtroModelo()]})["estimate"][URL]
assert [nuevo for _, nuevo in lotes] == [True, True] and lotes[0][0] != lotes[1][0]
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 2
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
(lote_id, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
# Por proyecto: la cohorte, el horizonte de sus bandas y su resumen por banda. Desde T-21h solo CaCu arma
# su cohorte; las de TEA y CaMa son propuestas y su punta a punta está en `models` y en el kit.
DE_PUNTA_A_PUNTA = {
"cacu": (URL, 0.0, "cacu/CACU_RIESGO_BANDA"),
}