Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking

This commit is contained in:
2026-11-05 16:12:23 -06:00
parent 0fdab3651c
commit 9808701c46
35 changed files with 1710 additions and 719 deletions
+151 -6
View File
@@ -1,5 +1,6 @@
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
split, that training on a build's file registers a version with its lineage, and the `models train` command over it.
split, that training on a build's file registers a version with its lineage, and the `models train` and
`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none.
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
@@ -16,9 +17,10 @@ import pytest
from models.__main__ import main
from models.cacu.cin2_logistic import model
from models.cacu.cin2_logistic.train import train
from models.io.cohorts import SCHEMA
from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry
from models.cacu.cin2_logistic.train import find_trained, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
from models.io.registry import PRODUCTION_ALIAS, registry
def _row(pac_id, index, days, valor, tipo="bethesda"):
@@ -105,8 +107,8 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort_sha256"]) == 64
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
assert len(probabilities) == 20 and probabilities.between(0, 1).all()
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
@@ -146,3 +148,146 @@ def test_what_is_missing_is_named(exported, arguments, message, capsys):
version. Fails if the command lets the import error through, or trains on another file."""
assert main(["train", *arguments]) == 1
assert message in capsys.readouterr().err
def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys):
"""Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per
member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest
version instead of the alias, or the output can't be matched to members."""
main(["train", "cacu", "cin2_logistic"])
main(["train", "cacu", "cin2_logistic"])
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
output = tmp_path / "risks" / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 0
assert "version 1" in capsys.readouterr().out
risks = pd.read_parquet(output)
assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"]
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
metadata = pq.read_metadata(output).metadata
assert metadata[b"modelo_version"] == b"1" and metadata[b"armado_id"] == b"12"
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
"""Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the
alias becomes mandatory."""
main(["train", "cacu", "cin2_logistic"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys):
"""Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes
nothing. Fails if it falls back to another version or lets the error through."""
main(["train", "cacu", "cin2_logistic"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1
assert "no version in production" in capsys.readouterr().err and not output.exists()
RUN = ["run", "cacu", "cin2_logistic"]
def _versions():
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
def test_run_without_a_step_is_refused(capsys):
"""Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running
steps."""
with pytest.raises(SystemExit) as stopped:
main(RUN)
assert stopped.value.code == 2 and "--export" in capsys.readouterr().err
def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path):
"""Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without
its option."""
assert main([*RUN, "--train"]) == 0
assert len(_versions()) == 1
with pytest.raises(LookupError):
registry.resolve("cacu", "cin2_logistic")
def test_repeating_every_step_changes_nothing(exported, mlflow_tracking, tmp_path, capsys):
"""Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops
looking for the existing version, or `--estimate` stops reading the output's metadata."""
output = tmp_path / "output.parquet"
steps = [*RUN, "--train", "--promote", "--estimate", "--output", str(output)]
assert main(steps) == 0
written = output.stat().st_mtime_ns
capsys.readouterr()
assert main(steps) == 0
assert len(_versions()) == 1 and output.stat().st_mtime_ns == written
out = capsys.readouterr().out
assert "already trained" in out and "already in production" in out and "already estimated" in out
def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
"""Pins down: what says a training is the same is the file and the environment, so a build with other content or a
PROD run gets its own version. Fails if the check ignores either and reuses a version from something else."""
assert main([*RUN, "--train", "--armado", "7"]) == 0
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
frame = pd.read_parquet(exported / "12.parquet")
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12)
assert main([*RUN, "--train", "--armado", "12"]) == 0
assert len(_versions()) == 3
def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch):
"""Pins down: a version trained by other code isn't reused. Fails if the check stops comparing `code_sha256`."""
assert main([*RUN, "--train"]) == 0
assert find_trained(exported / "12.parquet") == "1"
monkeypatch.setattr(model, "code_sha256", lambda: "other")
assert find_trained(exported / "12.parquet") is None
def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path):
"""Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if
`--estimate` skips because the file exists."""
output = tmp_path / "output.parquet"
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
def test_promote_needs_a_version(exported, mlflow_tracking, capsys):
"""Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias.
Fails if it promotes some other version."""
assert main([*RUN, "--promote"]) == 1
assert "use --train or --version" in capsys.readouterr().err
def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch):
"""Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if
the cohort or the build change, or training continues on a stale file."""
calls = []
def refuse(cohorts, read_timeline, root, domain, url, build_id=None):
calls.append((domain, url, build_id))
raise LookupError(f"no such build of {url}: {build_id}")
monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse)
assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
assert not _versions()
@@ -1,11 +1,11 @@
"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it
"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it
returns, `Risk` and `Provenance`.
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
"""
from models.io.contract import Provenance, Risk, RiskEstimator
from models.io.contracts import Provenance, Risk, RiskEstimator
class ConstantEstimator:
+49
View File
@@ -0,0 +1,49 @@
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with: the
hashes of files and tables, and the rule that decides an output is already done.
Fixtures: none; each test builds its own small table or file.
"""
import pyarrow as pa
import pytest
from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256
def test_a_table_hashes_by_its_rows_not_its_metadata():
"""Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash.
Fails if metadata such as `built_at` enters the hash, so every rebuild would look new."""
table = pa.table({"pac_id": [1, 2]})
assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"}))
assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]}))
def test_files_hash_in_order(tmp_path):
"""Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails
if a file is skipped or the order stops mattering."""
a, b = tmp_path / "a", tmp_path / "b"
a.write_bytes(b"one")
b.write_bytes(b"two")
assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a)
def test_an_output_is_done_when_its_lineage_has_every_expected_value():
"""Pins down: recorded lineage matches when every expected key has its value, compared as text since files and
MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text."""
recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"}
assert matches(recorded, {"armado_id": 7, "n_members": 2})
assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"})
def test_a_mismatch_is_refused_with_both_sides():
"""Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently."""
with pytest.raises(ValueError, match="doesn't belong.*armado_id"):
require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet")
def test_models_are_registered_as_domain_and_scenario():
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
+7 -6
View File
@@ -16,9 +16,10 @@ import pytest
from core.governance.enums import Environment
from mlflow import MlflowClient
from models.io import training
from models.io.registry import MODEL_SHA_TAG, registry
from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
from models.io import lineage
from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG
from models.io.registry import registry
from models.io.tracking import TrainingRun
class Constant(mlflow.pyfunc.PythonModel):
@@ -37,7 +38,7 @@ def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[T
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
if model is not None:
run.log_model(model)
return run, run.finish(metrics={"auc": 0.7})
return run, registry.register_run(run.finish(metrics={"auc": 0.7}))
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
@@ -129,7 +130,7 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready):
def _git(*args: str) -> str:
return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True,
return subprocess.run(["git", "-C", str(Path(lineage.__file__).parent), *args], capture_output=True, text=True,
check=True).stdout.strip()
@@ -155,7 +156,7 @@ def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_track
def no_git(*args, **kwargs):
raise FileNotFoundError("git")
monkeypatch.setattr(training.subprocess, "run", no_git)
monkeypatch.setattr(lineage.subprocess, "run", no_git)
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
+1 -1
View File
@@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready):
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.io.export import inspect_onnx_metadata
from models.io.tracking import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
@@ -2,8 +2,7 @@ import json
import pytest
from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.io.registry import registry
from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry
class StubModel:
@@ -1,4 +1,4 @@
"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder
"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
doesn't import the database layer, since the file is its only input.
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
@@ -13,7 +13,8 @@ import pyarrow.parquet as pq
import pytest
import models
from models.io.cohorts import SCHEMA, CohortFileError, read_cohort
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
from models.io.storage import read_cohort
def _row(pac_id, fecha_indice, valor, fuente_id):
@@ -1,10 +1,10 @@
"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name.
"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name.
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
"""
import pytest
from models.io.repositories import resolve_repository
from models.io.storage import resolve_repository
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
@@ -4,7 +4,8 @@ from core.governance.enums import ArtifactKind, Environment
from models.io.registry import registry
from mlflow import MlflowException
from models.io.training import ReadOnlyRepository, TrainingRun
from models.io.storage import ReadOnlyRepository
from models.io.tracking import TrainingRun
def test_prod_run_requires_a_cohort_build():
@@ -23,7 +24,7 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path)
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
@@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
from mlflow import MlflowClient
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.finish() == "1"
assert registry.register_run(run.finish()) == "1"
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert second.finish() == "2"
assert registry.register_run(second.finish()) == "2"
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
def unreachable(name):
def unreachable(self, name):
raise MlflowException("servidor no disponible")
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable)
with pytest.raises(MlflowException, match="no disponible"):
third.finish()
registry.register_run(third.finish())
def test_unknown_domain_is_rejected():
with pytest.raises(ValueError, match="dominio desconocido"):
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
def test_finishing_a_run_registers_nothing(mlflow_tracking):
"""Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run
can be kept without becoming a model. Fails if `finish` starts registering again."""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5})
assert registry.client.get_run(run.run_id).info.status == "FINISHED"
assert registry.client.search_model_versions("name='cacu-tamizaje'") == []
@@ -2,7 +2,7 @@ import onnx
import onnx.helper
import pytest
from models.io.export import inspect_onnx_metadata
from models.io.tracking import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
+221
View File
@@ -0,0 +1,221 @@
"""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.aristas.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 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[: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"),
])
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
+171 -110
View File
@@ -1,49 +1,56 @@
"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file
goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database.
"""What this module covers: exporting a cohort build to its Parquet file. The steps (`models.steps.cohort_file`), the
file (`models.io.storage`, `models.io.lineage`), both sources of `models.pipelines.export_cohort`, and the `models cohorts export` command.
Reading the timeline and dbt's queries is Persistance's, tested there.
Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build
cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and
one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository.
Fixtures: `build`, a kit build cut at 2025-12-31 with two members, and `kit`, a stand-in of its repository; `events`, one
kept event per member plus one after the cut-off and one of a patient outside the build; `dbt_cohort`, compiled queries
whose rules keep patients 10 and 20.
"""
import importlib.util
import sqlite3
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pandas as pd
import pyarrow.parquet as pq
import pytest
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from sqlmodel import Session, create_engine
from persistance.aristas.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session
ROOT = Path(__file__).resolve().parents[1]
from models.__main__ import main
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortQueries, ExclusionRule
from models.io.storage import cohorts_root, read_metadata, write_once
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
from models.steps.cohort_file import cohort_events, content_sha256
URL = "cacu/cohorte_vigilancia"
MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"),
CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")]
POPULATION = pd.DataFrame({"pac_id": [20, 10], "fecha_indice": [date(2025, 2, 1), date(2025, 1, 1)]})
@pytest.fixture
def script():
"""The script as a module."""
spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build(armado_id=1, known_until=None, n_miembros=2):
return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until,
n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc))
def _build(armado_id=1, n_miembros=2):
return CohortBuild(armado_id, URL, "1.0", "huella", "marco", date(2025, 12, 31), None, n_miembros,
datetime(2026, 1, 1, tzinfo=timezone.utc))
@pytest.fixture
def build():
"""A build with a clinical cut-off and a load cut-off."""
return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
"""A kit build with a clinical cut-off."""
return _build()
def _event(pac_id, fecha, conocida_en, fuente_id):
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda",
@pytest.fixture
def kit(build):
"""The cohort repository's reads an export needs, over `build` and its members."""
return SimpleNamespace(latest_build=lambda url: build.armado_id, build=lambda i: build if i == build.armado_id else None,
members=lambda i: MEMBERS, get=lambda i: SimpleNamespace(parametros='{"corte": "2025-12-31"}'))
def _event(pac_id, fecha, fuente_id):
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": "2025-02-02 10:00:00", "clase": "medicion", "tipo": "bethesda",
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": fuente_id}
@@ -51,134 +58,188 @@ def _event(pac_id, fecha, conocida_en, fuente_id):
@pytest.fixture
def events():
"""Dates as text, as SQLite returns them from a subquery."""
return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"),
_event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"),
_event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"),
_event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"),
_event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")]
return [_event(20, "2025-03-01", "kept-20"), _event(10, "2025-02-01", "kept-10"),
_event(10, "2026-02-01", "after-the-cutoff"), _event(99, "2025-02-01", "not-a-member")]
def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events):
"""Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each
with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted."""
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}')
assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"]
assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)]
assert table.schema.names == script.SCHEMA.names
def test_table_carries_the_lineage(script, build, events):
"""Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key
a reader relies on is dropped or renamed."""
metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata
lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
class _Timeline:
"""Stands in for `timeline_repository`: the given rows, counting reads; the export cuts them itself too."""
assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2"
assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31"
assert lineage["parametros"] == '{"corte": "2025-12-31"}'
def __init__(self, rows):
self.rows, self.reads = rows, 0
def read(self, *, until=None, **_):
self.reads += 1
return self.rows
def test_a_member_without_events_is_refused(script, build, events):
_query = DbtQueryRepository(lambda: Session(create_engine("sqlite://")))
@pytest.fixture
def dbt_cohort():
"""Patients 10, 20 and 30, all indexed; one rule excludes 30."""
index = "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-02-01' union all select 30, '2025-03-01'"
return CohortQueries(URL, "select 10 as pac_id union all select 20 union all select 30", index,
(ExclusionRule("third", "", 1, "select 30 as pac_id"),), date(2025, 12, 31), {"cutoff": "2025-12-31"})
def test_events_are_the_members_up_to_the_cutoff_in_order(events):
"""Pins down: only members' events, up to the cut-off, ordered by patient, each with its index date. Fails if the
cut-off or the join with the members is lost, or the rows aren't sorted."""
frame = cohort_events(events, POPULATION, date(2025, 12, 31))
assert frame["fuente_id"].tolist() == ["kept-10", "kept-20"]
assert frame["fecha_indice"].tolist() == [date(2025, 1, 1), date(2025, 2, 1)] and list(frame.columns) == SCHEMA.names
def test_a_member_without_events_is_refused(events):
"""Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the
file is written with fewer members than the build."""
file is written with fewer members than the population."""
with pytest.raises(ValueError, match="1 members"):
script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None)
cohort_events([e for e in events if e["pac_id"] != 20], POPULATION, date(2025, 12, 31))
def test_file_is_written_once(script, build, events, tmp_path):
"""Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again."""
calls = []
def test_the_hash_follows_the_rows_only(events):
"""Pins down: the same rows hash the same however they arrive, and another row changes the hash. Fails if the hash
takes in the input order or misses a row."""
one = content_sha256(cohort_events(events, POPULATION, date(2025, 12, 31)))
reordered = content_sha256(cohort_events(events[::-1], POPULATION, date(2025, 12, 31)))
longer = content_sha256(cohort_events(events, POPULATION, date(2026, 12, 31)))
def make_table():
calls.append(1)
return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
assert one == reordered != longer
path, first = script.ensure(build, tmp_path, make_table)
_, second = script.ensure(build, tmp_path, make_table)
def test_kit_build_is_written_once_with_its_lineage(kit, events, tmp_path):
"""Pins down: the kit's build goes to `<armado_id>.parquet` with its identity and cut-off, and a second run reuses it
without reading the timeline. Fails if the lineage loses a key a reader relies on, or the export repeats."""
timeline = _Timeline(events)
path, first = export_kit_build(kit, timeline, tmp_path, "cacu", URL)
_, second = export_kit_build(kit, timeline, tmp_path, "cacu", URL)
assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet"
assert (first, second, len(calls)) == ("exported", "reused", 1)
assert pq.read_metadata(path).num_rows == 2
assert (first, second, timeline.reads) == ("exported", "reused", 1)
lineage = read_metadata(path)
assert lineage["armado_id"] == "1" and lineage["n_members"] == "2" and lineage["producer"] == "kit"
assert lineage["datos_as_of"] == "2025-12-31" and lineage["parametros"] == '{"corte": "2025-12-31"}'
def test_file_of_another_build_is_refused(script, build, events, tmp_path):
"""Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone."""
other = tmp_path / "cacu" / "cohorte_vigilancia"
other.mkdir(parents=True)
pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet")
def test_file_of_another_build_is_refused(kit, events, tmp_path):
"""Pins down: a file whose lineage names another build isn't reused. Fails if the export trusts the path alone."""
other = SimpleNamespace(**{**kit.__dict__, "build": lambda i: _build(armado_id=1, n_miembros=5)})
export_kit_build(kit, _Timeline(events), tmp_path, "cacu", URL)
with pytest.raises(ValueError, match="doesn't belong"):
script.ensure(build, tmp_path, lambda: pytest.fail("must not export"))
export_kit_build(other, _Timeline(None), tmp_path, "cacu", URL)
def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch):
def test_unknown_kit_build_is_named(kit, tmp_path):
"""Pins down: a build that doesn't exist ends in `LookupError` before anything is read. Fails if it exports another."""
with pytest.raises(LookupError, match="no such build"):
export_kit_build(kit, _Timeline(None), tmp_path, "cacu", URL, build_id=9)
def test_dbt_build_writes_its_population_and_attrition(dbt_cohort, events, tmp_path):
"""Pins down: dbt's rules give the members, numbered in the `dbt/` folder, with their parameters, rules and attrition
in the lineage. Fails if the export ignores the rules, or the file lands where the kit's builds are looked for."""
path, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
assert (path, outcome) == (tmp_path / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet", "exported")
assert sorted(set(pq.read_table(path).column("pac_id").to_pylist())) == [10, 20]
lineage = read_metadata(path)
assert lineage["producer"] == "dbt" and lineage["build"] == "1" and lineage["rules"] == '["third"]'
assert '"step":"third","n":2,"excluded":1' in lineage["attrition"] and len(lineage["content_sha256"]) == 64
def test_dbt_build_is_reused_until_its_rows_change(dbt_cohort, events, tmp_path):
"""Pins down: building again with the same rows writes nothing; new rows write the next number. Fails if every run
writes a file, or a change is missed."""
first, _ = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
again, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
more = [*events, _event(20, "2025-04-01", "new-20")]
second, changed = export_dbt_build(dbt_cohort, _query, _Timeline(more), tmp_path, "cacu")
assert (again, outcome) == (first, "reused")
assert (second.name, changed) == ("2.parquet", "exported")
def test_failed_write_leaves_no_file(events, tmp_path, monkeypatch):
"""Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a
later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file."""
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
table = pq.read_table(export_kit_build(SimpleNamespace(latest_build=lambda u: 1, build=lambda i: _build(), members=lambda i: MEMBERS,
get=lambda i: SimpleNamespace(parametros=None)),
_Timeline(events), tmp_path / "first", "cacu", URL)[0])
def fail(*_):
raise OSError("disk full")
monkeypatch.setattr(Path, "replace", fail)
with pytest.raises(OSError, match="disk full"):
script.write_once(table, tmp_path / "cacu" / "1.parquet")
write_once(table, tmp_path / "cacu" / "1.parquet")
assert not list((tmp_path / "cacu").iterdir())
@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"])
def test_files_live_next_to_the_database(script, monkeypatch, url):
"""Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix
ends up in the path."""
def test_files_live_next_to_the_database(monkeypatch):
"""Pins down: `cohorts/` next to the SQLite file. Fails if the default folder moves."""
monkeypatch.delenv("COHORTS_DIR", raising=False)
assert script.cohorts_root(url) == Path("/data/cohorts")
assert cohorts_root("sqlite:////data/cacu.db") == Path("/data/cohorts")
def test_cohorts_dir_replaces_the_folder(script, monkeypatch):
def test_cohorts_dir_replaces_the_folder(monkeypatch):
"""Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored."""
monkeypatch.setenv("COHORTS_DIR", "/writable")
assert script.cohorts_root("mysql://host/cacu") == Path("/writable")
assert cohorts_root("mysql://host/cacu") == Path("/writable")
def test_server_engine_needs_cohorts_dir(script, monkeypatch):
"""Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path."""
def test_server_engine_needs_cohorts_dir(monkeypatch):
"""Pins down: a server database has no data folder, so the export says what to set. Fails if it guesses a path."""
monkeypatch.delenv("COHORTS_DIR", raising=False)
with pytest.raises(ValueError, match="COHORTS_DIR"):
script.cohorts_root("mysql://host/cacu")
cohorts_root("mysql://host/cacu")
@pytest.fixture
def timeline_db(tmp_path):
"""A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it."""
path = tmp_path / "cacu.db"
connection = sqlite3.connect(path)
connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})")
connection.execute("create view cacu_linea_de_tiempo as select * from eventos")
connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')")
connection.commit()
connection.close()
engine = create_engine(f"sqlite:///{path}")
return path, TimelineRepository(lambda: Session(engine))
def test_the_command_exports_from_dbt_through_the_session(cacu_db, tmp_path, monkeypatch, capsys):
"""Pins down: `cohorts export --source dbt` reads the manifest, runs the rules and the timeline through the domain's
session and writes the file, then reuses it. Fails if the wiring to the session, the manifest or the folder changes."""
import json
from persistance.db import get_cacu_engine
with get_cacu_engine().begin() as connection:
connection.execute(text("create view cacu_linea_de_tiempo as select 10 as pac_id, '2025-02-01' as fecha, "
"'2025-02-02 10:00:00' as conocida_en, 'medicion' as clase, 'bethesda' as tipo, 'bethesda' as codigo, "
"'NORMAL' as valor_codigo, null as valor_numerico, 't' as fuente_tabla, '1' as fuente_id"))
nodes = [
{"name": "p", "kind": "population", "sql": "select 10 as pac_id union all select 20",
"meta": {"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'}},
{"name": "i", "kind": "index", "sql": "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-01-01'"},
{"name": "x", "kind": "exclusion", "sql": "select 20 as pac_id", "meta": {"name": "only", "order": 1}},
]
manifest = tmp_path / "manifest.json"
manifest.write_text(json.dumps({"nodes": {n["name"]: {
"name": n["name"], "unique_id": n["name"], "description": "", "compiled_code": n["sql"], "depends_on": {"nodes": []},
"config": {"meta": {"cohort": URL, "kind": n["kind"], **n.get("meta", {})}}} for n in nodes}}))
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
command = ["cohorts", "export", "cacu", "cohorte_vigilancia", "--source", "dbt", "--manifest", str(manifest)]
assert main(command) == 0 and main(command) == 0
out = capsys.readouterr().out
assert "exported:" in out and "reused:" in out
assert pq.read_table(tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet").column("pac_id").to_pylist() == [10]
def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db):
"""Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails
if the script reads another relation, or starts creating objects in the database."""
path, repository = timeline_db
@pytest.mark.parametrize("arguments, message", [
(["--source", "dbt"], "needs --manifest"),
(["--source", "dbt", "--manifest", "m.json", "--build", "1"], "can't go with --source dbt"),
])
def test_dbt_source_arguments_are_checked(arguments, message, capsys):
"""Pins down: `--source dbt` needs the manifest and takes no kit build. Fails if either combination runs."""
with pytest.raises(SystemExit) as stopped:
main(["cohorts", "export", "cacu", "cohorte_vigilancia", *arguments])
rows = script.read_timeline(repository, "cacu")
assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")]
connection = sqlite3.connect(path)
assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)]
connection.close()
def test_missing_view_says_how_to_create_it(script, timeline_db):
"""Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the
user unexplained, or if the message stops naming the domain's model."""
_, repository = timeline_db
with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"):
script.read_timeline(repository, "cama")
assert stopped.value.code == 2 and message in capsys.readouterr().err