Lineage: Recording and Querying the Data Graph
A source team will change what customers.status means. Record table- and column-level lineage with the OpenLineage Python client as three jobs run, load the events into DuckDB, and use recursive queries to find exactly which columns and owners the change affects, and where a wrong number came from.
Contentsand lesson path
On this page
- The problem
- Step 1: A helper that emits run events
- Step 2: Run a pipeline that reports its lineage
- Step 3: Look at the events
- Step 4: Build the graph and ask a table-level question
- Step 5: Narrow the impact with column lineage
- Step 6: Trace a wrong number upstream
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Contracts & Governance
- Data Products, Data Mesh and Contracts Between Teams Concept · 20 min
- Lab: Enforcing a Contract and Shipping a Breaking Change Lab · 25 min
- Lineage: Recording and Querying the Data Graph Worked example · 25 min
- Lab: Catalog Entries, Classification and Access Control Lab · 25 min
- Protecting Personal Data: Pseudonymize, Encrypt, Retain, Erase Worked example · 30 min
- Check: Governance Review of a Pipeline Knowledge check · 10 questions
What you will learn
- Capture table- and column-level lineage (for example with OpenLineage) and use it to assess the impact of a change or incident.
01. The problem
The CRM team announces that next month status in the customer table will gain a new value, platinum, and that gold will mean something narrower. They ask a fair question: who will be affected? Without a record of how data flows, the honest answer is "we will find out when a report breaks". A text search for "status" finds dozens of unrelated columns and misses every place where the column was renamed on the way.
Lineage is that record: a graph of which jobs read which datasets and wrote which others. Table-level lineage links datasets through jobs. Column-level lineage links each output column to the input columns it was computed from, so you can follow one field instead of a whole table. With lineage you can run impact analysis, following the graph downstream from a change to every affected asset and its owner, and root-cause analysis, following it upstream from a wrong number to its sources.
OpenLineage is an open standard for collecting lineage at run time. A job, or an integration inside the tool that runs it, sends run events as it runs: a START event, then COMPLETE or FAIL. Each event names the job, a unique run id, the input and output datasets, and optional facets, extra blocks of metadata such as a schema, an owner or column lineage. A backend such as Marquez stores the events and draws the graph. Ready-made integrations exist for Airflow, Spark, dbt and Flink; in this worked example you emit events yourself with the Python client, so you can see every part.
02. Step 1: A helper that emits run events
You need Python 3.10 or later and pip install "openlineage-python==1.55.0" "duckdb==1.5.6"; the example was run with Python 3.12. The client reads its settings from openlineage.yml in the working directory. The file transport writes each event as one JSON line, so you need no server. lineage.py wraps the client: run_job emits START, runs the job, then emits COMPLETE with the outputs, or FAIL if the job raised an error. output describes one output dataset with three facets: its schema, its owner, and its column lineage.
Column lineage records how each output column depends on its inputs. The spec calls the dependency DIRECT when the value is derived from the input (subtypes IDENTITY, TRANSFORMATION and AGGREGATION) and INDIRECT when the input only influences the result, for example as a join key, a filter or a group-by key. Inputs that affect every column, such as join keys, go in the facet's dataset list rather than under one column.
# The client reads this file from the working directory. Each event becomes one JSON
# line in lineage/events.jsonl; in production the transport would be "http" to Marquez.
transport:
type: file
log_file_path: lineage/events.jsonl
append: true"""Emit OpenLineage run events, with schema, owner and column lineage."""
from datetime import datetime, timezone
from openlineage.client import OpenLineageClient
from openlineage.client.event_v2 import InputDataset, Job, OutputDataset, Run, RunEvent
from openlineage.client.event_v2 import RunState
from openlineage.client.facet_v2 import column_lineage_dataset as cl
from openlineage.client.facet_v2 import ownership_dataset, schema_dataset
from openlineage.client.uuid import generate_new_uuid
NAMESPACE = "duckdb://shop.duckdb" # where the datasets live
PRODUCER = "https://example.com/lineage-lab"
INDIRECT = {"JOIN", "GROUP_BY", "FILTER", "SORT", "WINDOW", "CONDITIONAL"}
client = OpenLineageClient() # reads openlineage.yml
def field(source, subtype):
"""One input column, 'dataset.column', and how the output depends on it."""
dataset, column = source.rsplit(".", 1)
kind = "INDIRECT" if subtype in INDIRECT else "DIRECT"
how = cl.Transformation(type=kind, subtype=subtype)
return cl.InputField(namespace=NAMESPACE, name=dataset, field=column,
transformations=[how])
def output(con, name, owner, columns, whole_dataset=()):
"""An output dataset with its schema, its owner and its column lineage.
columns maps each output column to [(input 'dataset.column', subtype), ...];
whole_dataset lists inputs that affect every row, such as join or group keys.
"""
types = con.sql(f"select column_name, column_type from (describe {name})")
return OutputDataset(namespace=NAMESPACE, name=name, facets={
"schema": schema_dataset.SchemaDatasetFacet(fields=[
schema_dataset.SchemaDatasetFacetFields(name=c, type=t)
for c, t in types.fetchall()]),
"ownership": ownership_dataset.OwnershipDatasetFacet(
owners=[ownership_dataset.Owner(name=owner)]),
"columnLineage": cl.ColumnLineageDatasetFacet(
fields={col: cl.Fields(inputFields=[field(s, t) for s, t in srcs])
for col, srcs in columns.items()},
dataset=[field(s, t) for s, t in whole_dataset])})
def run_job(name, inputs, work):
"""Emit START, run work() (it returns the outputs), then COMPLETE or FAIL."""
run = Run(runId=str(generate_new_uuid()))
job = Job(namespace="lineage-lab", name=name)
ins = [InputDataset(namespace=NAMESPACE, name=i) for i in inputs]
def event(state, outputs=()):
now = datetime.now(timezone.utc).isoformat()
return RunEvent(eventType=state, eventTime=now, run=run, job=job,
producer=PRODUCER, inputs=ins, outputs=list(outputs))
client.emit(event(RunState.START))
try:
outputs = work()
except Exception:
client.emit(event(RunState.FAIL)) # a failed run is lineage too
raise
client.emit(event(RunState.COMPLETE, outputs))
print(f"{name}: {', '.join(inputs) or '(source)'} -> "
f"{', '.join(o.name for o in outputs)}")03. Step 2: Run a pipeline that reports its lineage
pipeline.py has three jobs. load_raw creates the raw tables. build_staging joins orders to customers and turns status into a segment. build_marts builds two marts, revenue by segment and revenue by country. Each job declares the column lineage of what it wrote. Here you write it by hand; integrations derive it from the query plan or the SQL.
"""Three jobs: load raw data, build staging, build two marts. Each emits lineage."""
import duckdb
from lineage import output, run_job
con = duckdb.connect("shop.duckdb")
con.execute("create schema if not exists raw; create schema if not exists stg;"
" create schema if not exists marts")
def load_raw():
con.execute("""create or replace table raw.customers as
select i as customer_id, 'user' || i || '@example.com' as email,
['gold', 'silver', 'basic'][1 + i % 3] as status,
['GB', 'DE', 'FR'][1 + i % 3 // 2] as country
from range(1, 31) t(i)""")
con.execute("""create or replace table raw.orders as
select i as order_id, 1 + (i * 7) % 30 as customer_id,
(10 + (i * 13) % 90)::decimal(10, 2) as amount
from range(1, 201) t(i)""")
# The raw layer copies the source as it is, so no column lineage is recorded here.
return [output(con, "raw.customers", "team:platform", {}),
output(con, "raw.orders", "team:platform", {})]
def build_staging():
con.execute("""create or replace table stg.orders as
select o.order_id, o.customer_id, o.amount, c.country,
case when c.status = 'gold' then 'premium' else 'standard' end as segment
from raw.orders o join raw.customers c using (customer_id)""")
return [output(con, "stg.orders", "team:analytics", {
"order_id": [("raw.orders.order_id", "IDENTITY")],
"customer_id": [("raw.orders.customer_id", "IDENTITY")],
"amount": [("raw.orders.amount", "IDENTITY")],
"country": [("raw.customers.country", "IDENTITY")],
"segment": [("raw.customers.status", "CONDITIONAL")],
}, whole_dataset=[("raw.orders.customer_id", "JOIN"),
("raw.customers.customer_id", "JOIN")])]
def build_marts():
con.execute("""create or replace table marts.revenue_by_segment as
select segment, count(*) as orders, sum(amount) as revenue
from stg.orders group by segment""")
con.execute("""create or replace table marts.revenue_by_country as
select country, sum(amount) as revenue from stg.orders group by country""")
return [output(con, "marts.revenue_by_segment", "team:finance", {
"segment": [("stg.orders.segment", "IDENTITY")],
"orders": [("stg.orders.order_id", "AGGREGATION")],
"revenue": [("stg.orders.amount", "AGGREGATION")],
}, whole_dataset=[("stg.orders.segment", "GROUP_BY")]),
output(con, "marts.revenue_by_country", "team:sales-ops", {
"country": [("stg.orders.country", "IDENTITY")],
"revenue": [("stg.orders.amount", "AGGREGATION")],
}, whole_dataset=[("stg.orders.country", "GROUP_BY")])]
run_job("load_raw", [], load_raw)
run_job("build_staging", ["raw.orders", "raw.customers"], build_staging)
run_job("build_marts", ["stg.orders"], build_marts)mkdir -p lineage
python pipeline.pyload_raw: (source) -> raw.customers, raw.orders
build_staging: raw.orders, raw.customers -> stg.orders
build_marts: stg.orders -> marts.revenue_by_segment, marts.revenue_by_country04. Step 3: Look at the events
Six events arrived: a START and a COMPLETE for each run. In this helper the START events carry no outputs, because run_job learns the outputs only when the job returns. The spec allows datasets on any event and merges them, and many integrations already list outputs in START; that is why graph.py reads only COMPLETE events, which describe what a run really wrote. With an integration, merge all events of a run and keep the runs that reached COMPLETE. The event time and run id differ on every run, so the commands below print only the stable parts.
wc -l < lineage/events.jsonl
python -c 'import json
for line in open("lineage/events.jsonl"):
e = json.loads(line)
print(e["eventType"], e["job"]["name"], [d["name"] for d in e["outputs"]])'6
START load_raw []
COMPLETE load_raw ['raw.customers', 'raw.orders']
START build_staging []
COMPLETE build_staging ['stg.orders']
START build_marts []
COMPLETE build_marts ['marts.revenue_by_segment', 'marts.revenue_by_country']Here is the column lineage of stg.orders.segment as it was sent: one input field, raw.customers.status, with an indirect CONDITIONAL transformation. segment is computed by case when c.status = 'gold' then ...: the status decides which branch is taken, but its value is never copied or computed into the result, and the spec's CONDITIONAL subtype describes exactly an input used in IF, CASE WHEN or COALESCE.
python - <<'PY'
import json
events = [json.loads(line) for line in open("lineage/events.jsonl")]
stg = next(e for e in events if e["eventType"] == "COMPLETE"
and e["job"]["name"] == "build_staging")["outputs"][0]
print(json.dumps(stg["facets"]["columnLineage"]["fields"]["segment"], indent=2))
PY{
"inputFields": [
{
"field": "status",
"name": "raw.customers",
"namespace": "duckdb://shop.duckdb",
"transformations": [
{
"subtype": "CONDITIONAL",
"type": "INDIRECT"
}
]
}
]
}05. Step 4: Build the graph and ask a table-level question
graph.py reads the COMPLETE events into three DuckDB tables: table edges, column edges and owners. A dataset-level input becomes an edge to every column of the output. The questions are recursive queries: a WITH RECURSIVE query starts from the edges of one node and keeps following them until no new rows appear. Start with the table level: what is downstream of raw.customers?
"""Load the lineage events into DuckDB and answer impact questions with SQL."""
import json
import sys
import duckdb
con = duckdb.connect() # in memory: rebuilt from the events
con.execute("create table table_edges (job text, source text, target text)")
con.execute("""create table column_edges (source text, target text,
kind text, subtype text)""")
con.execute("create table owners (dataset text, owner text)")
for line in open("lineage/events.jsonl"):
event = json.loads(line)
if event["eventType"] != "COMPLETE": # only finished runs count
continue
for out in event["outputs"]:
facets = out["facets"]
con.execute("insert into owners values (?, ?)",
[out["name"], facets["ownership"]["owners"][0]["name"]])
for inp in event["inputs"]:
con.execute("insert into table_edges values (?, ?, ?)",
[event["job"]["name"], inp["name"], out["name"]])
lineage = facets["columnLineage"]
columns = [f["name"] for f in facets["schema"]["fields"]]
for column, spec in lineage["fields"].items():
for f in spec["inputFields"]:
t = f["transformations"][0]
con.execute("insert into column_edges values (?, ?, ?, ?)",
[f"{f['name']}.{f['field']}", f"{out['name']}.{column}",
t["type"], t["subtype"]])
for f in lineage.get("dataset", []): # affects every column of the output
t = f["transformations"][0]
for column in columns:
con.execute("insert into column_edges values (?, ?, ?, ?)",
[f"{f['name']}.{f['field']}", f"{out['name']}.{column}",
t["type"], t["subtype"]])
# Each query starts from the edges of one node and follows them recursively.
QUERIES = {
"downstream-tables": """
with recursive down(dataset) as (
select target from table_edges where source = ?
union
select e.target from table_edges e join down on e.source = down.dataset)
select dataset, owner from down join owners using (dataset) order by 1""",
"downstream-columns": """
with recursive down(col, how) as (
select target, subtype from column_edges where source = ?
union
select e.target, e.subtype
from column_edges e join down on e.source = down.col)
select col as affected_column,
string_agg(distinct how, ', ' order by how) as via, owner
from down join owners on owners.dataset = regexp_replace(col, '[.][^.]+$', '')
group by col, owner order by 1""",
"upstream-columns": """
with recursive up(col, how) as (
select source, subtype from column_edges where target = ?
union
select e.source, e.subtype
from column_edges e join up on e.target = up.col)
select col as source_column, string_agg(distinct how, ', ' order by how) as via
from up group by col order by 1""",
}
question, start = sys.argv[1], sys.argv[2]
print(con.sql(QUERIES[question], params=[start]))python graph.py downstream-tables raw.customers┌──────────────────────────┬────────────────┐
│ dataset │ owner │
│ varchar │ varchar │
├──────────────────────────┼────────────────┤
│ marts.revenue_by_country │ team:sales-ops │
│ marts.revenue_by_segment │ team:finance │
│ stg.orders │ team:analytics │
└──────────────────────────┴────────────────┘Table-level lineage says that both marts depend on raw.customers, so you would warn the finance team and the sales operations team.
06. Step 5: Narrow the impact with column lineage
Now follow the one column that changes.
python graph.py downstream-columns raw.customers.status┌──────────────────────────────────┬────────────────────┬────────────────┐
│ affected_column │ via │ owner │
│ varchar │ varchar │ varchar │
├──────────────────────────────────┼────────────────────┼────────────────┤
│ marts.revenue_by_segment.orders │ GROUP_BY │ team:finance │
│ marts.revenue_by_segment.revenue │ GROUP_BY │ team:finance │
│ marts.revenue_by_segment.segment │ GROUP_BY, IDENTITY │ team:finance │
│ stg.orders.segment │ CONDITIONAL │ team:analytics │
└──────────────────────────────────┴────────────────────┴────────────────┘Only revenue_by_segment is affected. Its segment column depends on status through the CASE condition, and its orders and revenue columns are grouped by it, so all three can change; revenue_by_country reads stg.orders but never uses segment. You contact two owners instead of everyone downstream, and you can tell finance exactly which columns to check. This is the main reason to collect lineage at column level.
07. Step 6: Trace a wrong number upstream
Lineage also works backwards. Suppose sales operations report that revenue by country looks too low. Follow marts.revenue_by_country.revenue upstream.
python graph.py upstream-columns marts.revenue_by_country.revenue┌───────────────────────────┬─────────────┐
│ source_column │ via │
│ varchar │ varchar │
├───────────────────────────┼─────────────┤
│ raw.customers.country │ IDENTITY │
│ raw.customers.customer_id │ JOIN │
│ raw.orders.amount │ IDENTITY │
│ raw.orders.customer_id │ JOIN │
│ stg.orders.amount │ AGGREGATION │
│ stg.orders.country │ GROUP_BY │
└───────────────────────────┴─────────────┘The list gives you every place to look: the order amounts, the country values, and the join keys between orders and customers. A missing customer, for example, would drop orders silently in the inner join. In a real backend you would also see which run produced each version of the mart, and whether that run failed, so you could find the bad load as well as the bad column.
08. Check your understanding
09. Apply it
This is the lineage part of the skill practice. Emit OpenLineage events from two jobs of a pipeline you built, either with an integration (the Airflow OpenLineage provider, dbt-ol for dbt, or the Spark listener) or with the client as here. Then:
- Send them to a file and, if you can, to a local Marquez, and compare the graph with your own picture of the pipeline.
- Pick one source column that could change, and write down the affected columns and owners from a downstream query.
- Write down which parts of your pipeline are not instrumented yet.
10. Review prompt
Without looking back, explain: what an OpenLineage run event contains and why the graph is built from COMPLETE events; what facets are, with three examples; the difference between DIRECT and INDIRECT column lineage; why column lineage gives a smaller, more useful impact list than table lineage; and how the same graph answers both "what will this change break?" and "where did this number come from?".
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.