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
+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