06f2bf45ac
The SQLite TEA gate failed in training: the API and the run opened the new MLflow SQLite file together, both ran its migrations, and one failed with "duplicate column name: step". Deployments use an MLflow server, so only tests had the race.
241 lines
9.7 KiB
Python
241 lines
9.7 KiB
Python
"""Shared by every test: the synthetic hospital, a fresh platform per test (SQLite and
|
|
PostgreSQL), and the platform's own processes, run the way they run in production."""
|
|
|
|
import atexit
|
|
import json
|
|
import os
|
|
import secrets
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import httpx
|
|
import pytest
|
|
from sqlalchemy import create_engine, make_url, text
|
|
|
|
from synthetic.site import build, create_database
|
|
|
|
SCHEMAS = ("bronze", "silver", "gold", "config")
|
|
|
|
|
|
def run(env, *args):
|
|
subprocess.run(args, env=env, check=True, cwd=env["ISSSTELEON_DATA"])
|
|
|
|
|
|
def ingest(env, pipeline="site"):
|
|
config = Path(env["ISSSTELEON_DATA"]) / "run.json"
|
|
config.write_text(json.dumps({"ops": {"run_pipeline": {"config": {"pipeline": pipeline}}}}))
|
|
run(env, "dagster", "job", "execute", "-m", "models.definitions", "-j", "ingest",
|
|
"--config", str(config)) # fmt: skip
|
|
|
|
|
|
@pytest.fixture(params=["sqlite", "postgres"])
|
|
def platform(request, tmp_path):
|
|
"""Env for a fresh platform on each backend, and a SQL connection to read it back."""
|
|
return _platform(request.param, tmp_path)
|
|
|
|
|
|
@pytest.fixture
|
|
def fresh_platform(tmp_path_factory):
|
|
"""A second, empty platform (SQLite): where a test sends what the first one exported."""
|
|
return _platform("sqlite", tmp_path_factory.mktemp("fresh"))
|
|
|
|
|
|
def _platform(kind: str, tmp_path: Path) -> SimpleNamespace:
|
|
(tmp_path / "dagster").mkdir()
|
|
shutil.copy(Path(__file__).parent / "dagster.yaml", tmp_path / "dagster") # as deployed
|
|
env = {
|
|
**os.environ,
|
|
"ISSSTELEON_DATA": str(tmp_path),
|
|
"DLT_DATA_DIR": str(tmp_path / "dlt"),
|
|
"DAGSTER_HOME": str(tmp_path / "dagster"),
|
|
"MLFLOW_TRACKING_URI": f"sqlite:///{tmp_path / 'mlflow.db'}",
|
|
"EXECUTION_MODE": "sync",
|
|
}
|
|
_mlflow_schema(env["MLFLOW_TRACKING_URI"], tmp_path)
|
|
if kind == "sqlite":
|
|
url = env["PLATFORM_DATABASE_URL"] = f"sqlite:///{tmp_path / 'platform.db'}"
|
|
attach = [f"ATTACH '{tmp_path}/platform__{s}.db' AS {s}" for s in SCHEMAS]
|
|
else:
|
|
pg = os.environ["POSTGRES_TEST_URL"] # required: run with `docker compose run --rm test`
|
|
env.update(PLATFORM_DATABASE_URL=pg, DBT_TARGET="postgres")
|
|
url = make_url(pg).set(drivername="postgresql+psycopg2")
|
|
attach = []
|
|
with create_engine(url).begin() as con:
|
|
for schema in SCHEMAS: # and dlt's staging copies, so no table outlives a test
|
|
con.exec_driver_sql(f"drop schema if exists {schema} cascade")
|
|
con.exec_driver_sql(f"drop schema if exists {schema}_staging cascade")
|
|
|
|
def count(table: str) -> int:
|
|
with create_engine(url).connect() as con:
|
|
for statement in attach:
|
|
con.exec_driver_sql(statement)
|
|
return con.execute(text(f"select count(*) from {table}")).scalar()
|
|
|
|
def query(sql: str):
|
|
with create_engine(url).connect() as con:
|
|
for statement in attach:
|
|
con.exec_driver_sql(statement)
|
|
return con.execute(text(sql)).fetchall()
|
|
|
|
return SimpleNamespace(
|
|
env=env, count=count, query=query,
|
|
run=lambda *args: run(env, *args),
|
|
ingest=lambda pipeline="site": ingest(env, pipeline),
|
|
save=lambda kind, item, path: run(env, "python", "-m", "persistance.config_log",
|
|
kind, item, str(path)),
|
|
) # fmt: skip
|
|
|
|
|
|
_MLFLOW_TEMPLATE: list[Path] = [] # MLflow's empty SQLite schema, built once per session
|
|
|
|
|
|
def _mlflow_schema(uri: str, tmp_path: Path) -> None:
|
|
"""Start the platform with MLflow's schema in place: when the API and a run open a new
|
|
file at the same time, both run its migrations and one fails (`duplicate column name:
|
|
step`). The schema is built once (slow: every migration) and copied for each platform."""
|
|
if not _MLFLOW_TEMPLATE:
|
|
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
|
|
|
folder = tempfile.mkdtemp(prefix="mlflow-schema-")
|
|
atexit.register(shutil.rmtree, folder, ignore_errors=True)
|
|
template = Path(folder) / "mlflow.db"
|
|
SqlAlchemyStore(f"sqlite:///{template}", template.parent.as_uri()).engine.dispose()
|
|
_MLFLOW_TEMPLATE.append(template)
|
|
shutil.copy(_MLFLOW_TEMPLATE[0], uri.removeprefix("sqlite:///"))
|
|
|
|
|
|
def _free_port() -> int:
|
|
with socket.socket() as s:
|
|
s.bind(("127.0.0.1", 0))
|
|
return s.getsockname()[1]
|
|
|
|
|
|
def _until_up(url: str, process: subprocess.Popen, seconds: int = 120) -> None:
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
if process.poll() is not None:
|
|
raise RuntimeError(f"{process.args[0]} exited with {process.returncode}")
|
|
try:
|
|
if httpx.get(url, timeout=2).status_code == 200:
|
|
return
|
|
except httpx.TransportError:
|
|
pass
|
|
time.sleep(1)
|
|
raise TimeoutError(url)
|
|
|
|
|
|
@pytest.fixture
|
|
def api(platform):
|
|
"""The Dagster webserver and daemon and the API, as separate processes on this platform
|
|
(as compose runs them), and an HTTP client for the API: what the WebApp talks to."""
|
|
with _serve(platform) as client:
|
|
yield client
|
|
|
|
|
|
@pytest.fixture
|
|
def fresh_api(fresh_platform):
|
|
"""The same processes on the second, empty platform."""
|
|
with _serve(fresh_platform) as client:
|
|
yield client
|
|
|
|
|
|
@contextmanager
|
|
def _serve(platform: SimpleNamespace):
|
|
dagster_port, api_port = _free_port(), _free_port()
|
|
env = {**platform.env, "DAGSTER_HOST": "127.0.0.1", "DAGSTER_PORT": str(dagster_port)}
|
|
webserver = subprocess.Popen(
|
|
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
|
"-p", str(dagster_port)], env=env, cwd=env["ISSSTELEON_DATA"],
|
|
) # fmt: skip
|
|
server = subprocess.Popen(
|
|
["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1",
|
|
"--port", str(api_port)], env=env, cwd=env["ISSSTELEON_DATA"],
|
|
) # fmt: skip
|
|
daemon = None
|
|
try:
|
|
_until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver)
|
|
# Started once the webserver has set up the instance, as compose orders them.
|
|
daemon = subprocess.Popen(
|
|
["dagster-daemon", "run", "-m", "models.definitions"],
|
|
env=env,
|
|
cwd=env["ISSSTELEON_DATA"],
|
|
)
|
|
_until_up(f"http://127.0.0.1:{api_port}/health", server)
|
|
with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client:
|
|
yield client
|
|
finally:
|
|
for process in (server, daemon, webserver):
|
|
if process is not None:
|
|
process.terminate()
|
|
process.wait(timeout=30)
|
|
|
|
|
|
ROOT = Path(__file__).parent
|
|
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
|
SITE_PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "erick_site.json"
|
|
CONCEPT_MAPS = ROOT / "tests" / "fixtures" / "concept_maps"
|
|
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
|
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
|
WOMEN = 50 # the site's patients in tests (the dev deployment has a thousand)
|
|
|
|
|
|
def synthea(out: Path, people: int, modules: str, ages: str, seed: int = 7) -> list[dict]:
|
|
"""Synthea's FHIR R4 Bundles of `people` women (fixed seeds) through `modules`, with
|
|
only the resources the platform reads, from the last eight years."""
|
|
subprocess.run(
|
|
["java", "-jar", SYNTHEA, "-p", str(people), "-s", str(seed), "-cs", str(seed),
|
|
"-g", "F", "-a", ages, "-d", str(MODULES), "-m", modules,
|
|
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
|
"--exporter.hospital.fhir.export", "false",
|
|
"--exporter.practitioner.fhir.export", "false", "--exporter.years_of_history", "8",
|
|
"--exporter.fhir.included_resources", "Patient,Encounter,DiagnosticReport,Observation"],
|
|
check=True, capture_output=True, cwd=out.parent,
|
|
) # fmt: skip
|
|
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def site_women(tmp_path_factory) -> list[dict]:
|
|
"""The women whose studies ISSSTELEON's test source holds (CaCu and CaMa screening)."""
|
|
out = tmp_path_factory.mktemp("synthea") / "out"
|
|
return synthea(out, WOMEN, "cervical_screening:breast_screening", "25-80")
|
|
|
|
|
|
def put_concept_map(api, name: str) -> None:
|
|
"""A site's ConceptMap fixture, saved through the API as a site's operator would."""
|
|
doc = json.loads((CONCEPT_MAPS / f"{name}.json").read_text())
|
|
response = api.put(f"/ingest/concept-maps/{name}", json=doc)
|
|
assert response.status_code == 200, response.text
|
|
|
|
|
|
def _patients(q, truth) -> dict[str, str]:
|
|
"""The true patient of every record the site gave (for checking only)."""
|
|
at = {r["where"]: r for r in truth}
|
|
return {
|
|
r: at[f"ResultadoSubrogado:{i}"]["person"]
|
|
for i, r in q("select id, _record from bronze.n__site__resultados")
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def site(tmp_path, site_women):
|
|
"""ISSSTELEON's test source (SQL Server, required: run with `docker compose run --rm
|
|
test`) holding the women's studies as its PDFs, its ground truth, the pipeline an
|
|
operator draws for it, and, for checking only, the true patient of each of its rows."""
|
|
url = create_database(os.environ["SITE_SQL_SERVER"], f"pruebas_{secrets.token_hex(6)}")
|
|
truth = build(site_women, url, tmp_path / "site")
|
|
return SimpleNamespace(
|
|
url=url,
|
|
truth=truth,
|
|
meta=json.loads((tmp_path / "site" / "truth.json").read_text()),
|
|
drawn=SITE_PIPELINE.read_text().replace("{database}", url),
|
|
concept_map=CONCEPT_MAPS / "erick_site.json",
|
|
patients=lambda q: _patients(q, truth),
|
|
)
|