From 122f71105a6274decc57bd710696bd6a381064b0 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 20:39:53 -0600 Subject: [PATCH] Export reads the timeline from dbt's view --- README.md | 2 +- scripts/export_cohort.py | 56 +++++++++++++++---------------------- tests/test_export_cohort.py | 41 +++++++++++---------------- 3 files changed, 40 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 1057f50..e16f40d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ WebApi. | `io/catalog.py` | `catalog`: qué modelos existen (`/` → su módulo) y `ScreeningModel`, los pasos que define cada modelo (`prepare`, `fit`, `predict`) sobre marcos, sin leer la base. | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | -| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, sin guardar nada en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. Necesita `Transformation` para compilar la línea de tiempo. | +| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. | diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index 2894844..bb6e7ed 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -6,15 +6,14 @@ One file per build, `/cohorts///.parquet`, wher domain's database and `COHORTS_DIR` replaces `/cohorts`. Long format: one row per member and event, with the member's index date on every row and the build's lineage in the file's metadata. -The timeline comes from the dbt model `_linea_de_tiempo`. dbt only compiles it to SQL, which runs here as -a subquery, so nothing is stored in the database and it can be opened read-only (on SQLite, dbt doesn't open it at -all). In a read-only folder, with nothing writing to the file, use +The timeline comes from dbt's view `_linea_de_tiempo`, which holds no rows and needs creating only when its +dbt model changes (`dbt run --select _linea_de_tiempo`). The script only reads, through the domain's +repository, so it needs neither dbt nor write access. In a read-only folder, with nothing writing to the file, use `CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database. """ import argparse import os -import subprocess import sys import tempfile from collections.abc import Callable, Iterable @@ -28,14 +27,17 @@ import pyarrow.parquet as pq from persistance.aristas.oro import CohortBuild, CohortMember from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository from persistance.settings import settings -from sqlalchemy import column, select, text +from sqlalchemy import column, select, table from sqlalchemy.engine import make_url +from sqlalchemy.exc import DBAPIError from models.io.cohorts import SCHEMA ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] -DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} -DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation" + + +class TimelineViewError(RuntimeError): + """dbt's timeline view can't be read.""" def cohorts_root(database_url: str) -> Path: @@ -59,30 +61,15 @@ def lineage_of(path: Path) -> dict[str, str]: return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} -def compile_timeline(domain: str, database_url: str, transformation: Path) -> str: - """The SQL of the domain's timeline model for this engine. On SQLite, dbt connects to an empty throwaway file.""" - backend = make_url(database_url).get_backend_name() - model = f"{domain}_linea_de_tiempo" - with tempfile.TemporaryDirectory(prefix="dbt-compile-") as workdir: - work = Path(workdir) - (work / "schemas").mkdir() - env = {**os.environ, "DBT_SCHEMA_DIR": str(work / "schemas")} - if backend == "sqlite": - env[f"{domain.upper()}_DB_PATH"] = str(work / "empty.db") - subprocess.run( - ["uv", "run", "--no-sync", "dbt", "--quiet", "compile", "--profiles-dir", ".", "--profile", domain, - "--target", DBT_TARGETS[backend], "--select", model, "--target-path", str(work / "target"), - "--log-path", str(work / "logs")], - cwd=transformation, env=env, check=True, capture_output=True, text=True) - compiled = next((work / "target" / "compiled").rglob(f"{model}.sql")) - return compiled.read_text().strip().rstrip(";") - - -def read_timeline(repository: TimelineRepository, sql: str) -> list[dict]: - """Every event of the domain, with `sql` as a subquery. The cut-offs are applied in `build_table`.""" - linea = text(sql.replace(":", r"\:")).columns(*(column(name) for name in TIMELINE_COLUMNS)).subquery("linea") - query = select(*(linea.c[name] for name in TIMELINE_COLUMNS)) - return repository.with_query(lambda **_: query).read() +def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: + """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" + name = f"{domain}_linea_de_tiempo" + view = table(name, *(column(c) for c in TIMELINE_COLUMNS)) + try: + return repository.with_query(lambda **_: select(*(view.c[c] for c in TIMELINE_COLUMNS))).read() + except DBAPIError as error: + raise TimelineViewError(f"can't read {name} ({error.orig}): is it created? " + f"Run `dbt run --select {name}` in Transformation") from error def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str, @@ -153,11 +140,9 @@ def main(argv: list[str] | None = None) -> int: return 1 database_url = getattr(settings, f"{args.domain}_database_url") - transformation = Path(os.environ.get("TRANSFORMATION_DIR", DEFAULT_TRANSFORMATION)) def make_table() -> pa.Table: - rows = read_timeline(timeline, compile_timeline(args.domain, database_url, transformation)) - return build_table(rows, cohorts.members(build.armado_id), build, domain=args.domain, + return build_table(read_timeline(timeline, args.domain), cohorts.members(build.armado_id), build, domain=args.domain, parametros=cohorts.get(build.armado_id).parametros) try: @@ -165,6 +150,9 @@ def main(argv: list[str] | None = None) -> int: except PermissionError as error: print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) return 1 + except TimelineViewError as error: + print(error, file=sys.stderr) + return 1 print(f"{outcome}: {path}") return 0 diff --git a/tests/test_export_cohort.py b/tests/test_export_cohort.py index cbe4061..064e262 100644 --- a/tests/test_export_cohort.py +++ b/tests/test_export_cohort.py @@ -1,13 +1,12 @@ """What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file -goes, what it holds, that it's written once, and that reading the timeline stores nothing in the database. +goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database. Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and -one of a patient outside the build; `timeline_db`, a SQLite file with a `eventos` table and its repository. +one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository. """ import importlib.util -import shutil import sqlite3 from datetime import date, datetime, timezone from pathlib import Path @@ -19,7 +18,6 @@ from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository from sqlmodel import Session, create_engine ROOT = Path(__file__).resolve().parents[1] -TRANSFORMATION = ROOT.parent / "Transformation" MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"), CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")] @@ -152,40 +150,35 @@ def test_server_engine_needs_cohorts_dir(script, monkeypatch): @pytest.fixture def timeline_db(tmp_path): - """A SQLite file with an `eventos` table, and a repository over it.""" + """A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it.""" path = tmp_path / "cacu.db" connection = sqlite3.connect(path) connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})") - connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a:b', null, 't', '1')") + connection.execute("create view cacu_linea_de_tiempo as select * from eventos") + connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')") connection.commit() connection.close() engine = create_engine(f"sqlite:///{path}") return path, TimelineRepository(lambda: Session(engine)) -def test_read_timeline_stores_nothing(script, timeline_db): - """Pins down: the timeline runs as a subquery, with the column contract, and adds no object to the database. - Fails if the read creates a view, or if a colon in the SQL is taken for a bind parameter.""" +def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db): + """Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails + if the script reads another relation, or starts creating objects in the database.""" path, repository = timeline_db - sql = "select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo || ':x' as valor_codigo, valor_numerico, fuente_tabla, fuente_id from eventos" - rows = script.read_timeline(repository, sql) + rows = script.read_timeline(repository, "cacu") - assert rows[0]["pac_id"] == 10 and rows[0]["valor_codigo"] == "a:b:x" + assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")] connection = sqlite3.connect(path) - assert connection.execute("select name from sqlite_master").fetchall() == [("eventos",)] + assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)] connection.close() -@pytest.mark.skipif(not (TRANSFORMATION / ".venv").exists() or shutil.which("uv") is None, - reason="needs the Transformation environment") -def test_compile_never_opens_the_domains_database(script, monkeypatch, tmp_path): - """Pins down: dbt compiles the timeline without touching the domain's SQLite file. Fails if the compile uses the - caller's database path or stops producing SQL over `procedimiento`.""" - database = tmp_path / "cacu.db" - monkeypatch.setenv("CACU_DB_PATH", str(database)) +def test_missing_view_says_how_to_create_it(script, timeline_db): + """Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the + user unexplained, or if the message stops naming the domain's model.""" + _, repository = timeline_db - sql = script.compile_timeline("cacu", f"sqlite:///{database}", TRANSFORMATION) - - assert '"procedimiento"' in sql and not sql.endswith(";") - assert not database.exists() + with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"): + script.read_timeline(repository, "cama")