"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage. The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them: - `export_kit_build`: a build the kit stored, written once to `.parquet`; - `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is reused; otherwise the next number is written. The timeline comes from the domain's `timeline_repository` (dbt's view `_linea_de_tiempo`), cut at the build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the database. """ import json from datetime import date from pathlib import Path import pandas as pd import pyarrow as pa from hamilton import ad_hoc_utils, driver from models.io.contracts import CohortQueries from models.io.lineage import matches from models.io.storage import (cohort_path, dbt_build_path, latest_dbt_build, read_metadata, require_match, write_once) from models.pipelines.cohort_build import build_cohort from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage NODES = [cohort_events, content_sha256, lineage, cohort_table] def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]: dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build() inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage} results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs) return results["cohort_table"], results["content_sha256"] def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]: """The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's `cohort_repository` and `timeline_repository`.""" build_id = build_id if build_id 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: raise LookupError(f"no such build of {url}: {build_id}") path = cohort_path(root, url, build.armado_id) if path.exists(): require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path)) return path, "reused" population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)], columns=["pac_id", "fecha_indice"]) base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit", "parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()} table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base) write_once(table, path) return path, "exported" def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]: """Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and `timeline` are the domain's `dbt_query_repository` and `timeline_repository`.""" built = build_cohort(queries, dbt_queries) latest = latest_dbt_build(root, queries.url) number = latest[0] + 1 if latest else 1 base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt", "parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(), "rules": json.dumps([rule.name for rule in queries.rules]), "attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")} table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base) if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}): return latest[1], "reused" path = dbt_build_path(root, queries.url, number) write_once(table, path) return path, "exported"