"""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 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 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, 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"] class TimelineViewError(RuntimeError): """dbt's timeline view can't be read.""" 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 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, 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") def make_table() -> pa.Table: 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: 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 except TimelineViewError as error: print(error, file=sys.stderr) return 1 print(f"{outcome}: {path}") return 0 if __name__ == "__main__": sys.exit(main())