Collect and unpack jobs; ingestion gate on SQLite and PostgreSQL

This commit is contained in:
Roberto Treviño
2026-11-24 17:48:18 -06:00
parent f1370d2776
commit 79a55a7a62
6 changed files with 296 additions and 91 deletions
+31 -31
View File
@@ -1,45 +1,45 @@
"""Dagster code location: every heavy step of the platform is an asset or job defined here."""
"""Dagster code location: every heavy step of the platform is a job defined here.
Ingestion jobs take the pipeline to run (and optionally its config version) as run config.
"""
import dagster as dg
import dlt
from dagster_dbt import DbtCliResource, dbt_assets
from dagster_dlt import DagsterDltResource, DagsterDltTranslator, dlt_assets
from dagster_dlt.translator import DltResourceTranslatorData
from models.dbt_project import dbt_project
from persistance.destination import platform
from persistance.sources.sample import sample_patients
from models import unpack
from persistance import collect, config_log
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
class BronzeKeys(DagsterDltTranslator):
"""Name dlt assets bronze/<table>, the key dbt's sources point at."""
def get_asset_spec(self, data: DltResourceTranslatorData) -> dg.AssetSpec:
spec = super().get_asset_spec(data)
return spec.replace_attributes(key=dg.AssetKey(["bronze", data.resource.table_name]))
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None
@dlt_assets(
dlt_source=sample_patients(),
dlt_pipeline=dlt.pipeline("sample", destination=platform(), dataset_name="bronze"),
group_name="ingest",
dagster_dlt_translator=BronzeKeys(),
)
def sample_ingest(context: dg.AssetExecutionContext, dlt: DagsterDltResource):
yield from dlt.run(context=context)
@dg.op
def collect_sources(context: dg.OpExecutionContext, config: PipelineRun) -> int:
version, pipeline = config_log.get(config.pipeline, config.version)
for source in pipeline.sources:
info = collect.run(source)
context.log.info(f"{source.name}: {info}")
return version
@dbt_assets(manifest=dbt_project.manifest_path)
def transforms(context: dg.AssetExecutionContext, dbt: DbtCliResource):
yield from dbt.cli(["build"], context=context).stream()
@dg.op
def unpack_items(context: dg.OpExecutionContext, config: PipelineRun) -> int:
version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(str(unpack.run(pipeline)))
return version
sample_job = dg.define_asset_job("sample", selection=dg.AssetSelection.all(), tags=WRITES)
@dg.job(tags=WRITES)
def collect_job():
collect_sources()
defs = dg.Definitions(
assets=[sample_ingest, transforms],
jobs=[sample_job],
resources={"dlt": DagsterDltResource(), "dbt": DbtCliResource(project_dir=dbt_project)},
)
@dg.job(tags=WRITES)
def unpack_job():
unpack_items()
defs = dg.Definitions(jobs=[collect_job, unpack_job])
+98
View File
@@ -0,0 +1,98 @@
"""Stage 2: read the columns the rules point the LLM at, into text.
MarkItDown reads every format it has a converter (or an installed plugin) for; a PDF with
no text layer is OCRed first with OCRmyPDF. Items are stored once per content hash, so the
same file in two places, or on a rerun, is read once.
"""
import hashlib
import io
import json
from concurrent.futures import ProcessPoolExecutor
from functools import cache
import dlt
import ocrmypdf
from markitdown import MarkItDown
from sqlalchemy import inspect, text
from core.pipeline import Pipeline
from persistance.destination import engine, platform
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
ITEM_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
"text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True},
}
@cache
def _reader() -> MarkItDown:
return MarkItDown()
def read(content: bytes) -> dict:
"""Text of one file, and whether OCR was needed. Unreadable files keep their error."""
try:
found = _reader().convert_stream(io.BytesIO(content)).text_content
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
if ocr:
out = io.BytesIO()
ocrmypdf.ocr(
io.BytesIO(content), out, language="spa", skip_text=True,
output_type="pdf", optimize=0, progress_bar=False, jobs=1,
) # fmt: skip
found = _reader().convert_stream(io.BytesIO(out.getvalue())).text_content
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - any unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def _refs(pipeline: Pipeline):
"""(raw table, column, row reference, content) for every cell an llm rule reads."""
with engine().connect() as con:
for rule in pipeline.rules:
if not rule.llm:
continue
collected = dlt.attach(f"collect_{rule.source}")
naming = collected.default_schema.naming
table = f"raw__{rule.source}__{naming.normalize_table_identifier(rule.table)}"
columns = collected.default_schema.get_table(table)["columns"]
key = [c for c, v in columns.items() if v.get("primary_key")] or ["_dlt_id"]
for column in map(naming.normalize_identifier, rule.llm):
rows = con.execute(text(f"select {', '.join(key)}, {column} from bronze.{table}"))
for *row_key, content in rows:
if content is not None:
yield table, column, json.dumps(row_key, default=str), bytes(content)
def run(pipeline: Pipeline, workers: int | None = None) -> dict:
refs, contents = [], {}
for table, column, row_ref, content in _refs(pipeline):
sha = hashlib.sha256(content).hexdigest()
refs.append({"raw_table": table, "column": column, "row_ref": row_ref, "sha256": sha})
contents[sha] = content
with engine().connect() as con:
if inspect(con).has_table("items", schema="bronze"):
for (sha,) in con.execute(text("select sha256 from bronze.items")):
contents.pop(sha, None)
with ProcessPoolExecutor(workers) as pool:
read_items = [
{"sha256": sha, **found}
for sha, found in zip(contents, pool.map(read, contents.values()), strict=True)
]
out = dlt.pipeline("unpack", destination=platform(), dataset_name="bronze")
out.run(
[
dlt.resource(
read_items, name="items", primary_key="sha256", write_disposition="merge",
columns=ITEM_COLUMNS,
),
dlt.resource(
refs, name="item_refs", write_disposition="merge",
primary_key=["raw_table", "column", "row_ref"],
),
]
) # fmt: skip
return {"refs": len(refs), "read": len(read_items)}
+8 -1
View File
@@ -3,7 +3,14 @@ name = "models"
version = "0.0.0"
description = "Dagster assets and jobs; one module per model."
requires-python = ">=3.12"
dependencies = ["core", "persistance", "dagster", "dagster-webserver", "dagster-dbt", "dagster-dlt", "mlflow-skinny"]
dependencies = [
"core",
"persistance",
"dagster",
"dagster-webserver",
"dagster-dbt",
"mlflow-skinny",
]
[build-system]
requires = ["uv_build>=0.12,<0.13"]
+159
View File
@@ -0,0 +1,159 @@
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
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"
SQL = "dlt.sources.sql_database:sql_database"
FILES = "dlt.sources.filesystem:filesystem"
def pipeline(tmp: Path) -> dict:
def sql(name, path):
return {"name": name, "source": SQL, "args": {"credentials": f"sqlite:///{path}"}}
def files(name, glob, **extra):
args = {"bucket_url": str(tmp / "site" / "files"), "file_glob": glob}
return {"name": name, "source": FILES, "args": args, **extra}
return {
"sources": [
sql("cacu", tmp / "hospital_cacu.db"),
sql("cama", tmp / "hospital_cama.db"),
sql("site", tmp / "site" / "site.db"),
files(
"notes", "*.csv", source="dlt.sources.filesystem:readers", resources=["read_csv"]
),
files("altas", "*.xlsx", then="persistance.readers:read_excel"),
files("pdfs", "*.pdf", then="persistance.readers:read_bytes"),
],
"rules": [
{"source": "site", "table": "ArchivosUni", "llm": ["Archivo"]},
{"source": "pdfs", "table": "filesystem", "llm": ["content"]},
],
}
@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)
OPS = {"collect_job": "collect_sources", "unpack_job": "unpack_items"}
def job(env, name):
config = Path(env["ISSSTELEON_DATA"]) / f"{name}.json"
config.write_text(json.dumps({"ops": {OPS[name]: {"config": {"pipeline": "site"}}}}))
run(
env,
"dagster",
"job",
"execute",
"-m",
"models.definitions",
"-j",
name,
"--config",
str(config),
)
def test_collect_and_unpack(platform, tmp_path):
env, count, query = platform
for db in ("hospital_cacu.db", "hospital_cama.db"):
shutil.copy(FIXTURES / db, tmp_path / db)
truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"]
(tmp_path / "pipeline.json").write_text(json.dumps(pipeline(tmp_path)))
run(env, "python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json"))
expected = {"raw__site__archivos_uni": 53, "raw__pdfs__filesystem": 8}
for name in ("cacu", "cama"):
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
tables = con.execute("select name from sqlite_master where type = 'table'")
for (table,) in tables.fetchall():
rows = con.execute(f"select count(*) from {table}").fetchone()[0]
expected[f"raw__{name}__{table}"] = rows
by_place = {}
for r in truth:
by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r)
expected |= {
"raw__site__pacientes_his": len(by_place["pacientes_his"]),
"raw__altas__filesystem": len(by_place["altas.xlsx"]),
"raw__notes__read_csv": len(by_place["consultas.csv"]),
}
for _ in range(2): # a rerun changes nothing
job(env, "collect_job")
assert {t: count(t) for t in expected} == expected
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a changed row updates
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
job(env, "collect_job")
assert count("raw__cacu__paciente") == expected["raw__cacu__paciente"]
changed = query("select pac_codigo_postal from bronze.raw__cacu__paciente where pac_id = 1")
assert changed == [("64000",)]
job(env, "unpack_job")
items = query(
"select i.text, i.ocr, i.error, r.raw_table, r.row_ref from bronze.items i "
"join bronze.item_refs r on r.sha256 = i.sha256"
)
assert len(items) == 53 + 8 and all(error is None for _, _, error, _, _ in items)
space = re.compile(r"\s+")
found = {(t, json.loads(ref)[0]): (space.sub(" ", txt), ocr) for txt, ocr, _, t, ref in items}
for r in by_place["ArchivosUni"]:
txt, ocr = found[("raw__site__archivos_uni", int(r["where"].split(":")[1]))]
assert bool(ocr) == r["scanned"]
if "record_number" in r["identity"]: # OCR included: the identifier reads back exactly
assert r["identity"]["record_number"] in txt, (r["where"], txt)
before = query("select sha256, _dlt_load_id from bronze.items order by sha256")
job(env, "unpack_job") # nothing new to read: no item is read or written again
assert query("select sha256, _dlt_load_id from bronze.items order by sha256") == before
-10
View File
@@ -1,10 +0,0 @@
import mlflow
def test_logs_a_run(tmp_path):
mlflow.set_tracking_uri(f"sqlite:///{tmp_path / 'mlflow.db'}")
with mlflow.start_run() as run:
mlflow.log_param("seed", 7)
mlflow.log_metric("auc", 0.5)
got = mlflow.get_run(run.info.run_id)
assert got.data.params == {"seed": "7"} and got.data.metrics == {"auc": 0.5}
-49
View File
@@ -1,49 +0,0 @@
import os
import subprocess
from pathlib import Path
import pytest
from sqlalchemy import create_engine, make_url, text
POSTGRES = os.environ.get("POSTGRES_TEST_URL") # set by CI's postgres job
HOSPITAL = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
PATIENTS = 312
@pytest.mark.parametrize(
"backend",
["sqlite", pytest.param("postgres", marks=pytest.mark.skipif(not POSTGRES, reason="no PG"))],
)
def test_sample_job_loads_and_reloads_without_duplicates(backend, tmp_path):
(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"),
"HOSPITAL_CACU_URL": f"sqlite:///{HOSPITAL}",
}
if backend == "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:
env.update(PLATFORM_DATABASE_URL=POSTGRES, DBT_TARGET="postgres")
url = make_url(POSTGRES).set(drivername="postgresql+psycopg2") # dlt's driver
attach = []
with create_engine(url).begin() as con:
con.exec_driver_sql("drop schema if exists bronze cascade")
con.exec_driver_sql("drop schema if exists silver cascade")
for _ in range(2): # each run in its own process, as the Dagster daemon launches them
subprocess.run(
["dagster", "job", "execute", "-m", "models.definitions", "-j", "sample"],
env=env,
check=True,
)
with create_engine(url).connect() as con:
for statement in attach:
con.exec_driver_sql(statement)
assert con.execute(text("select count(*) from bronze.patients")).scalar() == PATIENTS
assert (
con.execute(text("select count(*) from silver.cacu_patients")).scalar() == PATIENTS
)