Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 47 additions & 29 deletions ingestion/src/metadata/ingestion/source/database/dbt/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,14 @@
from metadata.utils.entity_link import get_table_fqn
from metadata.utils.filters import filter_by_tag
from metadata.utils.logger import ingestion_logger
from metadata.utils.lru_cache import LRU_CACHE_SIZE, LRUCache
from metadata.utils.tag_utils import get_ometa_tag_and_classification, get_tag_labels
from metadata.utils.time_utils import datetime_to_timestamp

logger = ingestion_logger()

RESOLVED_TABLES_CACHE_SIZE = LRU_CACHE_SIZE


class InvalidServiceException(Exception): # noqa: N818
"""
Expand Down Expand Up @@ -185,6 +188,10 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata):
# per referencing model. Bounded by the number of distinct upstream nodes in the
# project and reset per project in yield_data_models.
self.reported_unresolved_upstreams: set[str] = set()
# Tables found so far, keyed by how the manifest names them. A table is met once as
# its own model and again for every model and test that depends on it. Reset per
# project in yield_data_models.
self.resolved_tables: LRUCache[Table] = LRUCache(RESOLVED_TABLES_CACHE_SIZE)
self._load_omd_custom_properties()

@cached_property
Expand Down Expand Up @@ -832,13 +839,12 @@ def add_dbt_sources(self, key: str, manifest_node, dbt_objects: DbtObjects) -> N
# A freshness check tests the source table itself. Sources are graph roots with no
# depends_on, so resolving upstreams the way a dbt test node does always yields an
# empty list and leaves the test case with no table to attach to.
source_fqn = self._build_table_fqn(
database_name=get_corrected_name(manifest_node.database),
schema_name=get_corrected_name(manifest_node.schema_),
table_name=get_source_physical_name(manifest_node),
table_entity = self._resolve_table(
get_corrected_name(manifest_node.database),
get_corrected_name(manifest_node.schema_),
get_source_physical_name(manifest_node),
literal_table_name=True,
)
table_entity = self._get_table_entity(table_fqn=source_fqn, literal_table_name=True) if source_fqn else None
if not table_entity:
logger.warning(f"Table entity not found for dbt source {key}, skipping its freshness test")
return
Expand Down Expand Up @@ -975,12 +981,38 @@ def _get_table_entity(self, table_fqn, *, literal_table_name: bool = False) -> T

return None

def _resolve_table(
self,
database_name: str | None,
schema_name: str | None,
table_name: str,
*,
literal_table_name: bool = False,
) -> Table | None:
key = (database_name, schema_name, table_name, literal_table_name)
if key in self.resolved_tables:
return self.resolved_tables.get(key)
table_fqn = self._build_table_fqn(
database_name=database_name,
schema_name=schema_name,
table_name=table_name,
literal_table_name=literal_table_name,
)
table_entity = (
self._get_table_entity(table_fqn=table_fqn, literal_table_name=literal_table_name) if table_fqn else None
)
# Misses are not kept: _get_table_entity returns None for a failed lookup as well.
if table_entity:
self.resolved_tables.put(key, table_entity)
return table_entity

# pylint: disable=too-many-locals, too-many-branches
def yield_data_models(self, dbt_objects: DbtObjects) -> Iterable[Either[DataModelLink]]: # noqa: C901
"""
Yield the data models
"""
self.reported_unresolved_upstreams.clear()
self.resolved_tables.clear()
if self.source_config.dbtConfigSource and dbt_objects.dbt_manifest:
logger.debug("Parsing DBT Data Models")
manifest_entities = {
Expand Down Expand Up @@ -1092,18 +1124,13 @@ def yield_data_models(self, dbt_objects: DbtObjects) -> Iterable[Either[DataMode
)
or []
)
table_fqn = self._build_table_fqn(
database_name=get_corrected_name(node_database),
schema_name=get_corrected_name(node_schema),
table_name=model_name,
literal_table_name=resource_type == DbtCommonEnum.SOURCE.value,
)

dbt_compiled_query = get_dbt_compiled_query(manifest_node)
dbt_raw_query = get_dbt_raw_query(manifest_node)

if table_entity := self._get_table_entity(
table_fqn=table_fqn,
if table_entity := self._resolve_table(
get_corrected_name(node_database),
get_corrected_name(node_schema),
model_name,
literal_table_name=resource_type == DbtCommonEnum.SOURCE.value,
):
logger.debug(
Expand Down Expand Up @@ -1237,25 +1264,16 @@ def parse_upstream_nodes_with_names(self, manifest_entities, dbt_node):
if check_ephemeral_node(parent_node):
upstream_nodes.extend(self.parse_upstream_nodes_with_names(manifest_entities, parent_node))
else:
parent_fqn = self._build_table_fqn(
database_name=get_corrected_name(parent_database),
schema_name=get_corrected_name(parent_schema),
table_name=table_name,
literal_table_name=parent_resource_type == DbtCommonEnum.SOURCE.value,
)

# check if the parent table exists in OM before adding it to the upstream list
table_entity = (
self._get_table_entity(
table_fqn=parent_fqn,
literal_table_name=parent_resource_type == DbtCommonEnum.SOURCE.value,
)
if parent_fqn
else None
table_entity = self._resolve_table(
get_corrected_name(parent_database),
get_corrected_name(parent_schema),
table_name,
literal_table_name=parent_resource_type == DbtCommonEnum.SOURCE.value,
)
# catalogMapping and searchAcrossDatabases can resolve the parent under another
# database or service, so lineage and tests follow the table that was found
if parent_fqn and table_entity:
if table_entity:
upstream_nodes.append(
build_upstream_node(
parent_node,
Expand Down
44 changes: 43 additions & 1 deletion ingestion/tests/unit/test_dbt.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@
validate_table_structure,
validate_time_interval,
)
from metadata.ingestion.source.database.dbt.metadata import DbtSource
from metadata.ingestion.source.database.dbt.metadata import RESOLVED_TABLES_CACHE_SIZE, DbtSource
from metadata.ingestion.source.database.dbt.models import DbtFiles, DbtObjects, UpstreamNode
from metadata.utils.logger import ingestion_logger, set_loggers_level
from metadata.utils.lru_cache import LRUCache
from metadata.utils.tag_utils import get_tag_labels
from metadata.utils.time_utils import datetime_to_timestamp

Expand Down Expand Up @@ -4368,6 +4369,7 @@ def _source(self, catalog, searches):
source.status = MagicMock()
source.tag_classification_name = "dbtTags"
source.reported_unresolved_upstreams = set()
source.resolved_tables = LRUCache(RESOLVED_TABLES_CACHE_SIZE)
source.context = SimpleNamespace(get=lambda: self._ctx)
return source

Expand Down Expand Up @@ -4398,6 +4400,33 @@ def test_lineage_does_not_search_for_an_upstream_it_already_resolved(self):
assert results[0].right.lineage_request.edge.fromEntity.id.root == catalog[self.RAW_FQN].id.root
source.status.warning.assert_not_called()

def test_a_table_used_as_model_and_upstream_is_searched_for_once(self):
"""Issue #38288.

raw_orders is a model and the parent of orders, so parsing meets it twice.
It must cost no more searches than orders, which parsing meets once.
"""
from metadata.ingestion.source.database.dbt.models import DbtObjects

catalog = self._catalog()
searches = []
self._ctx = SimpleNamespace()
source = self._source(catalog, searches)

with self.MANIFEST.open(encoding="utf-8") as manifest_file:
manifest = parse_manifest(json.load(manifest_file))

links = [item.right for item in source.yield_data_models(DbtObjects(dbt_manifest=manifest))]

orders = next(link for link in links if str(link.table_entity.fullyQualifiedName.root) == self.ORDERS_FQN)
assert orders.upstream_table_ids == {self.RAW_FQN: catalog[self.RAW_FQN].id.root}

def searched(table_name):
return sum(1 for search in searches if search.rsplit(".", 1)[-1] == table_name)

assert searched("orders") > 0
assert searched("raw_orders") == searched("orders"), searches


class TestDbtOverrideLineageWithoutUpstream:
"""Issue #37092.
Expand Down Expand Up @@ -4599,6 +4628,7 @@ def _source(sources_generate_time, run_results_generate_time=None, search_across
source.config.serviceName = "snowflake_svc"
source.source_config = MagicMock()
source.source_config.searchAcrossDatabases = search_across_databases
source.resolved_tables = LRUCache(RESOLVED_TABLES_CACHE_SIZE)
source.context.get.return_value.dbt_tests = {}
source.context.get.return_value.sources_generate_time = sources_generate_time
source.context.get.return_value.run_results_generate_time = run_results_generate_time
Expand Down Expand Up @@ -5971,6 +6001,18 @@ def test_freshness_and_metadata_share_the_physical_table_and_keep_logical_names(
assert freshness[DbtCommonEnum.MANIFEST_NODE.value].name == "orders_freshness"
assert generate_entity_link(freshness) == [f"<#E::table::{self.PHYSICAL_FQN}>"]

def test_freshness_reuses_the_source_table_lookup(self):
"""Issue #38288: a freshness result costs no extra search for its source table."""
with TestAddDbtSourceFreshnessResults.SOURCES_FILE.open(encoding="utf-8") as sources_file:
sources = json.load(sources_file)

def searches(**files):
source = self._source(self.PHYSICAL_FQN, self.MODEL_FQN)
self._links(source, self._objects(source, **files))
return source.metadata.es_search_from_fqn.call_count

assert searches(dbt_sources=sources) == searches()

def test_repeated_ingestion_preserves_logical_manifest_identity(self):
source = self._source(self.PHYSICAL_FQN, self.MODEL_FQN)
objects = self._objects(source)
Expand Down
Loading