From bc15cc3e0491db5a8b072b0427d30b630bcc8481 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 20:19:03 +0000 Subject: [PATCH] dags: reading nodes for a cohort build, its members and their timeline The timeline is cut at the build's clinical and load cut-offs, so the read can be repeated. Adds apache-hamilton. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + models/dags/__init__.py | 1 + models/dags/reading.py | 44 ++++++++++ pyproject.toml | 2 + tests/test_reading_nodes.py | 169 ++++++++++++++++++++++++++++++++++++ 5 files changed, 217 insertions(+) create mode 100644 models/dags/__init__.py create mode 100644 models/dags/reading.py create mode 100644 tests/test_reading_nodes.py diff --git a/README.md b/README.md index e411dcf..f907652 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ WebApi. | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | | `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. | +| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` y `conocida_hasta` del armado). Los repositorios entran como insumos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | diff --git a/models/dags/__init__.py b/models/dags/__init__.py new file mode 100644 index 0000000..2d7d505 --- /dev/null +++ b/models/dags/__init__.py @@ -0,0 +1 @@ +"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge.""" diff --git a/models/dags/reading.py b/models/dags/reading.py new file mode 100644 index 0000000..63f5777 --- /dev/null +++ b/models/dags/reading.py @@ -0,0 +1,44 @@ +"""The nodes every model DAG reads through: a cohort build, its members and their timeline. + +Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows +which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories +are inputs too: whoever builds the driver passes a domain's `cohorte_repository` and a +`timeline_repository` already bound to its query. + +The timeline is cut at the build's clinical date (`datos_as_of`) and at what had been loaded when the +build was made (`conocida_hasta`), so reading it again gives the build's input. +""" + +from dataclasses import fields + +import pandas as pd +from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset + +MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember)) + + +class UnknownBuild(LookupError): + """The requested cohort build doesn't exist.""" + + +def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, build_id: int) -> CohortBuild: + """The build's lineage: cohort, version, fingerprints and cut-offs.""" + build = cohort_repository.build(build_id) + if build is None: + raise UnknownBuild(f"cohort build {build_id} doesn't exist") + return build + + +def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort_build: CohortBuild) -> pd.DataFrame: + """One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`.""" + return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS)) + + +def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, + timeline_repository: TimelineRepository) -> pd.DataFrame: + """The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and `conocida_hasta`.""" + rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of, + known_until=cohort_build.conocida_hasta) + return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)) diff --git a/pyproject.toml b/pyproject.toml index 52bb574..d054073 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,8 @@ dependencies = [ "persistance", "extraction", "mlflow>=2.9", + # The model DAGs (`models/dags`): each function a node, each parameter an edge. + "apache-hamilton>=1.90", ] [project.optional-dependencies] diff --git a/tests/test_reading_nodes.py b/tests/test_reading_nodes.py new file mode 100644 index 0000000..6dbb707 --- /dev/null +++ b/tests/test_reading_nodes.py @@ -0,0 +1,169 @@ +"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `timeline`) +run by a Hamilton driver built from that module alone, and their place in the asset graph. + +Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain +`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to +`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and +executes the requested nodes. +""" + +import json +from datetime import date, datetime, timezone + +import pytest +from core.cacu.base import CaCuModel +from core.cacu.indicadores.models import ( + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, +) +from core.indicadores.cohortes import TablasCohorte +from hamilton import driver +from persistance.aristas.oro import CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset, InvalidGraph, validate +from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, create_engine + +from models.dags import reading + +TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, + EvaluacionRiesgo) +ASSETS = {name: Asset(name) for name in ("cohorte_armado", "cohorte_miembro", "linea_de_tiempo")} + +metadata = MetaData() +events = Table( + "timeline_events", metadata, + Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime), + Column("clase", String), Column("tipo", String), Column("codigo", String), + Column("valor_codigo", String), Column("valor_numerico", Float), + Column("fuente_tabla", String), Column("fuente_id", String), +) + + +def _event(pac_id, fecha, conocida_en, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "procedimiento", + "tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "NORMAL", "valor_numerico": None, + "fuente_tabla": "citologiacervical", "fuente_id": fuente_id} + + +EVENTS = [ + _event(10, date(2025, 2, 1), datetime(2025, 2, 2), "kept-10"), + _event(20, date(2025, 3, 1), datetime(2025, 3, 2), "kept-20"), + _event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"), + _event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"), + _event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"), +] + + +def timeline_query(*, patients, until, known_until): + """Stands in for the kit's query: same columns and filters, over `timeline_events`.""" + query = select(*(events.c[name] for name in TIMELINE_COLUMNS)).order_by(events.c.pac_id, events.c.fecha) + if patients is not None: + query = query.where(events.c.pac_id.in_(patients)) + if until is not None: + query = query.where(events.c.fecha <= until) + if known_until is not None: + query = query.where(events.c.conocida_en <= known_until.replace(tzinfo=None)) + return query + + +@pytest.fixture +def repositories(): + """Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00 + UTC, members 20 and 10 (inserted in that order). Build 2 exists with no members. `EVENTS` has one + event per member inside both cut-offs, one past the clinical cut-off, one loaded after the build and + one of a patient outside the cohort. + """ + engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False}) + CaCuModel.metadata.create_all(engine) + metadata.create_all(engine) + parameters = json.dumps({"corte": "2025-12-31", "conocida_hasta": "2026-01-02T08:00:00+00:00"}) + with Session(engine) as session: + session.add_all([ + CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", + reglas_sha="r", parametros=parameters, datos_as_of=date(2025, 12, 31), + huella=f"h{armado_id}", marco_sha=f"m{armado_id}", n_miembros=2 if armado_id == 1 else 0, + armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + for armado_id in (1, 2) + ]) + session.add_all([ + CohorteMiembro(armado_id=1, pac_id=pac_id, fecha_indice=fecha, indice_fuente_tabla="citologiacervical", + indice_fuente_id=str(pac_id)) + for pac_id, fecha in ((20, date(2025, 3, 1)), (10, date(2025, 2, 1))) + ]) + session.commit() + session.connection().execute(insert(events), EVENTS) + session.commit() + factory = lambda: Session(engine) # noqa: E731 + return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query) + + +def _run(repositories, build_id, nodes=("members", "timeline")): + cohort_repository, timeline_repository = repositories + dr = driver.Builder().with_modules(reading).build() + return dr.execute(list(nodes), inputs={**ASSETS, "cohort_repository": cohort_repository, + "timeline_repository": timeline_repository, "build_id": build_id}) + + +def test_reads_the_members_and_their_timeline_of_a_build(repositories): + """Pins down: a driver with only the reading nodes returns the build's members ordered by `pac_id` + with `MEMBER_COLUMNS`, and a timeline with `TIMELINE_COLUMNS` holding only the members' events. + + Fails if `members` loses its order or columns, or `timeline` stops filtering by the members. + """ + result = _run(repositories, 1) + + assert list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["members"]["pac_id"].tolist() == [10, 20] + assert list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + assert 99 not in result["timeline"]["pac_id"].tolist() + + +def test_the_timeline_is_cut_where_the_build_was_made(repositories): + """Pins down: the timeline keeps events up to the build's `datos_as_of` and loaded by its + `conocida_hasta`, so reading it again gives the build's input. + + Fails if `timeline` reads with no cut-off, or takes the cut-offs from anywhere but the build. + """ + timeline = _run(repositories, 1)["timeline"] + + assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"] + + +def test_a_build_without_members_reads_an_empty_timeline(repositories): + """Pins down: a build with no members gives empty frames with their columns, not everyone's timeline. + + Fails if an empty member list reaches the query as "no patient filter". + """ + result = _run(repositories, 2) + + assert result["members"].empty and list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["timeline"].empty and list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + + +def test_an_unknown_build_fails(repositories): + """Pins down: asking for a build that doesn't exist raises `UnknownBuild` naming it. + + Fails if `cohort_build` lets `None` through to the other nodes. + """ + with pytest.raises(reading.UnknownBuild, match="404"): + _run(repositories, 404, nodes=("cohort_build",)) + + +def test_the_assets_read_are_sources_of_the_graph(): + """Pins down: the reading nodes read three assets nobody in `models` produces (`cohorte_armado`, + `cohorte_miembro`, `linea_de_tiempo`), so the graph validates only with them declared as sources. + + Fails if a node stops declaring the asset it reads, or reads one more without saying so. + """ + nodes = driver.Builder().with_modules(reading).build().list_available_variables() + + with pytest.raises(InvalidGraph) as error: + validate(nodes) + assert len(str(error.value).splitlines()) == 3 + validate(nodes, sources=set(ASSETS))