246 lines
12 KiB
Python
246 lines
12 KiB
Python
"""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: `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.
|
|
"""
|
|
|
|
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.dbt import DbtQueryRepository
|
|
from sqlalchemy import create_engine, text
|
|
from sqlmodel import Session
|
|
|
|
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)]})
|
|
|
|
|
|
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 kit build with a clinical cut-off."""
|
|
return _build()
|
|
|
|
|
|
@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}
|
|
|
|
|
|
@pytest.fixture
|
|
def events():
|
|
"""Dates as text, as SQLite returns them from a subquery."""
|
|
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")]
|
|
|
|
|
|
|
|
|
|
class _Timeline:
|
|
"""Stands in for `timeline_repository`: the given rows, counting reads; the export cuts them itself too."""
|
|
|
|
def __init__(self, rows):
|
|
self.rows, self.reads = rows, 0
|
|
|
|
def read(self, *, until=None, **_):
|
|
self.reads += 1
|
|
return self.rows
|
|
|
|
|
|
_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 population."""
|
|
with pytest.raises(ValueError, match="1 members"):
|
|
cohort_events([e for e in events if e["pac_id"] != 20], POPULATION, date(2025, 12, 31))
|
|
|
|
|
|
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)))
|
|
|
|
assert one == reordered != longer
|
|
|
|
|
|
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, 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(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"):
|
|
export_kit_build(other, _Timeline(None), tmp_path, "cacu", URL)
|
|
|
|
|
|
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 = 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"):
|
|
write_once(table, tmp_path / "cacu" / "1.parquet")
|
|
|
|
assert not list((tmp_path / "cacu").iterdir())
|
|
|
|
|
|
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 cohorts_root("sqlite:////data/cacu.db") == Path("/data/cohorts")
|
|
|
|
|
|
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 cohorts_root("mysql://host/cacu") == Path("/writable")
|
|
|
|
|
|
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"):
|
|
cohorts_root("mysql://host/cacu")
|
|
|
|
|
|
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]
|
|
|
|
|
|
@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])
|
|
|
|
assert stopped.value.code == 2 and message in capsys.readouterr().err
|