From ea6db36b236e39c97df81f12985f5975133ac7e7 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 19:52:05 -0600 Subject: [PATCH] dbt is the only definition of a cohort: the stored build runs dbt's queries The WebApi cycle's build (models.cohorts.build.build_of) runs the cohort's queries from dbt's manifest with the same chain as the export, instead of a Python frame per cohort; the TOML definitions, their frames and definition.py are removed. A cohort may have no exclusions (cacu/cohorte_total, for models whose rules don't fit SQL) and an optional `variables` query; the population meta carries the cohort's version. cohort_urls lists a domain's cohorts in the manifest. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- README.md | 8 +- models/__main__.py | 10 +-- models/cohorts/__init__.py | 9 +- models/cohorts/build.py | 145 ++++++++++++------------------- models/io/contracts.py | 5 +- models/io/storage.py | 22 +++-- models/pipelines/cohort_build.py | 4 + tests/test_cohort_build.py | 70 ++++++++++++++- 8 files changed, 164 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index 207df63..25ac439 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,11 @@ Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de versiones en MLflow con requisitos de promoción, registro de predicciones y -los trabajos de OCR de reportes. Las cohortes con que se entrena son los -armados del kit de indicadores (`cohorte_armado`, en la base de cada -dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa +los trabajos de OCR de reportes. Las cohortes se definen solo en dbt +(`Transformation/models//cohorts/`); el ciclo de la WebApi guarda un +armado de ellas (`cohorte_armado`, en la base de cada dominio, por +`models/cohorts/build.py`), y con ese armado se entrena y se estima. Las reglas +que no caben en SQL son del modelo, sobre `cacu/cohorte_total`. Lee y escribe por los mismos repositorios de `Persistance` que usa WebApi. | Módulo | Qué hace | diff --git a/models/__main__.py b/models/__main__.py index 135795a..07bd7e9 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -388,7 +388,7 @@ def build_parser() -> argparse.ArgumentParser: show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition") show.add_argument("domain", choices=["cacu", "cama", "tea"]) show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") - show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'") + show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)") show.add_argument("--build", type=int, required=True, help="the build's number") show.set_defaults(run=_cohort_show) @@ -397,7 +397,7 @@ def build_parser() -> argparse.ArgumentParser: train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") train.add_argument("--build", "--armado", dest="armado", type=int, help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") - train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") + train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)") train.add_argument("--read", choices=["db", "file"], default="db", help="a kit build read from the database, or its exported file; dbt's builds are files") train.add_argument("--environment", choices=["dev", "prod"], default="dev") @@ -409,7 +409,7 @@ def build_parser() -> argparse.ArgumentParser: estimate.add_argument("--output", required=True, help="the Parquet file to write") estimate.add_argument("--build", "--armado", dest="armado", type=int, help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") - estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") + estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)") estimate.add_argument("--read", choices=["db", "file"], default="db", help="a kit build read from the database, or its exported file; dbt's builds are files") estimate.add_argument("--version", help="the model version; the one in production by default") @@ -424,7 +424,7 @@ def build_parser() -> argparse.ArgumentParser: eda.add_argument("--notebook", help="the notebook; the scenario's /notebooks/01_eda.ipynb by default") eda.add_argument("--build", "--armado", dest="armado", type=int, help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") - eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'") + eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)") eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default") eda.set_defaults(run=_report_eda) @@ -444,7 +444,7 @@ def build_parser() -> argparse.ArgumentParser: run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks") run.add_argument("--build", "--armado", dest="armado", type=int, help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") - run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") + run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)") run.add_argument("--read", choices=["db", "file"], default="db", help="a kit build read from the database, or its exported file; dbt's builds are files") run.add_argument("--version", help="an existing model version, for --promote and --estimate") diff --git a/models/cohorts/__init__.py b/models/cohorts/__init__.py index e00325b..93cbba3 100644 --- a/models/cohorts/__init__.py +++ b/models/cohorts/__init__.py @@ -1,7 +1,6 @@ -"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that -builds its frame from the patients' timeline (dbt's view, through Persistance). +"""Cohorts for the risk models. dbt is their only definition (`Transformation/models//cohorts/`: population, +index date and exclusions as queries in the manifest); this package stores a build of them for the WebApi cycle. - definition.py a cohort's definition, read from its TOML - build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide - /.py a cohort's rule (`expression` in its TOML); `/proposals/`: not built yet + build.py from dbt's queries to `cohorte_armado` and its rows; the stored frame, wide + cama/ CaMa's screening cohort, a PROPOSAL in the old Python-frame format, not built """ diff --git a/models/cohorts/build.py b/models/cohorts/build.py index 2999c20..343057b 100644 --- a/models/cohorts/build.py +++ b/models/cohorts/build.py @@ -1,111 +1,79 @@ -"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables. +"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición. -El armado lee solo la línea de tiempo: la vista de dbt `_linea_de_tiempo`, por la consulta que le dan -(`TimelineRepository.query`), recortada al corte y, -si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin -versiones de fila es aproximado, ADR-MD-009). La regla de -la cohorte es la función que nombra su definición (`expression`). +dbt es la única definición de una cohorte (`Transformation/models//cohorts/`): su población, su fecha +índice y sus exclusiones son consultas del manifest (`models.io.storage.read_queries`), y el armado las corre en la +sesión que le dan, con la misma cadena que la exportación (`models.pipelines.cohort_build.build_cohort`). Las +reglas que no caben en SQL son del modelo, sobre `cacu/cohorte_total` y la línea de tiempo, no de una cohorte. -Rearmar con la misma definición, los mismos parámetros y los mismos datos no -guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están. -Si los datos cambiaron, el `marco_sha` cambia y se guarda un armado nuevo. - -`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o -valida con este armado: llaves y huellas, nunca filas ni `pac_id`. +Rearmar con las mismas consultas, los mismos parámetros y los mismos datos no guarda otro armado: la huella del +pedido y la del marco (`marco_sha`) ya están. Si los datos cambiaron, el `marco_sha` cambia y se guarda uno nuevo. """ -import inspect +import hashlib import json -from datetime import date, datetime, timezone -from importlib import import_module +from contextlib import nullcontext +from datetime import datetime, timezone from core.indicadores.cohortes import TablasCohorte +from persistance.edges.dbt import DbtQueryRepository from sqlmodel import Session, select -from models.cohorts.definition import Definition, json_sha - -DECIMALS = 9 # redondeo de los tiempos en la huella del marco +from models.io.contracts import CohortQueries +from models.pipelines.cohort_build import build_cohort -def timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]: - """The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`).""" - consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta) - return [dict(fila._mapping) for fila in sesion.execute(consulta)] +def json_sha(objeto) -> str: + """sha256 del JSON canónico: claves ordenadas, sin espacios.""" + texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str) + return hashlib.sha256(texto.encode("utf-8")).hexdigest() -def frame_of( - sesion: Session, - definicion: Definition, - inicio: date, - fin: date, - corte: date, - *, - linea, - pacientes: list[int] | None = None, - conocida_hasta: datetime | None = None, -): - """El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente).""" - filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta) - return definicion.function()(filas, definicion.reglas, inicio, fin, corte) +def queries_sha(queries: CohortQueries) -> str: + """Huella de las reglas: el SQL compilado de cada paso, en su orden. Hace el papel de la definición.""" + return json_sha({"all_patients": queries.all_patients, "index_date": queries.index_date, + "rules": [[rule.order, rule.name, rule.sql] for rule in queries.rules], + "variables": queries.variables}) -def frame_sha(miembros, definicion: Definition) -> str: +def frame_sha(miembros, variables=()) -> str: """Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden.""" - nombres = [v.nombre for v in definicion.variables] - - def redondo(valor): - return round(valor, DECIMALS) if isinstance(valor, float) else valor - - return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)] - for m in sorted(miembros, key=lambda m: m.pac_id)]) + return json_sha({"miembros": sorted([int(m["pac_id"]), m["fecha_indice"].isoformat()] for m in miembros), + "variables": sorted([v.pac_id, v.variable, v.valor_codigo, v.valor_numerico] for v in variables)}) -def code_sha(definicion: Definition) -> str: - """Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL.""" - modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}") - return json_sha(inspect.getsource(modulo)) - - -def build_of( - sesion: Session, - definicion: Definition, - inicio: date, - fin: date, - corte: date, - *, - cohortes: TablasCohorte, - linea, - conocida_hasta: datetime | None = None, - ahora: datetime | None = None, -): - """El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`). +def build_of(sesion: Session, queries: CohortQueries, *, cohortes: TablasCohorte, ahora: datetime | None = None): + """El armado sin guardarlo: la fila de `cohorte_armado`, sus exclusiones, sus miembros y sus variables (sin + `armado_id`). Las variables son las de la consulta `variables` de la cohorte, si tiene, solo de sus miembros; las + que no caben en SQL las calcula el modelo de la línea de tiempo. Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión. """ - miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea, - conocida_hasta=conocida_hasta) - parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(), - "corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()} - huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha, - "codigo": code_sha(definicion), "parametros": parametros}) + consultas = DbtQueryRepository(lambda: nullcontext(sesion)) + built = build_cohort(queries, consultas) + miembros = built.study_population.to_dict("records") + parametros = {**queries.parameters, "corte": queries.cutoff.isoformat()} + reglas_sha = json_sha(queries.parameters) + definicion_sha = queries_sha(queries) armado = cohortes.CohorteArmado( - url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha, - reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte, - huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros), - armado_en=ahora or datetime.now(timezone.utc), + url=queries.url, version=queries.version or "0", definicion_sha=definicion_sha, reglas_sha=reglas_sha, + parametros=json.dumps(parametros, sort_keys=True), datos_as_of=queries.cutoff, + huella=json_sha({"definicion": definicion_sha, "reglas": reglas_sha, "parametros": parametros}), + marco_sha="", n_miembros=len(miembros), armado_en=ahora or datetime.now(timezone.utc), ) - exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n) - for orden, (paso, n) in enumerate(atricion, start=1)] - filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice, - indice_fuente_tabla=m.indice_fuente_tabla, - indice_fuente_id=m.indice_fuente_id) for m in miembros] - tipos = {v.nombre: v.tipo for v in definicion.variables} - variables = [ - cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre, - **({"valor_codigo": str(valor)} if tipos[nombre] == "codigo" - else {"valor_numerico": float(valor)})) - for m in miembros for nombre, valor in m.variables.items() if valor is not None - ] + exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=fila["step"], n=int(fila["n"])) + for orden, fila in enumerate(built.attrition.to_dict("records"), start=1)] + filas_miembro = [cohortes.CohorteMiembro(pac_id=int(m["pac_id"]), fecha_indice=m["fecha_indice"], + indice_fuente_tabla=m.get("indice_fuente_tabla"), + indice_fuente_id=None if m.get("indice_fuente_id") is None + else str(m["indice_fuente_id"])) for m in miembros] + socias = {int(m["pac_id"]) for m in miembros} + variables = [cohortes.CohorteVariable(pac_id=int(v["pac_id"]), variable=v["variable"], + valor_codigo=None if v.get("valor_codigo") is None else str(v["valor_codigo"]), + valor_numerico=None if v.get("valor_numerico") is None + else float(v["valor_numerico"])) + for v in (consultas.read(queries.variables) if queries.variables else []) + if int(v["pac_id"]) in socias and (v.get("valor_codigo") is not None or v.get("valor_numerico") is not None)] + armado.marco_sha = frame_sha(miembros, variables) return armado, exclusiones, filas_miembro, variables @@ -117,15 +85,16 @@ def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int | ).first() -def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte): - """El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo.""" - nombres = [v.nombre for v in definicion.variables] +def read_frame(sesion: Session, armado_id: int, *, cohortes: TablasCohorte): + """El marco guardado, ancho: (columnas, filas), una por miembro, con las variables que el armado tenga (los de + dbt no tienen: solo `pac_id` y `fecha_indice`).""" valores: dict[int, dict] = {} variable = cohortes.CohorteVariable for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)): valores.setdefault(fila.pac_id, {})[fila.variable] = ( fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico ) + nombres = sorted({nombre for porpac in valores.values() for nombre in porpac}) miembro = cohortes.CohorteMiembro filas = [ (m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres)) diff --git a/models/io/contracts.py b/models/io/contracts.py index 9c180d6..d9b4df1 100644 --- a/models/io/contracts.py +++ b/models/io/contracts.py @@ -51,7 +51,7 @@ ESTIMATE_FRAME = pandera.DataFrameSchema( "probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))}, strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate") -POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion" +POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables" class CohortFileError(ValueError): @@ -93,6 +93,9 @@ class CohortQueries: rules: tuple[ExclusionRule, ...] cutoff: date parameters: dict + version: str = "" # the population meta's `version`: bumped when a rule changes + # optional: the members' stored variables, long (`pac_id`, `variable`, `valor_codigo`, `valor_numerico`) + variables: str | None = None @dataclass(frozen=True) diff --git a/models/io/storage.py b/models/io/storage.py index a209518..5e046e9 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -30,7 +30,7 @@ import pyarrow as pa import pyarrow.parquet as pq from sqlalchemy.engine import make_url -from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, +from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, VARIABLES, CohortDefinitionError, CohortFileError, CohortQueries, ExclusionRule, check_frame) from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches @@ -188,14 +188,16 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries: if not nodes: raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}") population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url) + # a cohort may have no exclusions (`cacu/cohorte_total`): its study population is everyone with an index exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION] - if not exclusions: - raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries") orders = [node["config"]["meta"]["order"] for node in exclusions] if len(set(orders)) != len(orders): raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}") + variables = [node for node in nodes if node["config"]["meta"]["kind"] == VARIABLES] + if len(variables) > 1: + raise CohortDefinitionError(f"{url} has more than one `{VARIABLES}` query") steps = {node["unique_id"] for node in nodes} - {index["unique_id"]} - for node in exclusions: + for node in [*exclusions, *variables]: if read := steps & set(node["depends_on"]["nodes"]): raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}") meta = population["config"]["meta"] @@ -204,7 +206,17 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries: rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node)) for node in exclusions) return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)), - date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}"))) + date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")), + str(meta.get("version", "")), _compiled(variables[0]) if variables else None) + + +def cohort_urls(manifest: str | Path, domain: str) -> list[str]: + """The urls of the domain's cohorts in dbt's manifest (`meta.cohort` of their population queries), sorted: the + cohorts the WebApi cycle builds.""" + nodes = json.loads(Path(manifest).read_text())["nodes"].values() + return sorted({node["config"]["meta"]["cohort"] for node in nodes + if node.get("config", {}).get("meta", {}).get("kind") == POPULATION + and str(node["config"]["meta"].get("cohort", "")).startswith(f"{domain}/")}) def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]: diff --git a/models/pipelines/cohort_build.py b/models/pipelines/cohort_build.py index cee6341..8b9fbb5 100644 --- a/models/pipelines/cohort_build.py +++ b/models/pipelines/cohort_build.py @@ -29,6 +29,10 @@ def _fresh(function): def build_driver(queries: CohortQueries) -> driver.Driver: """The chain for the cohort's rules, in their order.""" rules = list(queries.rules) + if not rules: # a cohort without rules (`cacu/cohorte_total`): everyone with an index + nodes = [all_patients, indexed, inject(last=source("indexed"))(_fresh(study_population)), + inject(populations=value([]), rules=value([]))(_fresh(attrition))] + return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build() previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]] nodes = [ all_patients, diff --git a/tests/test_cohort_build.py b/tests/test_cohort_build.py index 0235428..eb9d3c7 100644 --- a/tests/test_cohort_build.py +++ b/tests/test_cohort_build.py @@ -16,7 +16,7 @@ from sqlmodel import Session from models.__main__ import main from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule -from models.io.storage import read_queries +from models.io.storage import cohort_urls, read_queries from models.pipelines.cohort_build import build_cohort, build_driver, mermaid from models.steps import cohort @@ -125,10 +125,11 @@ def test_a_population_without_cutoff_is_refused(manifest): @pytest.mark.parametrize("change, message", [ (lambda n: n[:1] + n[2:], "exactly one `index`"), - (lambda n: n[:2], "no `exclusion` queries"), (lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"), (lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"), (lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"), + (lambda n: [*n, _node("v1", "variables", _rows(1)), _node("v2", "variables", _rows(1))], "more than one `variables`"), + (lambda n: [*n, _node("v", "variables", _rows(1)) | {"depends_on": {"nodes": ["model.p.first"]}}], "may only read"), ]) def test_a_badly_defined_cohort_is_refused(manifest, change, message): """Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an @@ -219,3 +220,68 @@ def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys): assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1 assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err + + +def test_a_cohort_without_rules_is_everyone_with_an_index(manifest): + """Pins down: a cohort with no exclusions (`cacu/cohorte_total`) reads, and its study population is every patient + with an index, with only the population and index steps in its attrition. Fails if exclusions become required + again or the chain needs a last rule.""" + queries = read_queries(manifest(_standard()[:2]), URL) + built = build_cohort(queries, _sqlite_reader()) + + assert queries.rules == () + assert sorted(built.study_population["pac_id"]) == [1, 2, 3, 4, 5] + assert built.attrition[["step", "n"]].values.tolist() == [["all_patients", 6], ["indexed", 5]] + + +def test_the_cycle_builds_the_domains_cohorts_of_the_manifest(manifest): + """Pins down: the cohorts of a domain are the `meta.cohort` of the manifest's population queries with that + prefix, sorted, once each; another domain's are not. Fails if an index or exclusion query names a cohort the + cycle then builds, or the prefix leaks.""" + path = manifest([*_standard(), _node("x", "population", _rows(1)) | {"config": {"meta": {"cohort": "cama/c", "kind": "population"}}}]) + + assert cohort_urls(path, "cacu") == ["cacu/other", URL] + assert cohort_urls(path, "cama") == ["cama/c"] + assert cohort_urls(path, "tea") == [] + + +def test_version_and_variables_come_from_the_manifest(manifest): + """Pins down: the population meta's `version` and the optional `variables` query reach `CohortQueries`. Fails if + either is dropped, so builds would lose their version or the WebApp its variables.""" + nodes = _standard() + nodes[0]["config"]["meta"]["version"] = "1.2.0" + sql = "select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico" + queries = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL) + + assert (queries.version, queries.variables) == ("1.2.0", sql) + + +def test_the_stored_build_comes_from_dbts_queries(manifest): + """Pins down: `models.cohorts.build.build_of` turns dbt's queries into the cycle's rows: the build with the + population meta's version and the count of the study population, one exclusion row per attrition step, the + members, and the `variables` query's values of members only. Fails if the build stops running dbt's rules, keeps + a non-member's variable, or its frame hash ignores the variables.""" + from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable, + EvaluacionRiesgo, EvaluacionRiesgoLote) + from core.indicadores.cohortes import TablasCohorte + + from models.cohorts.build import build_of + + tables = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, + EvaluacionRiesgo) + nodes = _standard() + nodes[0]["config"]["meta"]["version"] = "0.3.0" + sql = ("select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico " + "union all select 2, 'pap_0', 'ASC-US', null") + with_variables = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL) + without = read_queries(manifest(nodes), URL) + + with Session(create_engine("sqlite://")) as session: + build, exclusions, members, variables = build_of(session, with_variables, cohortes=tables) + plain, *_ = build_of(session, without, cohortes=tables) + + assert (build.url, build.version, build.n_miembros) == (URL, "0.3.0", 2) + assert [(e.paso, e.n) for e in exclusions] == [("all_patients", 6), ("indexed", 5), ("first", 3), ("second", 2)] + assert sorted(m.pac_id for m in members) == [1, 5] + assert [(v.pac_id, v.variable, v.valor_codigo) for v in variables] == [(1, "pap_0", "NORMAL")] + assert build.marco_sha != plain.marco_sha and build.huella != plain.huella