From 34de6e93481e371f5eeaf4672e5911ec99ddb8bf Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 18:32:07 -0600 Subject: [PATCH] Standalone export of a kit cohort build to Parquet --- README.md | 1 + pyproject.toml | 3 + scripts/export_cohort.py | 177 +++++++++++++++++++++++++++++++++ tests/test_export_cohort.py | 191 ++++++++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+) create mode 100644 scripts/export_cohort.py create mode 100644 tests/test_export_cohort.py diff --git a/README.md b/README.md index fd52038..8ec6767 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ WebApi. | `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | | `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. | | `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/pyproject.toml b/pyproject.toml index a063a5f..12680a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,9 @@ dependencies = [ "mlflow>=2.9", # The model DAGs (`models/pipelines`): each function a node, each parameter an edge. "apache-hamilton>=1.90", + # Cohort builds are Parquet files, read and written as frames. + "pandas>=2.0", + "pyarrow>=15", ] [project.optional-dependencies] diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py new file mode 100644 index 0000000..bb26e5a --- /dev/null +++ b/scripts/export_cohort.py @@ -0,0 +1,177 @@ +"""Export a kit cohort build to its Parquet file, once. + + uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N] + +One file per build, `/cohorts///.parquet`, where `` is the folder of the +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 +`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 +from datetime import datetime, timezone +from importlib import import_module +from pathlib import Path + +import pandas as pd +import pyarrow as pa +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.engine import make_url + +SCHEMA = pa.schema([ + ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), + ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), + ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), + ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), +]) +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" + + +def cohorts_root(database_url: str) -> Path: + """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" + if configured := os.environ.get("COHORTS_DIR"): + return Path(configured) + url = make_url(database_url) + if url.get_backend_name() != "sqlite" or not url.database: + raise ValueError("this database has no data folder: set COHORTS_DIR") + return Path(url.database.removeprefix("file:")).parent / "cohorts" + + +def cohort_file(build: CohortBuild, root: Path) -> Path: + domain, cohort = build.url.split("/", 1) + return root / domain / cohort / f"{build.armado_id}.parquet" + + +def lineage_of(path: Path) -> dict[str, str]: + """The lineage in the file's metadata, without reading any rows.""" + metadata = pq.read_metadata(path).metadata + 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 build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str, + parametros: str | None) -> pa.Table: + """The members' events up to `datos_as_of` and loaded by `conocida_hasta`, in the file's order, with the lineage.""" + members = list(members) + index_dates = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"]) + frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(index_dates, on="pac_id") + frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date + frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True) + frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"]) + frame = frame[frame["fecha"] <= build.datos_as_of] + if build.conocida_hasta is not None: + known_until = pd.Timestamp(build.conocida_hasta) + frame = frame[frame["conocida_en"] <= (known_until.tz_localize("UTC") if known_until.tzinfo is None else known_until)] + missing = len(members) - frame["pac_id"].nunique() + if missing: + raise ValueError(f"{missing} members of build {build.armado_id} have no events in the timeline") + frame = frame.sort_values(ROW_ORDER, kind="stable") + lineage = { + "url": build.url, "version": build.version, "armado_id": build.armado_id, "domain": domain, + "parametros": parametros or "{}", "datos_as_of": build.datos_as_of.isoformat(), + "conocida_hasta": build.conocida_hasta.isoformat() if build.conocida_hasta else "", + "n_members": len(members), "producer": "kit", "built_at": datetime.now(timezone.utc).isoformat(), + } + table = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False) + return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}}) + + +def write_once(table: pa.Table, path: Path) -> None: + """The file appears complete or not at all.""" + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle: + partial = Path(handle.name) + try: + pq.write_table(table, partial) + partial.replace(path) + finally: + partial.unlink(missing_ok=True) + + +def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]: + """The build's file: reused if it's already there and belongs to the build, written once if not.""" + path = cohort_file(build, root) + if path.exists(): + lineage = lineage_of(path) + if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): + raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}") + return path, "reused" + write_once(make_table(), path) + return path, "exported" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Export a kit cohort build to its Parquet file, once.") + parser.add_argument("--domain", required=True, choices=["cacu", "cama", "tea"]) + parser.add_argument("--cohort", required=True, help="the cohort without its domain, e.g. cohorte_vigilancia") + parser.add_argument("--build", type=int, help="the build's armado_id; the cohort's latest by default") + args = parser.parse_args(argv) + + repositories = import_module(f"persistance.{args.domain}") + cohorts, timeline = repositories.cohorte_repository, repositories.timeline_repository + url = f"{args.domain}/{args.cohort}" + build_id = args.build if args.build is not None else cohorts.latest_build(url) + build = None if build_id is None else cohorts.build(build_id) + if build is None or build.url != url: + print(f"no such build of {url}: {build_id}", file=sys.stderr) + 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, + parametros=cohorts.get(build.armado_id).parametros) + + try: + path, outcome = ensure(build, cohorts_root(database_url), make_table) + except PermissionError as error: + print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) + return 1 + print(f"{outcome}: {path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_export_cohort.py b/tests/test_export_cohort.py new file mode 100644 index 0000000..cbe4061 --- /dev/null +++ b/tests/test_export_cohort.py @@ -0,0 +1,191 @@ +"""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. + +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. +""" + +import importlib.util +import shutil +import sqlite3 +from datetime import date, datetime, timezone +from pathlib import Path + +import pyarrow.parquet as pq +import pytest +from persistance.aristas.oro import CohortBuild, CohortMember +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")] + + +@pytest.fixture +def script(): + """The script as a module.""" + spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _build(armado_id=1, known_until=None, n_miembros=2): + return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until, + n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc)) + + +@pytest.fixture +def build(): + """A build with a clinical cut-off and a load cut-off.""" + return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + + +def _event(pac_id, fecha, conocida_en, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda", + "codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical", + "fuente_id": fuente_id} + + +@pytest.fixture +def events(): + """Dates as text, as SQLite returns them from a subquery.""" + return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"), + _event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"), + _event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"), + _event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"), + _event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")] + + +def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events): + """Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each + with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted.""" + table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}') + + assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"] + assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)] + assert table.schema.names == script.SCHEMA.names + + +def test_table_carries_the_lineage(script, build, events): + """Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key + a reader relies on is dropped or renamed.""" + metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata + lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2" + assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31" + assert lineage["parametros"] == '{"corte": "2025-12-31"}' + + +def test_a_member_without_events_is_refused(script, build, events): + """Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the + file is written with fewer members than the build.""" + with pytest.raises(ValueError, match="1 members"): + script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None) + + +def test_file_is_written_once(script, build, events, tmp_path): + """Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again.""" + calls = [] + + def make_table(): + calls.append(1) + return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + + path, first = script.ensure(build, tmp_path, make_table) + _, second = script.ensure(build, tmp_path, make_table) + + assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet" + assert (first, second, len(calls)) == ("exported", "reused", 1) + assert pq.read_metadata(path).num_rows == 2 + + +def test_file_of_another_build_is_refused(script, build, events, tmp_path): + """Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone.""" + other = tmp_path / "cacu" / "cohorte_vigilancia" + other.mkdir(parents=True) + pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet") + + with pytest.raises(ValueError, match="doesn't belong"): + script.ensure(build, tmp_path, lambda: pytest.fail("must not export")) + + +def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch): + """Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a + later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file.""" + table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + + def fail(*_): + raise OSError("disk full") + + monkeypatch.setattr(Path, "replace", fail) + with pytest.raises(OSError, match="disk full"): + script.write_once(table, tmp_path / "cacu" / "1.parquet") + + assert not list((tmp_path / "cacu").iterdir()) + + +@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"]) +def test_files_live_next_to_the_database(script, monkeypatch, url): + """Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix + ends up in the path.""" + monkeypatch.delenv("COHORTS_DIR", raising=False) + assert script.cohorts_root(url) == Path("/data/cohorts") + + +def test_cohorts_dir_replaces_the_folder(script, monkeypatch): + """Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored.""" + monkeypatch.setenv("COHORTS_DIR", "/writable") + assert script.cohorts_root("mysql://host/cacu") == Path("/writable") + + +def test_server_engine_needs_cohorts_dir(script, monkeypatch): + """Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path.""" + monkeypatch.delenv("COHORTS_DIR", raising=False) + with pytest.raises(ValueError, match="COHORTS_DIR"): + script.cohorts_root("mysql://host/cacu") + + +@pytest.fixture +def timeline_db(tmp_path): + """A SQLite file with an `eventos` table, 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.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.""" + 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) + + assert rows[0]["pac_id"] == 10 and rows[0]["valor_codigo"] == "a:b:x" + connection = sqlite3.connect(path) + assert connection.execute("select name from sqlite_master").fetchall() == [("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)) + + sql = script.compile_timeline("cacu", f"sqlite:///{database}", TRANSFORMATION) + + assert '"procedimiento"' in sql and not sql.endswith(";") + assert not database.exists()