Skip to content

← Tutorials overview

12. Lineage

Reference

The reference for this topic is Persisted lineage graph.

A registered process is a SQL view that depends on tables and other views; a dataset is a view that depends on processes. tdfs4ds walks those dependencies, returns a graph and renders it as an interactive Sankey diagram.

import dataclasses
import getpass
import os

import tdfs4ds                      # importing it first also loads a .env file, if you have one
import teradataml as tdml

# 1. Open the Teradata session. Host and user come from the environment (TDFS4DS_TD_HOST,
#    TDFS4DS_TD_USERNAME), the password from TDFS4DS_TD_PASSWORD or a prompt: nothing secret
#    is written on this page.
host = os.environ["TDFS4DS_TD_HOST"]
user = os.environ["TDFS4DS_TD_USERNAME"]
password = os.environ.get("TDFS4DS_TD_PASSWORD") or getpass.getpass("Teradata password: ")
tdml.create_context(host=host, username=user, password=password)

# 2. Pick your industry. This is the ONLY line to change: retail, banking, healthcare, pharma,
#    manufacturing, assembly, energy or transportation. Every name below comes from S.
S = tdfs4ds.tutorial_scenario("retail")

# 3. Connect to the feature store (created when missing) and choose a data domain. disposable=True
#    records that this domain is an experiment, so the last page removes it in one call.
DATABASE = os.environ.get("TDFS4DS_TD_DATABASE") or user
tdfs4ds.connect(database=DATABASE, create_if_missing=True)
tdfs4ds.create_data_domain(f"TUTORIAL_{S.name.upper()}", disposable=True)   # an experiment: removable in one call

# 4. The tutorial data: three tables written once; a second run keeps them.
try:
    S = tdfs4ds.create_tutorial_data(S.name, DATABASE)
except ValueError:
    S = dataclasses.replace(S, database=DATABASE)


def register_entity_features():
    """Page 1 in one call: (re)register the entity features and return the process id."""
    sql = f"""
        SELECT {S.entity}, COUNT(*) AS nb_events, SUM({S.amount}) AS total_amount,
               AVG({S.amount}) AS avg_amount, COUNT(DISTINCT {S.partner}) AS nb_partners
        FROM {S.table('events')}
        GROUP BY 1"""
    return tdfs4ds.upload_features(
        df=None, sql_query=sql, target_view_name=f"{S.database}.{S.name}_entity_features",
        entity_id=[S.entity], feature_names=["nb_events", "total_amount", "avg_amount", "nb_partners"],
        replace=True, document=False, optimize_query=False, return_process_id=True)

process_id = register_entity_features()
dataset = tdfs4ds.build_dataset(
    entity_id=[S.entity],
    selected_features=["nb_events", "total_amount", "avg_amount", "nb_partners"],
    view_name=f"{S.database}.{S.name}_entity_dataset",
)

You should see a process id and the dataset built, as in module 10.

Why look at lineage

  • Audit before refactor. Before you change a source table, see every feature, process and dataset that depends on it.
  • Impact assessment. To deprecate the events table, walk forward and list what you would break.
  • Onboarding. "Where does total_amount come from?" is one diagram.
  • Migration planning. The graph feeds the manifest in module 13.

1 · Build the graph of the dataset

Seed the builder with the SQL of the dataset view:

from tdfs4ds.lineage import build_teradata_dependency_graph
from tdfs4ds.utils.show_text import show_text

dataset_sql = show_text(tdml.execute_sql(
    f"SHOW VIEW {S.database}.{S.name}_entity_dataset").fetchall()).replace("\r", "\n")
graph = build_teradata_dependency_graph(sql_query=dataset_sql)
print(list(graph["nodes"]))
print(graph["edges"])

Output with scenario='retail': the dataset, the process view (<flavor>_entity_features) and the events table as nodes, and the edges between them:

['"my_database"."retail_entity_dataset"', '"my_database"."retail_entity_features"', '"my_database"."retail_transactions"']
[('"my_database"."retail_entity_dataset"', '"my_database"."retail_entity_features"'), ('"my_database"."retail_entity_features"', '"my_database"."retail_transactions"')]

The dataset reads the process, the process reads the events table. The storage tables FS_T_... are skipped (the dataset is linked to the process that wrote them).

graph is a dict:

Key Content
nodes One entry per object: its object_type and table_info (primary index and partition columns)
edges Directed dependencies, (consumer, source)
roots The top-level targets

2 · Draw it

from tdfs4ds.lineage import plot_lineage_sankey

figure = plot_lineage_sankey(graph, title=f"{S.name} lineage")
figure.write_html(f"{S.name}_lineage.html")

You should see a file <flavor>_lineage.html in the working folder: open it for an interactive Sankey (in a notebook, figure.show() draws it inline). The consumer agent's LINEAGE skill uses the same graph: "Where does avg_amount come from?" answers with the dependency list.

3 · Table details at the same time

Every table node carries its primary index and partition columns, which is the evidence for module 8:

for name, node in graph["nodes"].items():
    info = node.get("table_info") or {}
    if node["object_type"] == "table":
        print(name, "PI:", info.get("primary_index_columns"), "partitions:", info.get("partition_columns"))

Output with scenario='retail': the events table with the entity as primary index and the event date as its partition column.

"my_database"."retail_transactions" PI: ['CustomerID'] partitions: ['Date_transaction']

4 · The persisted graph: both directions

The graph above is re-derived on every call. tdfs4ds also keeps a persisted, temporal graph in FS_LINEAGE_GRAPH, updated each time you call upload_features or build_dataset, and queryable in both directions:

from tdfs4ds.lineage import get_ancestors, get_descendants

print(get_descendants(S.database, f"{S.name}_entity_features"))      # impact: who depends on it
print(get_ancestors(S.database, f"{S.name}_entity_dataset"))         # sources: what feeds it

Output with scenario='retail' (the second dataset is the grouped one built on First dataset): the dataset among the descendants of the process view, and the process view and the events table among the ancestors of the dataset.

['MY_DATABASE.RETAIL_ENTITY_DATASET', 'MY_DATABASE.RETAIL_ENTITY_DATASET_GROUPED']
['MY_DATABASE.RETAIL_ENTITY_FEATURES', 'MY_DATABASE.RETAIL_TRANSACTIONS']

After you edit a view, refresh only the objects you changed (the names are checked against the store, and the processes that read them are checked to still compile):

tdfs4ds.rebuild_lineage_graph(objects=[f"{S.database}.{S.name}_entity_features"])

You should see the number of edges written for those objects. For the first time on an existing store, or after adding many processes, tdfs4ds.rebuild_lineage_graph() with no argument re-derives the graph of every process and dataset of the store, other teams' included; tdfs4ds.rebuild_documentation() then documents every process and dataset once, in dependency order (it needs the instruct model of module 2).

Clean up

Nothing to remove: the graph rows of an object end when you remove it (remove_process, drop_dataset). Module 13 lists the rest.

Learn more