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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-20 19:52:05 -06:00
parent 06829a4498
commit ea6db36b23
8 changed files with 164 additions and 109 deletions
+68 -2
View File
@@ -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