The cycle builds the cohorts dbt defines; models' moved modules

The `cohorts` and `estimate` steps take the project's cohorts from dbt's manifest (`cohort_urls`) and build each one
with models' `build_of` over dbt's queries, instead of the Python-frame TOMLs in models/cohorts, which are gone; without
a manifest a project has no cohort steps. The recruitment window and cut-off are dbt's vars. The live estimator reads
cin2_logistic through `Scenario` and `KitBuild`, and governance imports `models.reports.experiment`, where models now
keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-20 20:18:00 -06:00
parent c86c530703
commit 7d06f9db9d
8 changed files with 83 additions and 79 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
set -e
# The notebook runner shares the image but runs with no network, a read-only
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
if [ "$1" = "notebooks" ]; then
exec /app/WebApi/.venv/bin/python -m models notebooks serve
fi
+13 -6
View File
@@ -15,6 +15,7 @@ from sqlalchemy import create_engine, text
from sqlmodel import Session
from webapi.orchestration import Context, run
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.connection import point_to
ANIO = 2025
@@ -65,16 +66,22 @@ def test_volver_a_correr_no_agrega_reportes(bases):
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
def test_en_cacu_arma_su_cohorte_una_vez(bases):
def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases):
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from
anywhere else than dbt, or a build's count and members disagree."""
proyecto, ctx, motor, _, pasos = bases
if proyecto != "cacu":
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
assert "cohorts" not in [p.name for p in pasos]
return
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
for armado_id, _ in armados.values():
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
{"a": armado_id}).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
+14 -4
View File
@@ -1,5 +1,7 @@
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
import json
import pytest
from hamilton import driver
@@ -33,8 +35,16 @@ def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
assert {"load", "catalogs"} <= antes(deps, "check_silver")
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
definitions from anywhere else than dbt."""
manifest = tmp_path / "manifest.json"
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
for proyecto in ("cama", "tea"):
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
monkeypatch.delenv("DBT_MANIFEST", raising=False)
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
+2 -2
View File
@@ -8,7 +8,7 @@ either run elsewhere and register its result through `POST /model-versions`
`cohorte_armado_id`), or be triggered in place through `POST
/model-versions/<domain>/<scenario>/train`, for a deployment with no
command-line access to run the `entrenar` compose profile by hand.
Notebooks (`models.pipelines.experiment`) run in the background on the build's
Notebooks (`models.reports.experiment`) run in the background on the build's
file alone and are kept as MLflow runs.
"""
import contextlib
@@ -28,7 +28,7 @@ from models.io.lineage import DOMAINS
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
from models.io.storage import build_file, cohorts_root, exported_builds
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
from models.pipelines import experiment
from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
+17 -33
View File
@@ -37,13 +37,13 @@ from webapi.orchestration.reference.rules import (
from webapi.orchestration.reference.periods import periodos_de_tipos
from webapi.orchestration.tables import tablas_de
from persistance.edges.silver import save_load_in
from sqlmodel import SQLModel, func, select
from sqlmodel import SQLModel, select
from webapi.orchestration.context import Context
from webapi.orchestration.semantic_layer import catalog_layers, event_views
from models.cohorts.build import build_of, latest_build, read_frame
from models.cohorts.definition import read_definition
from webapi.orchestration.project import cohort_definitions, period_types
from models.io.storage import read_queries
from webapi.orchestration.project import cohort_urls, period_types
log = logging.getLogger(__name__)
@@ -188,23 +188,17 @@ def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict
@config.when(with_cohorts=True)
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
"""Arma cada cohorte del proyecto con las reglas de dbt, su única definición: la población, la fecha índice, las
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
corte (las variables de dbt), y corren en la base después de `event_models`.
"""
tablas = tablas_de(ctx.project)
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
def armado(definicion, sesion):
corte = ctx.cutoff or _last_load_date(sesion, tablas)
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
linea=ctx.repos.silver.timeline.query)
manifest = _manifest(ctx)
armados = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
for url in cohort_urls(ctx.project, manifest):
consultas = read_queries(manifest, url)
armados[url] = ctx.repos.gold.cohorts.assemble(
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
return armados
@@ -220,30 +214,20 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
estimador = ctx.estimators.get(definicion.url)
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
continue
def frame(sesion, definicion=definicion):
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
cohortes=tablas_cohorte)
def frame(sesion, url=url):
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
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[definicion.url] = ctx.repos.gold.cohorts.save_batch(
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
return lotes
def _last_load_date(sesion, tablas) -> date | None:
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
if ultima is None or isinstance(ultima, date):
return ultima.date() if isinstance(ultima, datetime) else ultima
return date.fromisoformat(str(ultima)[:10])
+23 -21
View File
@@ -3,9 +3,9 @@ its domain has in production.
`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
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`):
the cycle's latest build for membership, the domain's timeline for the events, then the production version in
MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go
unused by design.
"""
@@ -37,28 +37,29 @@ class Cin2LogisticEstimator:
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import mlflow.pyfunc
from persistance.settings import settings
import json
from models.cacu.cin2_logistic.model import SETTINGS
import mlflow.pyfunc
import numpy as np
from models.dags.estimation import estimate_frame
from models.dags.training import Scenario
from models.io.registry import registered_name, registry
from models.io.storage import cohorts_root, read_cohort
from models.pipelines.export_cohort import export_kit_build
from models.io.storage import KitBuild
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
url = SETTINGS["cohort"]
build_id = repos.cohort_repository.latest_build(url)
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
window = SETTINGS["outcome_window_months"]
self.desenlace = f"cin2_{window}m"
scenario = Scenario.load(self.domain, "cin2_logistic")
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
self.desenlace = scenario.outcome
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(risks, window / 12)]
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
def procedencia(self) -> Provenance:
if self._provenance is None:
@@ -71,11 +72,12 @@ def live_estimators(domain: str) -> dict[str, Any]:
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.cacu.cin2_logistic.model import SETTINGS
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, SETTINGS["scenario"])
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
+6 -6
View File
@@ -1,9 +1,9 @@
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
"""What the cycle needs to know of a project's definitions, all from dbt's manifest: its period types and its cohorts."""
import json
from pathlib import Path
from models.cohorts.definition import ROOT
from models.io.storage import cohort_urls as _cohort_urls
def period_types(proyecto: str, manifest: Path) -> list[str]:
@@ -13,7 +13,7 @@ def period_types(proyecto: str, manifest: Path) -> list[str]:
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
def cohort_definitions(proyecto: str) -> list[Path]:
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
Those in `<project>/proposals/` aren't built."""
return sorted((ROOT / proyecto).glob("*.toml"))
def cohort_urls(proyecto: str, manifest: Path | None) -> list[str]:
"""The cohorts the cycle builds: those of the project in dbt's manifest (`Transformation/models/<project>/cohorts/`,
`meta.cohort` of their population query). dbt is their only definition. None without a manifest."""
return _cohort_urls(manifest, proyecto) if manifest else []
+7 -6
View File
@@ -18,7 +18,8 @@ from hamilton.lifecycle import NodeExecutionHook
from webapi.orchestration import cycle
from webapi.orchestration.context import Context
from webapi.orchestration.project import cohort_definitions
from webapi.orchestration.context import dbt_manifest_path
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.repositories import repositories_of
log = logging.getLogger(__name__)
@@ -49,10 +50,10 @@ class _Logbook(NodeExecutionHook):
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
def _driver(proyecto: str, manifest, *adaptadores) -> driver.Driver:
return (driver.Builder()
.with_modules(cycle)
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
.with_adapters(*adaptadores)
.build())
@@ -61,9 +62,9 @@ def _in_order(dr: driver.Driver) -> list[str]:
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
def steps_of(proyecto: str) -> list[str]:
def steps_of(proyecto: str, manifest=None) -> list[str]:
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
return _in_order(_driver(proyecto))
return _in_order(_driver(proyecto, manifest or dbt_manifest_path()))
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
@@ -75,7 +76,7 @@ def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
if ctx.repos is None:
ctx = replace(ctx, repos=repositories_of(ctx.project))
bitacora = _Logbook()
dr = _driver(ctx.project, bitacora)
dr = _driver(ctx.project, ctx.dbt_manifest, bitacora)
todos = _in_order(dr)
pedidos = [p for p in todos if only is None or p in only]
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})