Databases

OpenLineage Spark: PySpark ETL with Pandera and OpenMetadata

You have a PySpark job that turns a raw table into features, and a catalog that is supposed to know where every column came from. Most teams wire one side and forget the other. Either the job validates its data and nobody can see the lineage, or the catalog draws a graph of tables that nobody checked. We connect both here. A Pandera schema decides which rows are clean, a plain Spark filter sends the rest to a quarantine table, and the OpenLineage Spark listener reports both writes to OpenMetadata, which draws the table and column lineage from a single run.

Original content from computingforgeeks.com - post 189257

We built the whole chain on one lab VM with the German Credit dataset from UCI, 1,000 real loan applications, five of which are larger than the credit cap our rules allow. The job fails itself when too many rows land in quarantine, so a bad batch never reaches the features table. I confirmed the setup working on Ubuntu 26.04 with Spark 4.3, Pandera 0.36 and OpenMetadata 2.0.7 in November 2026.

Connect the quality gate to the catalog

Start with the handshake in the diagram. Spark reads raw.german_credit over JDBC, writes passing rows to credit_features and failing rows to credit_quarantine, and the listener posts an OpenLineage COMPLETE event for each write. The OpenMetadata ingestion container supplies the other half: the table entities those events attach to, and the data quality results.

PySpark ETL architecture: credit_etl.py reads raw.german_credit over JDBC, the Pandera gate writes passing rows to credit_features and failing rows to credit_quarantine, the OpenLineage Spark listener sends COMPLETE events to OpenMetadata, and the ingestion container sends tables and data quality results

Pandera and OpenLineage never talk to each other in this setup. Pandera has no OpenLineage integration, so the validation result lives in the job’s own output and in the quarantine table, while OpenMetadata learns about quality through its own test runner. We’ll wire both and show where they agree.

Check the lab host sizing

OpenMetadata is the heavy side of this pairing, not Spark. Its Docker Compose stack runs MySQL, Elasticsearch, the server and an ingestion container, and on our 16 GB VM it held about 4.6 GiB at idle before Spark started. Treat the lab numbers below as a floor for a single developer, and size production around the drivers in the last column.

ResourceLab floor (tested)What drives it up
vCPU4Spark executor cores, concurrent ingestion workflows
RAM16 GB (OpenMetadata idle about 4.6 GiB)Elasticsearch heap, OpenMetadata heap, Spark driver and executor memory
Disk60 GBElasticsearch indices, MySQL entity history, Docker images (several GB)
OSUbuntu 26.04 LTSAny distro with Java 17 or 21 and Docker Compose v2

In production you would run OpenMetadata on its own host or on Kubernetes with an external MySQL or PostgreSQL and a managed search cluster, then point Spark at it over HTTPS. Keeping them on one box here makes the round trip easy to watch, which is the point of the exercise.

Install Java, Docker and uv on the Spark host

Spark runs on the JVM, OpenMetadata ships as containers, and uv builds the Python environment far faster than pip. Install all three from the Ubuntu archive and Astral’s installer. If you’d rather run a standalone Spark cluster than the pip package, our guide to installing Apache Spark on Ubuntu and Debian covers that route.

sudo apt-get update
sudo apt-get install -y openjdk-21-jdk-headless docker.io docker-compose-v2 python3-venv jq
sudo usermod -aG docker $USER
curl -LsSf https://astral.sh/uv/install.sh | sh

Log out and back in so the docker group membership and the uv path apply to your shell. Then confirm each tool answers:

uv --version; java -version 2>&1 | head -1; docker --version; docker compose version

Our host reported these versions:

uv 0.13.7 (x86_64-unknown-linux-gnu)
openjdk version "21.0.13.0.3" 2026-10-24
Docker version 29.1.3, build 29.1.3-0ubuntu4.1
Docker Compose version 2.40.3+ds1-0ubuntu1

Java 21 matters here. Spark 4 dropped Java 8 and 11, and we add one --add-opens JVM flag in the session config later to keep the listener clear of reflective access errors on newer JDKs. Java 17 and 25 are also supported by Spark 4.3 if your fleet standardizes on one of them.

Start OpenMetadata and a PostgreSQL warehouse

Start on the catalog side. OpenMetadata publishes a Docker Compose file with every release, so we fetch the tag of the latest release from the GitHub API and pull the matching file instead of pinning a version by hand.

mkdir -p ~/openmetadata && cd ~/openmetadata
OM_VER=$(curl -s https://api.github.com/repos/open-metadata/OpenMetadata/releases/latest | grep tag_name | cut -d '"' -f 4)
echo $OM_VER
curl -sLO https://github.com/open-metadata/OpenMetadata/releases/download/${OM_VER}/docker-compose.yml
time docker compose -f docker-compose.yml up --detach

The first start pulls several GB of images and runs the database migrations before the server comes up. Ours took close to five minutes, and the tail of the output shows the migration container exiting before the server and ingestion containers start:

2.0.7-release
...
 Container openmetadata_mysql  Healthy
 Container openmetadata_elasticsearch  Healthy
 Container execute_migrate_all  Exited
 Container openmetadata_server  Starting
 Container openmetadata_server  Started
 Container openmetadata_mysql  Waiting
 Container openmetadata_mysql  Healthy
 Container openmetadata_ingestion  Starting
 Container openmetadata_ingestion  Started

real	4m47.057s
user	0m0.933s
sys	0m0.493s

Ask the server for its version once the containers settle. A JSON answer on port 8585 means the API that Spark will post to is listening:

curl -s http://localhost:8585/api/v1/system/version

Expect a different revision hash on every build. The version itself should match the tag you pulled.

{"version":"2.0.7","revision":"744c5236bf840e131f091614450a7e892f877382","timestamp":1793085754273}

Here’s where the memory goes. We checked it with docker stats right after startup, because this is the number that decides whether Spark still has room on the same host:

docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"

Elasticsearch and the ingestion container are the two biggest consumers, together close to 3 GB. The whole catalog idles near 4.6 GiB, which leaves roughly 11 GiB of this 16 GB host for the Spark driver and its Python workers.

NAME                         CPU %     MEM USAGE / LIMIT
openmetadata_ingestion       4.69%     1.407GiB / 15.61GiB
openmetadata_server          9.06%     1.039GiB / 15.61GiB
openmetadata_mysql           13.55%    571.1MiB / 15.61GiB
openmetadata_elasticsearch   6.51%     1.565GiB / 15.61GiB

Now the warehouse. We run PostgreSQL as a container on the Compose network openmetadata_app_net, so the ingestion container can reach it by the name warehouse while Spark on the host reaches it on localhost:5432. That split shows up again later, because OpenLineage reports the address Spark used and OpenMetadata knows the address its connector used.

docker run -d --name warehouse --network openmetadata_app_net -p 127.0.0.1:5432:5432 \
  -e POSTGRES_USER=etl -e POSTGRES_PASSWORD=EtlPass2026 -e POSTGRES_DB=credit \
  -v warehouse_data:/var/lib/postgresql postgres:18

Since version 18, the PostgreSQL image keeps its data under /var/lib/postgresql rather than the old /data subdirectory, so the volume mounts one level higher than older guides show. On the first start the container spends a few seconds in initdb, so wait until docker exec warehouse pg_isready -h 127.0.0.1 -U etl reports accepting connections. The TCP check matters, because the temporary server initdb starts listens only on the Unix socket. Then create the two schemas the job uses, one for the source data and one for its outputs:

docker exec warehouse psql -U etl -d credit -c "CREATE SCHEMA raw; CREATE SCHEMA analytics;"

Both sides of the handshake now exist: a catalog listening on 8585 and a database that Spark and the ingestion container can each reach by their own route.

Build the PySpark environment and fetch the data

The job runs from a uv virtual environment on Python 3.13. Pin PySpark and Pandera to the versions you tested, because the Pandera Spark backend reaches into PySpark internals and a minor bump on either side can change behaviour.

mkdir -p ~/credit-etl && cd ~/credit-etl
uv venv --python 3.13
source .venv/bin/activate
# https://pypi.org/project/pyspark/ and https://pypi.org/project/pandera/
uv pip install "pyspark==4.3.0" "pandera[pyspark]==0.36.0"

Left alone, uv resolves pandas 3.x, and that combination breaks on import. PySpark prints a FutureWarning that it does not fully support pandas 3 yet, and pyspark.pandas, which Pandera loads, then fails on DateOffset (the full error is in the troubleshooting section). Pin pandas below 3 in the same environment and print the versions.

uv pip install "pandas<3"
python -c "import pyspark,pandera,pandas,pyarrow;print(pyspark.__version__,pandera.__version__,pandas.__version__,pyarrow.__version__)"

Check that the third number, pandas, now starts with 2. A 3.x there means the pin did not take, and Pandera will fail on its first import.

4.3.0 0.36.0 2.3.3 26.0.1

Download the Statlog (German Credit Data) dataset from the UCI repository, published under CC BY 4.0 by Hans Hofmann, and unpack it under data/raw. It’s a space separated file with coded categories such as A43 for radio and TV purchases, which gives the job something real to decode:

mkdir -p data/raw && cd data/raw
curl -sLO https://archive.ics.uci.edu/static/public/144/statlog+german+credit+data.zip
python3 -c "import zipfile; zipfile.ZipFile('statlog+german+credit+data.zip').extractall()"
wc -l german.data
cd ~/credit-etl

A count of 1,000 lines means the full file arrived. The quarantine ratio later divides by that total, so a truncated download would quietly skew the gate.

1000 german.data

Every Python file below lives in ~/credit-etl, and every command runs from there with the virtual environment active. Running .venv/bin/python without activating it is the quickest way to hit a Python version mismatch between the Spark driver and its workers.

Point the OpenLineage Spark listener at OpenMetadata

On the Spark side of the handshake, everything is session config. The listener ships as a Maven artifact, io.openlineage:openlineage-spark_2.13, and Spark 4 builds only for Scala 2.13, so the _2.12 jar from older guides will not load. That includes OpenMetadata’s own Spark lineage example, which is written for Spark 3.x with openlineage-spark_2.12:1.37.0, while the OpenLineage Spark page only names Spark 3.* alongside “latest Spark versions”. The run below is the measured Spark 4.3 case. Spark resolves it through Ivy at startup when it’s listed in spark.jars.packages.

Spark authenticates to OpenMetadata with a bot’s JWT, so the first job is to fetch one from the UI:

  1. Log in at http://localhost:8585 as [email protected] with password admin, and change that password on any shared host.
  2. Open Settings, then Bots, then ingestion-bot.
  3. Copy the JWT token shown on the bot page.

The bot page looks like this in OpenMetadata, with the token masked here and its expiry shown underneath as No expiration. Spark will send that value as its API key on every event it posts.

OpenMetadata ingestion-bot page with the JWT token field and the no expiration notice, the token Spark sends as its OpenLineage API key
  1. 1JWT token
  2. 2No expiration

By default the ingestion-bot token never expires, which is convenient in a lab and a liability anywhere else. For a shared catalog, create a dedicated bot for lineage with a set expiry so revoking it does not break your metadata ingestion. Save the token to a file only your user can read.

vim ~/.om_bot_jwt

Paste the token as the only line, save, then lock the file down and export the three values the scripts read:

chmod 600 ~/.om_bot_jwt
export WAREHOUSE_PASSWORD=EtlPass2026 OM_URL=http://localhost:8585
export OM_BOT_JWT=$(cat ~/.om_bot_jwt)

Every script builds its Spark session from one module, so the OpenLineage config lives in exactly one place. Create it:

vim ~/credit-etl/session.py

Add the session builder below. The PostgreSQL JDBC driver rides in the same package list as the listener:

import os

from pyspark.sql import SparkSession

PACKAGES = ",".join([
    "io.openlineage:openlineage-spark_2.13:1.55.0",
    "org.postgresql:postgresql:42.7.14",
])

JDBC_URL = "jdbc:postgresql://localhost:5432/credit"
JDBC_PROPS = {
    "user": "etl",
    "password": os.environ["WAREHOUSE_PASSWORD"],
    "driver": "org.postgresql.Driver",
}


def build_session(app_name: str) -> SparkSession:
    return (
        SparkSession.builder.appName(app_name)
        .config("spark.jars.packages", PACKAGES)
        .config("spark.driver.extraJavaOptions", "--add-opens=java.base/java.security=ALL-UNNAMED")
        .config("spark.extraListeners", "io.openlineage.spark.agent.OpenLineageSparkListener")
        .config("spark.openlineage.transport.type", "http")
        .config("spark.openlineage.transport.url", os.environ["OM_URL"])
        .config("spark.openlineage.transport.endpoint", "/api/v1/openlineage/lineage")
        .config("spark.openlineage.transport.auth.type", "api_key")
        .config("spark.openlineage.transport.auth.apiKey", os.environ["OM_BOT_JWT"])
        .config("spark.openlineage.namespace", "credit_etl")
        .config("spark.openlineage.parentJobName", "german_credit")
        .getOrCreate()
    )

Each OpenLineage key has one job, and two of them decide names you’ll see in OpenMetadata later. The table maps them:

Spark config keyValue hereWhy it matters
spark.extraListenersOpenLineageSparkListenerHooks the listener into every job in the session
spark.openlineage.transport.url + endpointOM_URL + /api/v1/openlineage/lineageOpenMetadata’s route differs from the transport default /api/v1/lineage
transport.auth.type / auth.apiKeyapi_key / bot JWTSent as a Bearer token
spark.openlineage.namespacecredit_etlFirst half of the pipeline name in OpenMetadata
spark.app.name (via appName)german_credit_featuresSecond half: the pipeline becomes credit_etl-german_credit_features
spark.driver.extraJavaOptions--add-opens=java.base/java.security=ALL-UNNAMEDLets the listener reflect into JDK classes on Java 17 and 21
spark.openlineage.parentJobNamegerman_creditLabels the run; if an orchestrator also passes parentRunId and parentJobNamespace, OpenMetadata can resolve a different pipeline name

People miss the endpoint row more than any other. OpenLineage’s HTTP transport defaults to /api/v1/lineage, which is Marquez’s route, so without the explicit endpoint the listener posts to OpenMetadata’s native lineage API, which expects a different request body. The events are rejected and you get no lineage and no obvious error on the Spark side. The OpenLineage Spark transport reference lists the other keys, including file and Kafka transports for debugging.

Load the raw table over JDBC

Your source data has to live in a table OpenMetadata can catalog. A CSV path reported by OpenLineage has no table identifier, so OpenMetadata cannot attach lineage to it. A short loader reads the file, names the 21 columns from the dataset’s documentation and writes raw.german_credit.

vim ~/credit-etl/load_raw.py

Add the loader:

from session import JDBC_PROPS, JDBC_URL, build_session

COLUMNS = [
    "checking_status", "duration_months", "credit_history", "purpose",
    "credit_amount", "savings_status", "employment_since", "installment_rate",
    "personal_status", "other_debtors", "residence_since", "property",
    "age_years", "other_installment_plans", "housing", "existing_credits",
    "job", "num_dependents", "telephone", "foreign_worker", "class",
]

spark = build_session("german_credit_load_raw")

raw = (
    spark.read.option("sep", " ").option("inferSchema", "true")
    .csv("data/raw/german.data")
    .toDF(*COLUMNS)
)
raw.write.jdbc(JDBC_URL, "raw.german_credit", mode="overwrite", properties=JDBC_PROPS)
print(f"raw.german_credit rows written: {raw.count()}")
spark.stop()

Run it. The first run downloads the listener and JDBC jars into ~/.ivy2.5.2, so expect a page of Ivy resolution output before Spark starts:

python3 load_raw.py

Past the Ivy lines and a long WARN from SparkOpenLineageExtensionVisitorWrapper about illegal reflective access, the last line is the one to check:

	io.openlineage#openlineage-spark_2.13;1.55.0 from central in [default]
	org.checkerframework#checker-qual;3.55.1 from central in [default]
	org.postgresql#postgresql;42.7.14 from central in [default]
...
26/11/12 11:50:29 WARN SparkOpenLineageExtensionVisitorWrapper: An illegal reflective access operation will occur when using the openlineage-spark integration with a Spark connector that implements spark-openlineage extension interfaces.
...
raw.german_credit rows written: 1000

Treat that WARN as informational. It describes a classloader clash with Spark connectors that implement OpenLineage extension interfaces, and the JDBC source used here does not, so it is safe to ignore. If you later add a connector that does, load it the same way as the listener so both share a classloader.

Write the Pandera schema and the quarantine filter

Now the quality side. Pandera’s PySpark backend validates a Spark DataFrame against a typed model, but it doesn’t split rows for you. Validation returns the same DataFrame with an errors report attached, and filtering the bad rows out is your job. So we keep the rule bounds in one dictionary and build both the Pandera model and the Spark filter from it, which stops the two from drifting apart.

vim ~/credit-etl/quality.py

Add the schema and the split function:

from functools import reduce

import pyspark.sql.functions as F
import pyspark.sql.types as T
from pandera.pyspark import DataFrameModel, Field

# One source of truth: the Pandera schema and the quarantine filter both read these.
RANGES = {
    "duration_months": (4, 72),
    "credit_amount": (250, 15000),
    "age_years": (18, 75),
    "installment_rate": (1, 4),
}
PURPOSES = [
    "car_new", "car_used", "furniture", "radio_tv", "appliances", "repairs",
    "education", "retraining", "business", "other",
]
RISK = ["good", "bad"]


class CreditFeatures(DataFrameModel):
    duration_months: T.IntegerType() = Field(ge=RANGES["duration_months"][0], le=RANGES["duration_months"][1])
    credit_amount: T.IntegerType() = Field(ge=RANGES["credit_amount"][0], le=RANGES["credit_amount"][1])
    age_years: T.IntegerType() = Field(ge=RANGES["age_years"][0], le=RANGES["age_years"][1])
    installment_rate: T.IntegerType() = Field(ge=RANGES["installment_rate"][0], le=RANGES["installment_rate"][1])
    purpose: T.StringType() = Field(isin=PURPOSES)
    credit_risk: T.StringType() = Field(isin=RISK)
    monthly_installment: T.DoubleType() = Field(gt=0)

    class Config:
        name = "credit_features"
        strict = False


def rule_columns():
    """Each check as a Spark boolean column, named so quarantined rows say why."""
    rules = {f"{c}_in_range": F.col(c).between(lo, hi) for c, (lo, hi) in RANGES.items()}
    rules["purpose_known"] = F.col("purpose").isin(PURPOSES)
    rules["credit_risk_known"] = F.col("credit_risk").isin(RISK)
    rules["monthly_installment_positive"] = F.col("monthly_installment") > 0
    # NULL fails a rule instead of slipping through the filter
    return {name: F.coalesce(cond, F.lit(False)) for name, cond in rules.items()}


def split_clean_quarantine(df):
    rules = rule_columns()
    passes = reduce(lambda a, b: a & b, rules.values())
    failed = F.array_compact(F.array(*[F.when(~c, F.lit(n)) for n, c in rules.items()]))
    clean = df.filter(passes)
    quarantine = df.filter(~passes).withColumn("failed_rules", F.array_join(failed, ","))
    return clean, quarantine

Two details in rule_columns() carry the weight. The coalesce to false matters because a Spark comparison against NULL returns NULL, and both filter(cond) and filter(~cond) drop NULL rows, so without it a row with a missing amount vanishes from both tables. The failed_rules column then lists every rule a row broke, which turns the quarantine table into something an analyst can triage without rerunning the job.

Setting strict = False lets the model check the seven columns that carry rules while the DataFrame keeps its other columns, such as checking_status and housing. Keep it strict only if you want Pandera to reject unexpected columns.

Make the job fail above a quarantine ratio

Now the ETL script ties the pieces together. It reads the raw table, decodes the categories, derives monthly_installment, validates, splits and decides. A few bad rows are normal in loan data, so the gate is a ratio, not zero tolerance. Below the limit the clean rows ship; above it the job exits non-zero and the features table keeps its previous contents.

vim ~/credit-etl/credit_etl.py

Add the job:

import json
import os
import sys

import pyspark.sql.functions as F

from quality import CreditFeatures, split_clean_quarantine
from session import JDBC_PROPS, JDBC_URL, build_session

MAX_QUARANTINE_RATIO = float(os.environ.get("MAX_QUARANTINE_RATIO", "0.05"))

PURPOSE = {"A40": "car_new", "A41": "car_used", "A42": "furniture", "A43": "radio_tv",
           "A44": "appliances", "A45": "repairs", "A46": "education", "A48": "retraining",
           "A49": "business", "A410": "other"}
CHECKING = {"A11": "negative", "A12": "under_200", "A13": "200_plus", "A14": "none"}
HOUSING = {"A151": "rent", "A152": "own", "A153": "free"}


def decode(col, mapping):
    return F.create_map(*[F.lit(x) for kv in mapping.items() for x in kv])[F.col(col)]


spark = build_session("german_credit_features")

raw = spark.read.jdbc(JDBC_URL, "raw.german_credit", properties=JDBC_PROPS)

features = raw.select(
    decode("checking_status", CHECKING).alias("checking_status"),
    F.col("duration_months").cast("int"),
    decode("purpose", PURPOSE).alias("purpose"),
    F.col("credit_amount").cast("int"),
    F.col("installment_rate").cast("int"),
    F.col("age_years").cast("int"),
    decode("housing", HOUSING).alias("housing"),
    F.col("existing_credits").cast("int"),
    F.round(F.col("credit_amount") / F.col("duration_months"), 2).alias("monthly_installment"),
    F.when(F.col("class") == 1, "good").otherwise("bad").alias("credit_risk"),
)

validated = CreditFeatures.validate(check_obj=features)
# Read errors now: later DataFrame operations can reset df.pandera.errors.
errors = json.loads(json.dumps(validated.pandera.errors))
print(json.dumps(errors, indent=2))

clean, quarantine = split_clean_quarantine(features)
total, bad = features.count(), quarantine.count()
ratio = bad / total
print(f"rows={total} clean={total - bad} quarantined={bad} ratio={ratio:.3f}")

quarantine.write.jdbc(JDBC_URL, "analytics.credit_quarantine", mode="overwrite", properties=JDBC_PROPS)

if ratio > MAX_QUARANTINE_RATIO:
    print(f"quality gate FAILED: {ratio:.1%} quarantined, limit {MAX_QUARANTINE_RATIO:.1%}")
    spark.stop()
    sys.exit(1)

clean.write.jdbc(JDBC_URL, "analytics.credit_features", mode="overwrite", properties=JDBC_PROPS)
print("quality gate passed: analytics.credit_features written")
spark.stop()

Read validated.pandera.errors straight after validate() and copy it out, as the script does. The report hangs off that DataFrame object, and once you derive new DataFrames from it the attribute can come back empty, which reads like a clean batch when it isn’t. The quarantine write also comes before the gate on purpose: when the job fails, the rows that caused it are already sitting in a table for someone to look at.

Run it twice: once with the default 5% limit, then with a limit of 0.1% to prove the failure path. The echo shows the exit code a scheduler such as Airflow would see:

python3 credit_etl.py; echo "exit code: $?"
MAX_QUARANTINE_RATIO=0.001 python3 credit_etl.py; echo "exit code: $?"

Both runs find the same five rows over the 15,000 credit cap. Only the limit differs, so the first run writes the features table and the second stops with exit code 1:

Terminal output of credit_etl.py showing Pandera errors for credit_amount, 995 clean and 5 quarantined rows, the gate passing with exit code 0 and failing with exit code 1 at a 0.1 percent limit

Pandera’s report says which check broke (less_than_or_equal_to(15000) on credit_amount) but not which rows, because the Spark backend reports at column level. That is why the row split comes from our own filter. Query the quarantine table to see which rows they were.

docker exec warehouse psql -U etl -d credit \
  -c "SELECT duration_months, purpose, credit_amount, age_years, credit_risk, failed_rules FROM analytics.credit_quarantine ORDER BY credit_amount DESC;" \
  -c "SELECT count(*) FROM analytics.credit_features;"

All five carry a single failed rule, and the features table holds the 995 rows from the passing run. Two of the five are labelled good credit, so the rule is catching oversized loans rather than bad borrowers, and that is a call for the data owner, not the pipeline.

 duration_months | purpose  | credit_amount | age_years | credit_risk |      failed_rules
-----------------+----------+---------------+-----------+-------------+------------------------
              48 | other    |         18424 |        32 | bad         | credit_amount_in_range
              54 | business |         15945 |        58 | bad         | credit_amount_in_range
              36 | other    |         15857 |        43 | good        | credit_amount_in_range
              48 | business |         15672 |        23 | bad         | credit_amount_in_range
              60 | radio_tv |         15653 |        21 | good        | credit_amount_in_range
(5 rows)

 count
-------
   995
(1 row)

Notice that two of the five are good loans. The 15,000 cap is a business rule, not a fact about bad data, which is exactly why these rows belong in quarantine for a human to review rather than in the bin. If you get the setting wrong in the other direction, the gate fires on every run and people learn to ignore it.

Create the warehouse and lineage services in OpenMetadata

Back on the catalog side. The listener already posted events for those runs, but OpenMetadata had nothing to attach them to, so the server log filled with resolver warnings. OpenMetadata only draws lineage between table entities it knows. The wiring order is what makes it work:

  1. Create an OpenLineage pipeline service and a Postgres database service named warehouse.
  2. Map the OpenLineage namespace postgres://localhost:5432 to that service in the OpenLineage settings (admin token required).
  3. Ingest the warehouse metadata so the three tables exist as entities.
  4. Create the pipeline entity credit_etl-german_credit_features, then rerun the Spark job.

Steps 3 and 4 exist because of an auto-create bug we hit in this release: with autoCreateEntities on, the server still failed to create the pipeline and the output tables with Column 'updatedAt' cannot be null. Creating them ahead of the run sidesteps it. Start with the pipeline service:

curl -s -X POST http://localhost:8585/api/v1/services/pipelineServices \
  -H "Authorization: Bearer ${OM_BOT_JWT}" -H "Content-Type: application/json" \
  -d '{"name": "openlineage", "serviceType": "OpenLineage"}' | jq '{name, serviceType, fullyQualifiedName}'

The reply confirms the service type:

{
  "name": "openlineage",
  "serviceType": "OpenLineage",
  "fullyQualifiedName": "openlineage"
}

Your database service needs a connection the ingestion container can use, which is the container name warehouse, not localhost. Put it in a file.

vim ~/credit-etl/warehouse-service.json

Add the Postgres connection:

{
  "name": "warehouse",
  "serviceType": "Postgres",
  "connection": {
    "config": {
      "type": "Postgres",
      "hostPort": "warehouse:5432",
      "username": "etl",
      "authType": {"password": "EtlPass2026"},
      "database": "credit"
    }
  }
}

Then post it:

curl -s -X POST http://localhost:8585/api/v1/services/databaseServices \
  -H "Authorization: Bearer ${OM_BOT_JWT}" -H "Content-Type: application/json" \
  -d @warehouse-service.json | jq '{name, serviceType, hostPort: .connection.config.hostPort}'

OpenMetadata stores the password encrypted and echoes back the host:

{
  "name": "warehouse",
  "serviceType": "Postgres",
  "hostPort": "warehouse:5432"
}

Now map the two addresses onto each other. Spark reports its datasets under the namespace postgres://localhost:5432, taken from the JDBC URL, and the setting below tells OpenMetadata that namespace means the warehouse service. Save the settings document:

vim ~/credit-etl/openlineage-settings.json

Add the OpenLineage settings:

{
  "config_type": "openLineageSettings",
  "config_value": {
    "enabled": true,
    "autoCreateEntities": true,
    "defaultPipelineService": "openlineage",
    "namespaceToServiceMapping": {
      "postgres://localhost:5432": "warehouse"
    }
  }
}

System settings need an admin, and the bot token gets a 403 here. Log in as admin for a short lived token (the login API expects the password base64 encoded) and apply the file with it. Swap admin inside printf for the new password if you changed it after the first login:

ADMIN_TOKEN=$(curl -s -X POST http://localhost:8585/api/v1/users/login \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"[email protected]\", \"password\": \"$(printf admin | base64)\"}" | jq -r .accessToken)
curl -s -X PUT http://localhost:8585/api/v1/system/settings \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" -H "Content-Type: application/json" \
  -d @openlineage-settings.json -o /dev/null -w 'HTTP %{http_code}\n'
curl -s http://localhost:8585/api/v1/system/settings/openLineageSettings \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq .config_value

A 200 and the stored value with the server’s defaults filled in mean the mapping is live:

HTTP 200
{
  "enabled": true,
  "autoCreateEntities": true,
  "eventTypeFilter": [],
  "ownershipUpdateMode": "replace",
  "defaultPipelineService": "openlineage",
  "namespaceToServiceMapping": {
    "postgres://localhost:5432": "warehouse"
  }
}

Next, ingest the tables. The ingestion container already has the metadata CLI, so we hand it a workflow file that reads the raw and analytics schemas and skips the rest:

vim ~/credit-etl/warehouse-ingest.yaml

Add the workflow. The JWT stays a placeholder that the CLI expands from the environment:

source:
  type: postgres
  serviceName: warehouse
  sourceConfig:
    config:
      type: DatabaseMetadata
      schemaFilterPattern:
        includes:
          - raw
          - analytics
sink:
  type: metadata-rest
  config: {}
workflowConfig:
  openMetadataServerConfig:
    hostPort: http://openmetadata-server:8585/api
    authProvider: openmetadata
    securityConfig:
      jwtToken: ${OM_BOT_JWT}

Copy it into the container and run it, passing the token through as an environment variable:

docker cp warehouse-ingest.yaml openmetadata_ingestion:/tmp/warehouse-ingest.yaml
docker exec -e OM_BOT_JWT openmetadata_ingestion metadata ingest -c /tmp/warehouse-ingest.yaml

The run opens with a SQL error about pg_stat_statements, which only means query history isn’t available, and ends with the summary. Six records processed are the database, the two schemas and the three tables; the two filtered are public and information_schema:

[2026-11-12 11:51:51] INFO     {metadata.Ingestion:runner:105} - Test connection for 'Postgres': Successful
[2026-11-12 11:51:51] WARNING  {metadata.Metadata:test_connections:236} - You might be missing metadata in: GetQueries due to None
[2026-11-12 11:51:52] INFO     {metadata.Ingestion:common_db_source:163} - Ingesting from database: credit
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Workflow Postgres Summary:
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Processed records: 6
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Updated records: 0
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Warnings: 0
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Filtered: 2
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Errors: 0
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Success %: 100.0
...
[2026-11-12 11:51:53] INFO     {metadata.Utils:logger:223} - Workflow finished in time: 2s 121.452ms

Last, create the pipeline entity under the openlineage service. Its name has to be the namespace and the Spark app name joined by a hyphen, because that’s the name OpenMetadata derives from each event:

curl -s -X POST http://localhost:8585/api/v1/pipelines \
  -H "Authorization: Bearer ${OM_BOT_JWT}" -H "Content-Type: application/json" \
  -d '{"name": "credit_etl-german_credit_features", "service": "openlineage"}' \
  | jq '{name, fullyQualifiedName}'

Lineage edges will point at the fully qualified name in this reply. OpenMetadata matches each incoming event on that name, so it has to equal the namespace and the app name joined by a hyphen, character for character.

{
  "name": "credit_etl-german_credit_features",
  "fullyQualifiedName": "openlineage.credit_etl-german_credit_features"
}

If you rename the Spark app or the namespace later, create a matching pipeline entity before the next run or the events land nowhere. The Spark job still exits 0 in that case, because the listener posts asynchronously, which is what makes this mistake easy to miss.

Run the job again and trace the lineage end to end

With every entity in place, run the job again with the default limit. Nothing changes on the Spark side; this time the COMPLETE events for both writes resolve to tables OpenMetadata knows:

python3 credit_etl.py; echo "exit code: $?"

Open raw.german_credit in the OpenMetadata UI and switch to its Lineage tab. The node on the left is the input: raw.german_credit, and it fans out to both outputs. Each pipeline edge carries the name of the Spark job that produced it, so you can tell at a glance which run wrote which table:

OpenMetadata lineage view of raw.german_credit with pipeline edges to credit_features and credit_quarantine created by the OpenLineage Spark listener
  1. 1Input: raw.german_credit
  2. 2Pipeline edge
  3. 3Clean rows
  4. 4Quarantined rows

Both edges matter. A lineage graph that only showed the clean table would hide where the rejected rows went, and the quarantine edge is the one an auditor asks about first. Column lineage goes one level deeper: open credit_features, pick Layers, then Column from the lineage toolbar, and click a derived column such as monthly_installment.

OpenMetadata column lineage layer showing monthly_installment in credit_features derived from credit_amount and duration_months in german_credit
  1. 1Layers, then Column
  2. 2monthly_installment

OpenLineage worked this out from Spark’s logical plan, not from anything we declared. monthly_installment traces back to credit_amount and duration_months because the F.round(...) expression reads both. That is the payoff of OpenLineage over hand-drawn lineage, since it stays right when someone edits the transform.

The UI is easy to misread, so check the same edges through the lineage API. This asks for one hop downstream of the raw table and prints each target, its pipeline and how many column mappings it carries:

curl -s -H "Authorization: Bearer ${OM_BOT_JWT}" \
  "http://localhost:8585/api/v1/lineage/table/name/warehouse.credit.raw.german_credit?upstreamDepth=0&downstreamDepth=1" \
  | jq -r '(.nodes | map({(.id): .fullyQualifiedName}) | add) as $n
      | .downstreamEdges[]
      | "\($n[.toEntity])  via \(.lineageDetails.pipeline.fullyQualifiedName)  columns=\(.lineageDetails.columnsLineage | length)"'

Two edges come back, both through the pipeline we created:

warehouse.credit.analytics.credit_quarantine  via openlineage.credit_etl-german_credit_features  columns=11
warehouse.credit.analytics.credit_features  via openlineage.credit_etl-german_credit_features  columns=10

Column counts line up with the schemas. The features table has 10 columns, and the quarantine table has the same 10 plus failed_rules, which the listener traced back to the columns its rules read.

Add the same rule as an OpenMetadata data quality test

Pandera’s verdict never reaches OpenMetadata, so the catalog cannot show that the raw table holds out-of-range amounts. If you want quality visible next to the lineage, define the same bound as an OpenMetadata test case on each table. Do it for the raw table and the clean one, so the catalog shows the problem upstream and its absence downstream.

curl -s -X POST http://localhost:8585/api/v1/dataQuality/testCases \
  -H "Authorization: Bearer ${OM_BOT_JWT}" -H "Content-Type: application/json" \
  -d '{
    "name": "credit_amount_in_range",
    "entityLink": "<#E::table::warehouse.credit.raw.german_credit::columns::credit_amount>",
    "testDefinition": "columnValuesToBeBetween",
    "parameterValues": [
      {"name": "minValue", "value": "250"},
      {"name": "maxValue", "value": "15000"}
    ]
  }' | jq '{fullyQualifiedName, testDefinition: .testDefinition.name}'

Repeat the call with the entity link <#E::table::warehouse.credit.analytics.credit_features::columns::credit_amount> for the clean table. Each reply names the test’s fully qualified path:

{
  "fullyQualifiedName": "warehouse.credit.raw.german_credit.credit_amount.credit_amount_in_range",
  "testDefinition": "columnValuesToBeBetween"
}

Tests run in the ingestion container with a TestSuite workflow. One file serves both tables because the table name comes from an environment variable.

vim ~/credit-etl/credit-tests.yaml

Add the workflow:

source:
  type: TestSuite
  serviceName: warehouse
  sourceConfig:
    config:
      type: TestSuite
      entityFullyQualifiedName: ${TABLE_FQN}
processor:
  type: orm-test-runner
  config: {}
sink:
  type: metadata-rest
  config: {}
workflowConfig:
  openMetadataServerConfig:
    hostPort: http://openmetadata-server:8585/api
    authProvider: openmetadata
    securityConfig:
      jwtToken: ${OM_BOT_JWT}

Copy it in and run it once per table:

docker cp credit-tests.yaml openmetadata_ingestion:/tmp/credit-tests.yaml
docker exec -e OM_BOT_JWT -e TABLE_FQN=warehouse.credit.raw.german_credit openmetadata_ingestion metadata test -c /tmp/credit-tests.yaml
docker exec -e OM_BOT_JWT -e TABLE_FQN=warehouse.credit.analytics.credit_features openmetadata_ingestion metadata test -c /tmp/credit-tests.yaml

A workflow success of 100% means the runner ran, not that the test passed. Each run finished in about three seconds:

[2026-11-12 11:57:29] INFO     {metadata.TestSuite:test_suite:105} - Retrieving table entity for FQN: warehouse.credit.raw.german_credit
[2026-11-12 11:57:30] INFO     {metadata.TestSuite:core:31} - Executing test case credit_amount_in_range for entity warehouse.credit.raw.german_credit
...
[2026-11-12 11:57:31] INFO     {metadata.Utils:logger:223} - Workflow Success %: 100.0
[2026-11-12 11:57:31] INFO     {metadata.Utils:logger:223} - Workflow finished in time: 3s 233.702ms

The verdict shows on the table’s Data Quality tab. On the raw table the test fails and reports the same 18,424 amount Pandera flagged:

OpenMetadata Data Quality tab for raw.german_credit with the credit_amount_in_range test failed at max 18424 against the 15000 bound

To read both results side by side, pull them from the test case API along with the lineage call from the previous section:

curl -s -H "Authorization: Bearer ${OM_BOT_JWT}" \
  "http://localhost:8585/api/v1/dataQuality/testCases?fields=testCaseResult&limit=10" \
  | jq -r '.data[] | "\(.fullyQualifiedName)\n  \(.testCaseResult.testCaseStatus): \(.testCaseResult.result)"'

Side by side, the raw table fails at a maximum of 18,424 while the features table passes at 14,896, so the gate and the catalog agree on the same boundary. Put the raw table test on a daily ingestion schedule and the catalog flags oversized loans before the Spark job ever reads them.

Terminal output of the OpenMetadata lineage API listing both downstream tables via the credit_etl pipeline, and the data quality API showing raw failed and analytics passed

You pay for this design with a rule defined in two places, RANGES in Python and the test parameters in OpenMetadata. We would accept that for a handful of critical columns and keep everything else in Pandera only, rather than try to sync two rule engines column by column.

Skip Great Expectations on PySpark 4 for now

Great Expectations is the usual answer to “pyspark data quality checks”, and OpenLineage does ship a GX action for 1.x checkpoints in its openlineage-integration-common package, whose great-expectations extra asks for great-expectations>=1.0.0. We still didn’t use it, and the reason is dependency conflicts, not a missing action. The GX Core package on PyPI declares its spark extra as pyspark<4.2,>=2.3.2, and this job runs PySpark 4.3, so installing GX with Spark support would downgrade PySpark or fail to resolve.

OpenLineage’s GX extra adds a second conflict, because the same PyPI metadata pins sqlalchemy<2.0.0,>=1.3.24 for it. The OpenMetadata ingestion image in this lab already runs SQLAlchemy 2 (its error links point at the sqlalche.me/e/20 pages), so the two cannot share an environment. If your platform is still on Spark 3.5 and you already run GX checkpoints, that route works and gives you validation results as OpenLineage facets. On Spark 4.x, Pandera is the lighter choice today, and you’ll want to revisit when GX widens its PySpark range.

Send the same events to DataHub or Marquez

Nothing in the Spark job is specific to OpenMetadata except the transport URL, endpoint and key, so switching catalogs is a config change. DataHub accepts OpenLineage events at /openapi/openlineage/api/v1/lineage on its GMS server, though its docs steer Spark users toward DataHub’s own Spark agent for richer metadata. Marquez, the OpenLineage reference backend, listens on /api/v1/lineage on its API port, which is the transport’s default, so you can drop the endpoint key entirely. Marquez’s latest release is 0.50.0 from October 2024 according to its GitHub releases page, so check its maintenance status before choosing it for a new platform. The table sums up what changes:

Backendtransport.endpointAuthBefore the first run
OpenMetadata/api/v1/openlineage/lineageBot JWT as api_keyIngest tables, map the namespace, create the pipeline entity
DataHub/openapi/openlineage/api/v1/lineageDataHub token as api_keyNothing; datasets are materialized from events by default
Marquezdefault /api/v1/lineageNone by defaultNothing; datasets are created from events

OpenMetadata asks for the most setup of the three because it insists on knowing the tables first. In return, the lineage lands on the same entities that carry owners, descriptions and test results, which is the reason to pick it when the catalog is the product rather than a lineage viewer.

Fix the errors between Spark and OpenMetadata

Every one of these came up while building the lab. Most failures in this pairing are silent on the Spark side, because the listener posts asynchronously and the job succeeds either way, so check the OpenMetadata server log first.

docker logs openmetadata_server 2>&1 | grep -i openlineage | tail -20

Match what you find against the headings below. Each one is the exact message from our lab log, so searching for the error text takes you straight to the fix.

Failed to create pipeline credit_etl-german_credit_features: java.sql.SQLIntegrityConstraintViolationException: Column ‘updatedAt’ cannot be null

OpenMetadata’s auto-create path is failing here, and the same bug also shows up as Failed to create table credit_features with the same constraint. The event arrives, the server tries to create the missing pipeline or table, and the insert fails, so the edge is dropped. Create the entities yourself: ingest the warehouse after the first Spark run so the output tables exist, create the pipeline entity named <namespace>-<appName>, then rerun the job.

Principal: CatalogPrincipal{name=’ingestion-bot’} is not admin

The PUT to /api/v1/system/settings returns HTTP 403 with this message when you use the bot JWT. Bots can write metadata but not change system settings. Log in as an admin through /api/v1/users/login, use that access token for the settings call only, and keep the bot token for Spark.

No parsable table identifier for dataset /home/eugene/credit-etl/data/raw/german.data (namespace file)

OpenMetadata only resolves datasets that look like schema.table or catalog.schema.table, and a local file path is neither. The loader job reads a CSV, so its input never resolves and that job shows no upstream edge. It’s harmless here because the lineage that matters starts at raw.german_credit; for files in object storage, ingest the storage service and map its namespace the same way we mapped PostgreSQL.

Cannot create table, schema not found for candidates: [DatasetCandidate[tableName=credit.raw.german_credit, namespace=postgres://localhost:5432]]

Your namespace mapping is missing or does not match, so OpenMetadata cannot tell which database service postgres://localhost:5432 belongs to. Compare the namespace in this message, character for character, with the key in namespaceToServiceMapping. If Spark connects through a different host name than the one in the mapping, the namespace changes with it.

ImportError: cannot import name ‘DateOffset’ from ‘pandas.tseries.frequencies’

The failing import sits in pyspark.pandas, which pandera.pyspark loads, and it asks for a name pandas 3 removed. PySpark also warns in the same run that it does not yet fully support pandas 3. Pin "pandas<3" in the virtual environment, as shown in the setup section, until both projects declare pandas 3 support.

[PYTHON_VERSION_MISMATCH] Python in worker has different version: 3.14 than that in driver: 3.13

Your driver ran from the virtual environment’s Python, but Spark started its Python workers with the system python3, which is 3.14 on Ubuntu 26.04. It happens when you call .venv/bin/python directly without activating the environment. Run source .venv/bin/activate first, or export PYSPARK_PYTHON pointing at the venv interpreter in scheduler jobs where activation is awkward.

If you’re still choosing where this job runs, the next pieces are an orchestrator and a model registry: our walkthroughs on setting up Apache Spark on Ubuntu and Spark on Oracle Linux cover a standalone cluster for heavier batches. When credit_features becomes training input for a credit model, log those runs to an MLflow tracking server so each model version points back at the batch that passed the gate. For deeper reading on the stack, see our picks of the best books to learn Kafka and Apache Spark and the best AWS data engineer books.

Keep reading

Install PostgreSQL 18 on Debian 13 / 12 Databases Install PostgreSQL 18 on Debian 13 / 12 Install DBeaver on Ubuntu 26.04 / 24.04 and Debian 13 Databases Install DBeaver on Ubuntu 26.04 / 24.04 and Debian 13 Install SQL Server 2025 Developer Edition on Windows Server 2025 Databases Install SQL Server 2025 Developer Edition on Windows Server 2025 MariaDB 13.1 New Features Tested: DENY, JSON Arrows, utf8mb4 Databases MariaDB 13.1 New Features Tested: DENY, JSON Arrows, utf8mb4 MariaDB CVE-2026-92262: Check If You Are Affected and Patch Databases MariaDB CVE-2026-92262: Check If You Are Affected and Patch Install Redis 8 on Rocky Linux 10 / AlmaLinux 10 / RHEL 10 Databases Install Redis 8 on Rocky Linux 10 / AlmaLinux 10 / RHEL 10

Leave a Comment

Press ESC to close