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.
This commit is contained in:
2026-11-22 20:34:38 -06:00
parent e0967d0175
commit 2fe4101982
4 changed files with 59 additions and 67 deletions
+18 -14
View File
@@ -13,34 +13,38 @@ from webapi.recomputation import RecomputationQueue
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
def test_only_cacu_has_a_live_estimator():
"""With no version in the registry, CaMa's cycle estimates nothing, and TEA never has a live estimator. Fails if a
domain without a production model gets an estimator that would then fail resolving a version."""
def test_with_an_empty_registry_no_domain_has_a_live_estimator():
"""With no version in the registry, neither CaMa's nor TEA's cycle estimates anything. Fails if a domain without
a production model gets an estimator that would then fail resolving a version."""
assert estimators.live_estimators("cama") == {}
assert estimators.live_estimators("tea") == {}
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
Fails if `live_estimators` stops catching the registry's `LookupError`."""
Fails if `live_estimators` offers a scenario the registry does not list as in production."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
monkeypatch.setattr(registry, "in_production", lambda domain: [])
assert estimators.live_estimators("cacu") == {}
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
def test_every_scenario_in_production_scores_its_cohort(monkeypatch):
"""Each scenario the registry has in production gets an estimator on the cohort its `model.toml` names, so two
scenarios on one cohort give that cohort two estimators; a registered name with no scenario in `models` is
skipped. An estimator reports nothing until it has estimated. Fails if the scenarios go back to a fixed list,
if one cohort keeps a single estimator, or if an unknown registered name breaks the cycle."""
from models.dags.training import Scenario
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
monkeypatch.setattr(registry, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
live = estimators.live_estimators("cacu")
assert list(live) == [URL]
estimator = live[URL]
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
cohort = Scenario.load("cacu", "cin2_pim").cohort
assert Scenario.load("cacu", "cancer_pim").cohort == cohort
assert list(live) == [cohort]
assert [e.scenario for e in live[cohort]] == ["cancer_pim", "cin2_pim"]
with pytest.raises(RuntimeError):
estimator.procedencia()
live[cohort][0].procedencia()
@pytest.mark.parametrize("proyecto", ["cacu"])
@@ -48,7 +52,7 @@ def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monk
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
as anything but `preliminary`."""
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: [EstimadorFijo()]})
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
assert result["estado"] == "ok", result
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
+18 -4
View File
@@ -56,7 +56,7 @@ def cuenta(base, sql):
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]
(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
@@ -68,16 +68,30 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
@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]
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
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]
(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"])
+12 -11
View File
@@ -203,20 +203,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
@config.when(with_cohorts=True)
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]:
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden
`confirm-risks`, no este paso.
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
estimadores = ctx.estimators.get(url) or []
if not estimadores:
continue
def frame(sesion, url=url):
@@ -226,8 +226,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
if armado_id is None:
continue
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
lotes[url] = []
for estimador in estimadores:
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
return lotes
+11 -38
View File
@@ -1,5 +1,5 @@
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version
of its domain in production, one batch per model.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
@@ -11,7 +11,6 @@ unused by design.
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
@@ -61,45 +60,19 @@ class ScenarioEstimator:
return self._provenance
class Cin2LogisticEstimator(ScenarioEstimator):
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`)."""
def __init__(self, domain: str = "cacu", version: str | None = None):
super().__init__(domain, "cin2_logistic", version)
self.desenlace = "cin2_mas"
# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production
# scores the cohort it names.
LIVE_SCENARIOS = {"cama": ("survival",)}
def _scenario_estimators(domain: str) -> dict[str, Any]:
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
configured: `estimate` then does nothing."""
from models.dags.training import Scenario
from models.io.registry import registry
found = {}
for name in LIVE_SCENARIOS.get(domain, ()):
scenario = Scenario.load(domain, name)
found: dict[str, list[ScenarioEstimator]] = {}
for name in registry.in_production(domain):
try:
registry.resolve(domain, name)
scenario = Scenario.load(domain, name)
except LookupError:
continue
found[scenario.cohort] = ScenarioEstimator(domain, name)
found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name))
return found
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return _scenario_estimators(domain)
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {scenario.cohort: Cin2LogisticEstimator(domain)}