dags: the timeline is always read with an explicit known_until
known_until is the build's conocida_hasta or, when the build has none, the moment of the read; it's a node, so the run can record it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,7 +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. |
|
||||
| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). 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 (`<dominio>-<escenario>`), 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). |
|
||||
|
||||
+12
-5
@@ -5,11 +5,13 @@ which tables a model depends on (`persistance.assets.validate` with them as sour
|
||||
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.
|
||||
The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off
|
||||
(`known_until`): the build's `conocida_hasta`, or the moment of the read when the build has none. The run
|
||||
records `known_until`, so the read can be repeated once silver keeps its history.
|
||||
"""
|
||||
|
||||
from dataclasses import fields
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository
|
||||
@@ -36,9 +38,14 @@ def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort
|
||||
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,
|
||||
def known_until(cohort_build: CohortBuild) -> datetime:
|
||||
"""The load cut-off of the read: the build's `conocida_hasta`, or now (UTC) when the build has none."""
|
||||
return cohort_build.conocida_hasta or datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, known_until: datetime,
|
||||
timeline_repository: TimelineRepository) -> pd.DataFrame:
|
||||
"""The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and `conocida_hasta`."""
|
||||
"""The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and at `known_until`."""
|
||||
rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of,
|
||||
known_until=cohort_build.conocida_hasta)
|
||||
known_until=known_until)
|
||||
return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS))
|
||||
|
||||
+28
-12
@@ -1,4 +1,4 @@
|
||||
"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `timeline`)
|
||||
"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `known_until`, `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
|
||||
@@ -57,6 +57,7 @@ EVENTS = [
|
||||
_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"),
|
||||
_event(10, date(2025, 4, 1), datetime(2099, 1, 1), "loaded-in-the-future"),
|
||||
]
|
||||
|
||||
|
||||
@@ -75,26 +76,27 @@ def timeline_query(*, patients, until, known_until):
|
||||
@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.
|
||||
UTC, members 20 and 10 (inserted in that order). Build 2 has no members; build 3 has member 10 and no
|
||||
load cut-off. `EVENTS` has one event per member inside both cut-offs, one past the clinical cut-off,
|
||||
one loaded after build 1, one of a patient outside the cohort and one loaded in the future.
|
||||
"""
|
||||
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"})
|
||||
load_cut = {1: "2026-01-02T08:00:00+00:00", 2: "2026-01-02T08:00:00+00:00", 3: None}
|
||||
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)
|
||||
reglas_sha="r", parametros=json.dumps({"corte": "2025-12-31", "conocida_hasta": cut}),
|
||||
datos_as_of=date(2025, 12, 31), huella=f"h{armado_id}", marco_sha=f"m{armado_id}",
|
||||
n_miembros=0, armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
|
||||
for armado_id, cut in load_cut.items()
|
||||
])
|
||||
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)))
|
||||
CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=fecha,
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
|
||||
for armado_id, pac_id, fecha in ((1, 20, date(2025, 3, 1)), (1, 10, date(2025, 2, 1)),
|
||||
(3, 10, date(2025, 2, 1)))
|
||||
])
|
||||
session.commit()
|
||||
session.connection().execute(insert(events), EVENTS)
|
||||
@@ -135,6 +137,20 @@ def test_the_timeline_is_cut_where_the_build_was_made(repositories):
|
||||
assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"]
|
||||
|
||||
|
||||
def test_a_build_without_a_load_cut_off_is_read_up_to_now(repositories):
|
||||
"""Pins down: when the build has no `conocida_hasta`, `known_until` is the moment of the read (UTC),
|
||||
never `None`, and the timeline is cut there.
|
||||
|
||||
Fails if `known_until` lets `None` through (the read couldn't be repeated) or isn't the one the
|
||||
timeline used.
|
||||
"""
|
||||
before = datetime.now(timezone.utc)
|
||||
result = _run(repositories, 3, nodes=("known_until", "timeline"))
|
||||
|
||||
assert before <= result["known_until"] <= datetime.now(timezone.utc)
|
||||
assert result["timeline"]["fuente_id"].tolist() == ["kept-10"]
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user