Run every node kind: route, map, join, extract (LLM or patterns), link (Splink), target
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
"""A fresh platform per test, on SQLite and on PostgreSQL, and the way an operator runs it:
|
||||
save a pipeline, run the `ingest` job (each run in its own process, as Dagster does)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, make_url, text
|
||||
|
||||
|
||||
def run(env, *args):
|
||||
subprocess.run(args, env=env, check=True)
|
||||
|
||||
|
||||
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."""
|
||||
(tmp_path / "dagster").mkdir()
|
||||
env = {
|
||||
**os.environ,
|
||||
"ISSSTELEON_DATA": str(tmp_path),
|
||||
"DLT_DATA_DIR": str(tmp_path / "dlt"),
|
||||
"DAGSTER_HOME": str(tmp_path / "dagster"),
|
||||
}
|
||||
if request.param == "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 ("bronze", "silver")]
|
||||
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 ("bronze", "silver", "config"):
|
||||
con.exec_driver_sql(f"drop schema if exists {schema} 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),
|
||||
) # fmt: skip
|
||||
+7
-60
@@ -2,16 +2,11 @@
|
||||
the rules point at is read into text (scanned ones through OCR)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, make_url, text
|
||||
|
||||
from synthetic.site import build
|
||||
|
||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
||||
@@ -53,56 +48,8 @@ FILES = "dlt.sources.filesystem:filesystem"
|
||||
READERS = "dlt.sources.filesystem:readers"
|
||||
|
||||
|
||||
@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."""
|
||||
(tmp_path / "dagster").mkdir()
|
||||
env = {
|
||||
**os.environ,
|
||||
"ISSSTELEON_DATA": str(tmp_path),
|
||||
"DLT_DATA_DIR": str(tmp_path / "dlt"),
|
||||
"DAGSTER_HOME": str(tmp_path / "dagster"),
|
||||
}
|
||||
if request.param == "sqlite":
|
||||
url = env["PLATFORM_DATABASE_URL"] = f"sqlite:///{tmp_path / 'platform.db'}"
|
||||
attach = [f"ATTACH '{tmp_path}/platform__bronze.db' AS bronze"]
|
||||
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 ("bronze", "config"):
|
||||
con.exec_driver_sql(f"drop schema if exists {schema} 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 bronze.{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 env, count, query
|
||||
|
||||
|
||||
def run(env, *args):
|
||||
subprocess.run(args, env=env, check=True)
|
||||
|
||||
|
||||
def ingest(env):
|
||||
config = Path(env["ISSSTELEON_DATA"]) / "run.json"
|
||||
config.write_text(json.dumps({"ops": {"run_pipeline": {"config": {"pipeline": "site"}}}}))
|
||||
run(env, "dagster", "job", "execute", "-m", "models.definitions", "-j", "ingest",
|
||||
"--config", str(config)) # fmt: skip
|
||||
|
||||
|
||||
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path):
|
||||
env, count, query = platform
|
||||
count, query = platform.count, platform.query
|
||||
tables = {}
|
||||
for name in ("cacu", "cama"):
|
||||
shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db")
|
||||
@@ -111,7 +58,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
||||
tables[name] = [t for (t,) in found]
|
||||
truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"]
|
||||
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables)))
|
||||
run(env, "python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
|
||||
by_place = {}
|
||||
for r in truth:
|
||||
@@ -131,17 +78,17 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
||||
expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0]
|
||||
|
||||
def counts():
|
||||
return {node: count(f"n__site__{node}") for node in expected}
|
||||
return {node: count(f"bronze.n__site__{node}") for node in expected}
|
||||
|
||||
for _ in range(2): # loading the same site again changes nothing
|
||||
ingest(env)
|
||||
platform.ingest()
|
||||
assert counts() == expected
|
||||
read_once = query("select sha256, _dlt_load_id from bronze.read_cache order by sha256")
|
||||
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
||||
assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once
|
||||
|
||||
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
||||
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
||||
ingest(env)
|
||||
platform.ingest()
|
||||
assert counts() == expected
|
||||
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
||||
assert query(corrected) == [("64000",)]
|
||||
@@ -155,6 +102,6 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
||||
assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans
|
||||
if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly
|
||||
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
||||
assert query("select sha256, _dlt_load_id from bronze.read_cache order by sha256") == (
|
||||
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
||||
read_once
|
||||
) # reruns never read a file again
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust.
|
||||
|
||||
The site hides its answers the way real ones do: demographics split between a database
|
||||
and an Excel file with mistyped record numbers, reports as BLOBs in three layouts (some
|
||||
scanned), loose PDFs, a CSV of consultations, and contradicting copies of some reports.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from synthetic.site import build
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "messy_site.json"
|
||||
FIELDS = {
|
||||
"cervical_cytology": ("sample_date", "adequacy", "result", "hpv"),
|
||||
"cervical_biopsy": ("request_date", "histology"),
|
||||
}
|
||||
BOOLS = {"hpv"}
|
||||
|
||||
|
||||
def _value(field, v):
|
||||
if v is None:
|
||||
return None
|
||||
if field in BOOLS:
|
||||
return bool(v)
|
||||
return v.isoformat() if isinstance(v, date) else str(v)
|
||||
|
||||
|
||||
def test_a_messy_site_becomes_silver_with_no_wrong_value(platform, tmp_path):
|
||||
truth = build(HOSPITAL, tmp_path / "site")["records"]
|
||||
at = {r["where"]: r for r in truth}
|
||||
drawn = PIPELINE.read_text().replace("{site}", str(tmp_path / "site"))
|
||||
(tmp_path / "pipeline.json").write_text(drawn)
|
||||
platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
|
||||
platform.ingest()
|
||||
q = platform.query
|
||||
|
||||
# Which place in the site each record came from (only for checking against the truth).
|
||||
where = {
|
||||
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
|
||||
}
|
||||
where |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")}
|
||||
where |= {
|
||||
r: f"pacientes_his:{n}"
|
||||
for n, r in q("select num, _record from bronze.n__site__his_patients")
|
||||
}
|
||||
|
||||
# Nobody is merged with somebody else.
|
||||
patients_of: dict[str, set] = {}
|
||||
for record, person in q("select _record, person_id from bronze.n__site__persons"):
|
||||
if record in where:
|
||||
patients_of.setdefault(person, set()).add(at[where[record]]["person"])
|
||||
assert all(len(p) == 1 for p in patients_of.values()), patients_of
|
||||
patient = {person: next(iter(p)) for person, p in patients_of.items()}
|
||||
|
||||
# Every value accepted from a document is what the document says.
|
||||
for entity, fields in FIELDS.items():
|
||||
cols = ", ".join(fields)
|
||||
for record, held, *values in q(
|
||||
f"select _record, _held, {cols} from bronze.staged__{entity}"
|
||||
):
|
||||
t = at[where[record]]
|
||||
if held is None and not t.get("flipped"):
|
||||
got = {f: _value(f, v) for f, v in zip(fields, values, strict=True)}
|
||||
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
||||
|
||||
def silver(entity):
|
||||
fields = FIELDS[entity]
|
||||
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
||||
return {
|
||||
(patient[p], *(_value(f, v) for f, v in zip(fields, values, strict=True)))
|
||||
for p, *values in rows
|
||||
}
|
||||
|
||||
def expected(entity, keep):
|
||||
return {
|
||||
(r["person"], *(r["values"][f] for f in FIELDS[entity]))
|
||||
for r in truth
|
||||
if r["entity"] == entity and keep(r)
|
||||
}
|
||||
|
||||
# Contradicting reports stay out until a reviewer decides; everything else is in.
|
||||
assert silver("cervical_cytology") == expected(
|
||||
"cervical_cytology", lambda r: not r.get("conflict")
|
||||
)
|
||||
assert silver("cervical_biopsy") == expected("cervical_biopsy", lambda r: True)
|
||||
notes = q("select note_date, specialty, icd10 from silver.clinical_note")
|
||||
assert sorted(tuple(map(str, n)) for n in notes) == sorted(
|
||||
(r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"])
|
||||
for r in truth
|
||||
if r["entity"] == "clinical_note"
|
||||
)
|
||||
|
||||
# The reviewer rejects each wrong copy; the next run places the right value.
|
||||
wrong = [rec for rec, w in where.items() if at[w].get("flipped")]
|
||||
assert wrong
|
||||
reject = "; ".join(
|
||||
f"nodes.reject('cervical_cytology', {rec!r}, 'contradicts the original report', 'qa')"
|
||||
for rec in wrong
|
||||
)
|
||||
platform.run("python", "-c", f"from persistance import nodes; {reject}")
|
||||
platform.ingest()
|
||||
assert silver("cervical_cytology") == expected(
|
||||
"cervical_cytology", lambda r: not r.get("flipped")
|
||||
)
|
||||
Reference in New Issue
Block a user