CareSync turns unreliable weekly clinic file deliveries into a trusted Snowflake reporting database. A third-party data aggregation agent drops six CSV exports into a shared Google Drive folder on a contractual schedule, outside Nexora's control over timing or format. The pipeline senses each file under a one-hour SLA, runs it through a pandas pre-validation gate before ingestion, loads validated files into Snowflake with idempotent, content-hashed writes, transforms them with dbt into a single-fact star schema, and runs a post-validation gate that verifies the reporting layer actually reconciles. Files that fail validation are quarantined and their dependent datasets are skipped automatically via the FK dependency graph, not failed outright, and stakeholders get a Slack and email alert the moment it happens, not just a mention buried in the end-of-run summary. All data is synthetic, generated with Synthea.
Nexora's partner clinics don't deliver data directly. A third-party data aggregation agent consolidates each clinic's weekly export and delivers six CSV files into a shared Google Drive folder on a contractual schedule. Clinic operations reviews, provider workload planning, and payer reconciliation all run off the weekly CareSync reports, so the timeliness and correctness of these files directly affect operational decisions across the clinic network.
Because a third party sits in the delivery chain, Nexora controls neither when files arrive nor what condition they arrive in. Delivery times drift, export formats change when clinic systems are upgraded, and files can arrive truncated or malformed. The brief was to deliver trustworthy weekly reporting by ensuring that only validated data enters the warehouse, only verified data reaches stakeholders, and every quality event (a late file, a rejected file, a failed business check, or a successful run) is communicated automatically. Because this project is intended for development and testing, Nexora uses synthetic healthcare data generated with Synthea, an open-source synthetic patient generator, giving realistic records with no exposure of real patient information.
Most pipelines gate quality once, at ingestion. I split the gate in two: a pre-validation pass before any file reaches Snowflake (schema, mandatory fields, UUID format, allowed values, chronology, duplicate IDs, row-count bounds), and a post-validation pass after dbt builds the reporting layer (table existence, row-count floors, and three cross-layer reconciliation queries). Passing the first gate only proves the input was well-formed; it says nothing about whether the warehouse the business actually queries is correct. The project is also deliberately staged in two tooling phases: everything is first built and proven with pandas validation orchestrated by GitHub Actions, then productionized by replacing every pandas check with Great Expectations suites and replacing GitHub Actions with Airflow: prove the logic is right cheaply, then move it onto industrial-grade tooling without redesigning the pipeline shape.
The whole pipeline runs as a single Python orchestrator calling six stages in order: sense, validate, load, transform, verify, notify. A Google Drive sensor checks for six expected files under a one-hour SLA and classifies each as found, missing, empty, too early, or late. A pandas pre-validation gate runs seven checks per file (parseability, expected columns, mandatory field format, UUID format, allowed values, chronology, row-count bounds). Anything that fails gets physically moved into a quarantine folder and fires its own Slack/email alert immediately, not just a line in the end-of-run digest. Healthy files load into Snowflake's RAW layer with idempotent, content-hashed writes. dbt transforms RAW into a staging layer and then a single-fact-grain star schema. A post-validation gate checks table population and three cross-layer reconciliation queries, then every stage's outcome rolls up into one unified Slack and email run report.
The six source files have real foreign-key dependencies on each other: an encounter references a patient, organization, provider, and payer, and a condition references an encounter and a patient, so the loader processes them in strict dependency order and propagates failures downstream automatically: if a file fails validation, everything that depends on it is skipped, not failed, while everything unaffected still loads, and the failure itself is quarantined and alerted on the moment it's detected, not held back for the final report.
The pattern that matters here is separation of concerns. The sensor only knows about file arrival. Pre-validation only knows about per-file correctness. The loader only knows about getting bytes into Snowflake exactly once. dbt only knows about modeling. Post-validation only knows about whether the finished warehouse actually answers the business's questions. Each stage can fail or quarantine independently without the others needing to understand why.
sensor.py's docstring says it plainly: "DESIGNED FOR SWAPABILITY: All file-source logic is isolated. To swap → SFTP: replace ONLY the file-listing/timestamp section. SLA checks, reporting, alerts, and pipeline flow → ZERO changes." The Drive-specific code lives entirely behind two functions, fetch_source_files() and download_file(): a genuine interface boundary, not just a comment promising one. If Nexora's third-party agent ever moves from Google Drive to SFTP, only those two functions change.
NEXORA_RAW.HL7 holds six tables defined by explicit DDL, not inferred from the CSV headers: the loader's COPY INTO maps file columns positionally into whatever columns the DDL already declares, plus four tracking columns (SOURCE_FILE, BATCH_ID, FILE_HASH, LOADED_AT) added automatically if they don't already exist. dbt then builds a staging layer in NEXORA_STAGING that drops or masks PHI, standardizes enums, and casts types, followed by a four-dimension, two-fact mart in NEXORA_PROD.
NEXORA_RAW.HL7 (raw, positionally loaded, hash-deduplicated) ├── ORGANIZATIONS (1,127 rows) ├── PAYERS (10 rows) ├── PROVIDERS (5,056 rows) ├── PATIENTS (1,163 rows) ├── ENCOUNTERS (61,459 rows) └── CONDITIONS (38,094 rows) NEXORA_STAGING.DBT_YISMAIL_HL7_HL7 (dbt staging · PHI dropped/masked, types cast) ├── stg_hl7__organizations ├── stg_hl7__payers ├── stg_hl7__providers ├── stg_hl7__patients (SSN, DRIVERS, PASSPORT, FIRST, LAST never pass through) ├── stg_hl7__encounters └── stg_hl7__conditions NEXORA_PROD.DBT_YISMAIL_HL7_HL7 (dbt marts · single-fact-grain star schema) ├── dim_organizations ├── dim_payers ├── dim_providers ├── dim_patients (masked initials, age, age_group, region) ├── fct_appointments (grain: one row per encounter) └── fct_conditions (grain: one row per diagnosis)
The RAW→staging boundary is where privacy enforcement actually happens: SSN, DRIVERS, PASSPORT, FIRST, LAST, MAIDEN, and full street address never reach stg_hl7__patients at all: the staging model only selects the columns it needs, PHI columns are excluded by omission rather than deleted downstream. What stands in for a name is an initials-only patient_masked_name (e.g. J.S.), never a full surname.
| mart table | grain | notes |
|---|---|---|
| dim_patients | 1,163 rows | patient_id PK · masked initials, age / age_group (deceased patients aged as-of death), region, county |
| dim_providers | 5,056 rows | provider_id PK · FK → dim_organizations · specialty_category, caseload_level |
| dim_organizations | 1,127 rows | organization_id PK · revenue-based facility_size tier, utilization_level |
| dim_payers | 10 rows | payer_id PK · coverage_status, customer-count-based payer_size_tier |
| fct_appointments | 61,459 rows | grain = encounter · FK → all 4 dims · coverage_percentage, encounter_duration_minutes |
| fct_conditions | 38,094 rows | grain = diagnosis · FK → fct_appointments, dim_patients · condition_duration_days, is_active_condition |
The sensor doesn't just check whether a file exists: it classifies arrival time against the SLA window on both ends. A file that shows up before the scheduled drop is just as suspect as one that's late: both get quarantined from the current run rather than silently accepted, with a dedicated Slack/email alert either way.
if arrived < scheduled_time: early_files.append(name) entry["sla_met"] = False entry["status"] = "TOO EARLY" elif arrived > deadline_time: late_files.append(name) entry["sla_met"] = False entry["status"] = "LATE" else: ready_files.append((name, info)) entry["sla_met"] = True entry["status"] = "ON TIME"
The loader never truncates. Every file gets a SHA-256 hash of its filename plus its full byte content; before inserting, it checks whether that exact hash has already been loaded. Re-running the same week's file, intentionally or by a retriggered job, is a no-op, not a duplicate.
def compute_file_hash(file_path): hasher = hashlib.sha256() hasher.update(os.path.basename(file_path).encode("utf-8")) with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): hasher.update(chunk) return hasher.hexdigest() # before inserting from the temp table... cur.execute(f"SELECT COUNT(*) FROM {full_table} WHERE FILE_HASH = %s", (file_hash,)) if cur.fetchone()[0] > 0: logging.info(f"SKIP - {filename} already loaded") return 0 # FRESH, not LOADED: same content, no new rows
A file that fails pre-validation doesn't just get marked skipped in memory. It's physically moved out of the landing folder into a timestamped quarantine path, and its own Slack/email alert fires right there, independently of whatever else the run is still doing.
passed, issues, row_count = validate_file(source_path) if not passed: summary["pre_validation"]["quarantined"] += 1 # move the file out of landing/ and fire the alert now, # not only as a line in the end-of-run summary quarantine_file(source_path, issues, row_count)
If one file in the dependency graph fails pre-validation, everything downstream of it is skipped, not failed, not silently processed with bad data, and the reason is traceable back to exactly which upstream file caused it.
# Skip Reason 1: this file's own validation failed if filename in validated_results and not validated_results[filename]["passed"]: skip_status[filename] = f"SKIPPED: validation failed - {validated_results[filename]['issues']}" continue # Skip Reason 2: an upstream dependency was itself skipped skipped_deps = [dep for dep in deps if skip_status.get(f"{dep}.csv")] if skipped_deps: skip_status[filename] = f"SKIPPED: upstream skipped - {', '.join(skipped_deps)}" continue
Post-validation runs after dbt succeeds, and checks something dbt's own tests can't: not just "did the models build" but "does the finished warehouse actually reconcile." Three business-level queries run independently of dbt's generic tests: staging-to-fact row count parity, no future-dated encounters, and patient count consistency across staging and dim layers.
{
"name": "Encounter reconciliation - STAGING = FACT",
"query": f"""
SELECT
(SELECT COUNT(*) FROM NEXORA_STAGING.{STAGING_SCHEMA}.STG_HL7__ENCOUNTERS)
= (SELECT COUNT(*) FROM NEXORA_PROD.{PROD_SCHEMA}.FCT_APPOINTMENTS) AS reconciled
"""
}
A naive pipeline would abort the whole run if any one file failed validation. Instead, a failing file is physically quarantined, its own alert fires immediately, and only its dependents (via the real FK graph) are skipped; everything unaffected still loads. Tradeoff: more orchestration logic to track what depends on what. Gain: a bad payers.csv export doesn't block organizations from loading.
The loader never truncates the RAW tables. Every file gets a SHA-256 hash of its filename plus full byte content, checked against FILE_HASH before inserting. Tradeoff: extra hashing and a lookup query on every load. Gain: re-running the same week's file is a safe no-op, never a duplicate row.
The loader and validators connect via an RSA private key (cryptography's PKCS8 serialization), not a stored password. Tradeoff: key generation and rotation is more setup. Gain: no plaintext credential, and key-pair auth is Snowflake's own recommended pattern for service accounts.
The Google Drive-specific code lives entirely behind fetch_source_files() and download_file() in sensor.py. Tradeoff: a thin abstraction layer even though only one source exists today. Gain: when the agent moves to SFTP, only two functions change.
SSN, DRIVERS, PASSPORT, FIRST, LAST, MAIDEN are excluded by omission in stg_hl7__patients rather than loaded and filtered later. Tradeoff: a future PHI need must be deliberately re-added. Gain: PHI has nowhere downstream to leak from, by construction.
Validation and orchestration logic is built once with pandas checks and a GitHub Actions trigger, before being productionized onto Great Expectations and Airflow. Tradeoff: the first build isn't the final tool. Gain: the pipeline shape gets proven fast; the later swap is tooling, not redesign.
dbt's own generic tests run as part of dbt build, but post_validation.py runs separately with its own connection and reconciliation queries. Tradeoff: duplicated-looking checks, a second round-trip. Gain: a bug in the dbt project itself still gets caught.
The pipeline runs end-to-end in under 3 minutes against real Snowflake infrastructure. Every stage logs structured timestamps, and the full run (sensor through final notification) is captured below from an actual run on October 18, 2026.
All 6 files arrived on time and passed pre-validation. All 6 loaded to NEXORA_RAW with their exact source row counts. dbt built all 12 models and ran all 36 generic tests: PK uniqueness and not-null on every dimension and fact, relationship tests across every FK in the star schema, an accepted_values test on encounter_class, all without a single failure. Post-validation then independently re-verified table population and all three business reconciliation checks, and the unified run report went out over both Slack and email within seconds of the pipeline finishing. The marts layer has since picked up more PK/FK coverage and a singular grain test for fct_conditions, bringing the current suite to 38 dbt tests.
This run is Stage 1: pandas validation, GitHub Actions scheduling. Stage 2, the same validation rules re-expressed as Great Expectations suites, the same orchestration re-expressed as an Airflow DAG, is the deliberate next step, not a hypothetical. The pipeline shape (sense → validate → load → transform → verify → notify) and the swappable-interface discipline behind it are designed so that swap changes tooling, not architecture.
_tests.yml schema + test declarationsThe honest next step is Stage 2 of the roadmap already designed into this pipeline: Great Expectations replacing the hand-written pandas checks in pre-validation, and an Airflow DAG replacing the GitHub Actions cron trigger for real dependency-aware scheduling and retries; both slot into the same six-stage shape without a redesign. Beyond that: SCD Type 2 on dim_patients so address and provider changes retain history instead of being overwritten; incremental dbt models rather than full-table rebuilds as source volume grows; column-level encryption and query audit logging for genuine HIPAA posture, not just PHI minimization; and a thin BI layer on top of the star schema.
PHI is minimized by omission at the staging boundary and names are masked to initials, but there's no column-level encryption, no query audit logging, and no formal access control layer. That's PHI-conscious design, not HIPAA compliance: worth naming as scope, not oversight, especially since the data is synthetic Synthea output anyway.
Validation is hand-written pandas checks and orchestration is a GitHub Actions cron trigger. Both are deliberately designed to be swapped for Great Expectations and Airflow without reshaping the pipeline, but that swap hasn't happened yet.
Data quality is enforced at runtime by pre-validation and post-validation, but the sensor, loader, and orchestrator code itself has no pytest coverage. There's no CI-time check that a refactor of the cascade-skip logic or the SHA-256 dedup check still behaves correctly.
If a patient's region, county, or payer coverage changes between weekly loads, the previous value is overwritten. Real reporting often needs history. Adding SCD Type 2 would need effective-from/effective-to columns and updated load logic.
The pipeline expects one file set per week and quarantines what fails pre-validation. If a file is missed or quarantined, there's no automated reprocessing job: re-running means manually re-uploading to the source folder for the next scheduled run to pick up.
I'm currently looking for Data Engineer / Analytics Engineer roles. UK-based, open to remote or hybrid.
5-service Docker Compose stack, Airflow-orchestrated PySpark medallion pipeline, 3-table dimensional Gold layer.
read-case-studyCloud-native serverless ELT on GCP with Cloud Composer, Dataproc Serverless, GCS lakehouse, BigQuery warehouse.
read-case-studyDistributed PySpark ETL processing 1M synthetic banking transactions into a validated star schema.
read-case-study