Files
models/tests/test_cohort_build.py
edgar ea6db36b23 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
2026-11-20 19:52:05 -06:00

288 lines
15 KiB
Python

"""What this module covers: reading a cohort's queries from dbt's manifest (`models.io.storage.read_queries`), the
graph `models.pipelines.cohort_build` generates from them, and the `models cohorts build` command over it.
Fixtures: `manifest`, a function writing a `manifest.json` whose queries are literal rows, so no dbt or tables are
needed: patients 1 to 6 with a cut-off in their meta, 1 to 5 with an index date, rule `first` flags 2 and 3, rule `second` flags 3 and 4;
`cacu_db` (conftest), a temporary CaCu database whose session the command reads through.
"""
import json
from datetime import date
import pytest
from persistance.edges.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session
from models.__main__ import main
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
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
URL = "cacu/sample"
def _rows(*ids):
return " union all ".join(f"select {i} as pac_id" for i in ids)
INDEX = " union all ".join(f"select {i} as pac_id, '2025-01-0{i}' as fecha_indice" for i in range(1, 6))
def _node(name, kind, sql, order=None, reads=()):
meta = {"cohort": URL, "kind": kind} | ({"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'} if kind == "population" else {})
if order is not None:
meta |= {"name": name, "order": order}
return {"name": name, "unique_id": f"model.p.{name}", "description": f"{name} rule", "compiled_code": sql,
"config": {"meta": meta}, "depends_on": {"nodes": [f"model.p.{r}" for r in reads]}}
def _standard():
return [_node("all_patients", "population", _rows(1, 2, 3, 4, 5, 6)), _node("index", "index", INDEX),
_node("first", "exclusion", _rows(2, 3), 1, ["index", "timeline"]),
_node("second", "exclusion", _rows(3, 4), 2, ["index", "timeline"])]
@pytest.fixture
def manifest(tmp_path):
"""Writes the given nodes, the standard cohort by default, plus a model of another cohort, and returns the path."""
def write(nodes=None):
other = _node("foreign", "population", _rows(99)) | {"config": {"meta": {"cohort": "cacu/other", "kind": "population"}}}
nodes = _standard() if nodes is None else nodes
path = tmp_path / "manifest.json"
path.write_text(json.dumps({"nodes": {node["unique_id"]: node for node in [*nodes, other]}}))
return path
return write
def _sqlite_reader():
"""The real `DbtQueryRepository` over an empty in-memory database: the test queries are literal rows."""
return DbtQueryRepository(lambda: Session(create_engine("sqlite://")))
def test_rules_come_from_the_manifest_in_their_order(manifest):
"""Pins down: only this cohort's queries are read, with name, description and order from the YAML. Fails if another
cohort's models leak in, or the rules follow the manifest's order instead of `order`."""
nodes = _standard()
queries = read_queries(manifest(nodes[:2] + nodes[:1:-1]), URL)
assert [(rule.name, rule.order) for rule in queries.rules] == [("first", 1), ("second", 2)]
assert queries.rules[0].description == "first rule" and "99" not in queries.all_patients
def test_the_chain_gives_population_and_attrition(manifest):
"""Pins down: the study population is the indexed patients minus every rule's set, and a patient two rules flag is
charged to the first. Fails if attrition counts each set whole, or a rule stops applying."""
built = build_cohort(read_queries(manifest(), URL), _sqlite_reader())
assert sorted(built.study_population["pac_id"]) == [1, 5]
assert built.attrition.to_dict("list")["step"] == ["all_patients", "indexed", "first", "second"]
assert built.attrition["n"].tolist() == [6, 5, 3, 2]
assert built.attrition["excluded"].tolist()[1:] == [1, 2, 1]
def test_order_changes_the_charge_not_the_population(manifest):
"""Pins down: with the rules reversed the population is the same and patient 3 is charged to the other rule. Fails if
a rule starts depending on the chain."""
forward = read_queries(manifest(), URL)
backward = CohortQueries(URL, forward.all_patients, forward.index_date, tuple(reversed(forward.rules)), forward.cutoff, {})
one, other = build_cohort(forward, _sqlite_reader()), build_cohort(backward, _sqlite_reader())
assert set(one.study_population["pac_id"]) == set(other.study_population["pac_id"])
assert one.attrition["step"].tolist()[2:] == ["first", "second"] and other.attrition["step"].tolist()[2:] == ["second", "first"]
assert one.attrition["excluded"].tolist()[2:] == [2, 1] and other.attrition["excluded"].tolist()[2:] == [2, 1]
def test_a_new_rule_only_needs_its_query(manifest):
"""Pins down: adding a rule in the manifest adds its nodes, with no code naming it. Fails if the chain stops being
generated from the rules."""
queries = read_queries(manifest([*_standard(), _node("third", "exclusion", _rows(5), 3, ["index"])]), URL)
built = build_cohort(queries, _sqlite_reader())
assert {"em_third", "a_third"} <= set(build_driver(queries).graph.nodes)
assert built.study_population["pac_id"].tolist() == [1]
def test_index_dates_become_dates(manifest):
"""Pins down: `fecha_indice` is a date whatever the engine returns; SQLite returns text. Fails if the conversion is
lost, which the export's schema would reject."""
built = build_cohort(read_queries(manifest(), URL), _sqlite_reader())
assert built.study_population.set_index("pac_id").loc[1, "fecha_indice"] == date(2025, 1, 1)
def test_a_population_without_cutoff_is_refused(manifest):
"""Pins down: the build needs the cut-off its events are cut at. Fails if the export could run without one."""
nodes = _standard()
del nodes[0]["config"]["meta"]["cutoff"]
with pytest.raises(CohortDefinitionError, match="no `cutoff`"):
read_queries(manifest(nodes), URL)
@pytest.mark.parametrize("change, message", [
(lambda n: n[:1] + n[2:], "exactly one `index`"),
(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
exclusion can't read another step. Fails if any of these reaches the graph."""
with pytest.raises(CohortDefinitionError, match=message):
read_queries(manifest(change(_standard())), URL)
@pytest.mark.parametrize("index_sql, message", [
("select 1 as pac_id, '2025-01-01' as fecha_indice union all select 1, '2025-01-02'", "more than one index date"),
("select 7 as pac_id, '2025-01-01' as fecha_indice", "outside all patients"),
])
def test_a_wrong_index_is_an_error_not_attrition(index_sql, message):
"""Pins down: a repeated patient or one unknown to `all_patients` stops the build. Fails if an inner join silently
drops them and they pass as attrition."""
queries = CohortQueries(URL, _rows(1, 2), index_sql, (ExclusionRule("r", "", 1, _rows(2)),), date(2025, 12, 31), {})
with pytest.raises(Exception, match=message):
build_cohort(queries, _sqlite_reader())
def test_the_graph_comes_without_running_anything(manifest):
"""Pins down: the diagram shows each rule, its excluded members and its population, and leaves the inputs out. Fails if
the nodes stop being derived from the rules."""
diagram = mermaid(build_driver(read_queries(manifest(), URL)).graph)
assert 'em_first["EM: first"]' in diagram and "a_first --> " in diagram
assert "dbt_queries" not in diagram and "cohort_queries" not in diagram and "a_second --> study_population" in diagram
def test_cutoff_and_parameters_come_from_the_population_meta(manifest):
"""Pins down: the cut-off and the parameters dbt rendered into the population query's meta are read with the rules,
so the export cuts the events where the rules did. Fails if they're lost or not parsed."""
queries = read_queries(manifest(), URL)
assert queries.cutoff == date(2025, 12, 31) and queries.parameters == {"cutoff": "2025-12-31"}
def test_two_builds_with_other_rules_stay_apart(manifest):
"""Pins down: building a chain decorates copies, so a second build with other rules doesn't inherit the first's
nodes, and the steps themselves stay plain. Fails if the pipeline decorates the step functions in place."""
queries = read_queries(manifest(), URL)
build_driver(queries)
other = build_driver(CohortQueries(URL, queries.all_patients, queries.index_date, (ExclusionRule("only", "", 1, _rows(2)),),
queries.cutoff, {}))
assert {"em_only", "a_only"} <= set(other.graph.nodes) and "em_first" not in other.graph.nodes
assert not getattr(cohort.excluded, "__dict__", {})
def test_the_command_builds_through_the_session(manifest, cacu_db, capsys):
"""Pins down: `cohorts build` reads through the domain's session, shows the attrition and says nothing was stored.
Fails if the wiring to the session or the output changes."""
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest())]) == 0
out = capsys.readouterr().out
assert "second" in out and "cacu/sample: 2 members, not stored" in out
def test_the_command_prints_the_graph_without_a_database(manifest, capsys):
"""Pins down: `--graph` needs only the manifest. Fails if it runs a query."""
nodes = _standard()
nodes[0]["compiled_code"] = "select from nowhere"
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes)), "--graph"]) == 0
assert capsys.readouterr().out.startswith("graph LR")
@pytest.mark.parametrize("arguments, message", [
(["--manifest", "/nowhere/manifest.json"], "manifest.json"),
(["--graph"], "has no queries"),
])
def test_what_is_missing_is_named(manifest, arguments, message, capsys):
"""Pins down: a missing manifest or an unknown cohort ends with exit 1 and a message. Fails if a traceback gets out."""
if arguments[0] == "--graph":
arguments = ["--manifest", str(manifest())]
assert main(["cohorts", "build", "cacu", "unknown", *arguments]) == 1
else:
assert main(["cohorts", "build", "cacu", "sample", *arguments]) == 1
assert message in capsys.readouterr().err
def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys):
"""Pins down: a query that can't run, usually because the view isn't created, ends with exit 1 and names the dbt
command. Fails if the database error reaches the user raw."""
nodes = _standard()
nodes[0]["compiled_code"] = "select pac_id from no_such_view"
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