Skip to content
Open
2 changes: 1 addition & 1 deletion ingestion/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
# since it helps us organize and isolate version management
[project]
name = "openmetadata-ingestion"
version = "2.0.7.0"
version = "2.0.7.0+a8c.3"
dynamic = ["readme", "dependencies", "optional-dependencies"]
authors = [
{ name = "OpenMetadata Committers" }
Expand Down
32 changes: 32 additions & 0 deletions ingestion/src/metadata/ingestion/lineage/sql_lineage.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,38 @@ def get_table_entities_from_query(
if table_entities:
return table_entities

# Cross-catalog fallback: the database resolved from the query/context may not
# match the database the source table was ingested under. This happens when the
# same physical data is exposed through different catalogs across services, so a
# view in one catalog references a table that another service ingested under a
# different database name. Searching with the view's database never matches the
# table under a different database name, so no lineage edge is created even with
# crossDatabaseServiceNames configured. Retry with database=None so the FQN search
# wildcards the database (`<service>.*.<schema>.<table>`) and resolves the table
# across the configured cross-database services. This is scoped to `service_names`,
# which only holds the current service plus the explicitly allowed
# crossDatabaseServiceNames, so it cannot reach unrelated services.
table_entities = search_table_entities(
metadata=metadata,
service_names=service_names,
database=None,
database_schema=schema_query if schema_query else database_schema,
table=table,
)
if table_entities:
return table_entities

if schema_fallback:
table_entities = search_table_entities(
metadata=metadata,
service_names=service_names,
database=None,
database_schema=None,
table=table,
)
if table_entities:
return table_entities

return None


Expand Down
24 changes: 17 additions & 7 deletions ingestion/src/metadata/ingestion/sink/metadata_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,9 @@ def _flush_query_buffer(self) -> Either[Entity]:

return self._record_query_flush_result(result)

def _record_query_flush_result(self, result: Optional[BulkOperationResult]) -> Either[Entity]: # noqa: UP045
def _record_query_flush_result(
self, result: Optional[BulkOperationResult]
) -> Either[Entity]: # noqa: UP045
"""Record a query bulk response. Already-present queries are reported as warnings
(not failures) so a lineage run is not marked failed over queries that lost no
metadata. Any other failure is still recorded as a failure."""
Expand All @@ -467,7 +469,10 @@ def _record_query_flush_result(self, result: Optional[BulkOperationResult]) -> E
for failed in result.failedRequest or []:
query_ref = failed.request or "unknown"
if is_duplicate_query_conflict(failed.message):
self.status.warning("Query", f"Skipped already-present query [{query_ref}]: {failed.message}")
self.status.warning(
"Query",
f"Skipped already-present query [{query_ref}]: {failed.message}",
)
else:
failure = StackTraceError(
name="Query Buffer",
Expand All @@ -477,7 +482,9 @@ def _record_query_flush_result(self, result: Optional[BulkOperationResult]) -> E
self.status.failed(failure)
first_failure = first_failure or failure

return Either(left=first_failure) if first_failure else Either(right=result) # pyright: ignore[reportCallIssue]
return (
Either(left=first_failure) if first_failure else Either(right=result)
) # pyright: ignore[reportCallIssue]

@_run_dispatch.register
def patch_entity(self, record: PatchRequest) -> Either[Entity]:
Expand Down Expand Up @@ -556,16 +563,19 @@ def write_lineage(self, add_lineage: AddLineageRequest) -> Either[str]:
# return_lineage=False: we only need a status identifier below, so skip the expensive
# per-edge full-graph GET that otherwise dominates lineage-heavy ingestions.
created_lineage = self.metadata.add_lineage(add_lineage, check_patch=True, return_lineage=False)
if created_lineage.get("error"):
if created_lineage and created_lineage.get("error"):
return Either(left=StackTraceError(name="AddLineageRequestError", error=created_lineage["error"]))

# Producers that build id-only references carry no FQN. Fall back to a "{type}:{uuid}"
# label (e.g. "table:d311bdf2-..."):
# The edge was written, but reading back the origin node can fail (None response,
# e.g. 404 when its graph holds an edge to a deleted entity), and producers that
# build id-only references carry no FQN. Fall back to a "{type}:{uuid}" label
# (e.g. "table:d311bdf2-..."):
# a None right would silently drop the edge from scanned status (ReturnStep.run) and
# stop write_override_lineage from patching the lineage-processed flag.
from_reference = add_lineage.edge.fromEntity
source_label = (
created_lineage["entity"]["fullyQualifiedName"] or f"{from_reference.type}:{model_str(from_reference.id)}"
(created_lineage or {}).get("entity", {}).get("fullyQualifiedName")
or f"{from_reference.type}:{model_str(from_reference.id)}"
)
return Either(right=source_label) # pyright: ignore[reportCallIssue]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,22 @@ def __init__(

self._added_lineage: Optional[Dict] = {} # noqa: UP006, UP045

@property
def _ui_base(self) -> str:
"""
Base URL for human-facing "View in Looker" links.

`hostPort` is bound to the Looker API host (the SDK uses it as
LOOKERSDK_BASE_URL), which is not always the URL a user should open in
the browser. When the API host differs from the UI host, set the
LOOKER_UI_BASE env var to the UI base URL; otherwise we fall back to
hostPort so behavior is unchanged.
"""
return clean_uri(
os.environ.get("LOOKER_UI_BASE")
or str(self.service_connection.hostPort)
)

@classmethod
def create(
cls,
Expand Down Expand Up @@ -1448,7 +1464,7 @@ def yield_dashboard(self, dashboard_details: LookerDashboard) -> Iterable[Either
# Dashboards are created from the UI directly. They are not linked to a project
# like LookML assets, but rather just organised in folders.
project=self.get_project_name(dashboard_details),
sourceUrl=SourceUrl(f"{clean_uri(self.service_connection.hostPort)}/dashboards/{dashboard_details.id}"),
sourceUrl=SourceUrl(f"{self._ui_base}/dashboards/{dashboard_details.id}"),
service=self.context.get().dashboard_service,
owners=self.get_owner_ref(dashboard_details=dashboard_details),
)
Expand Down Expand Up @@ -1820,8 +1836,18 @@ def yield_dashboard_chart(self, dashboard_details: LookerDashboard) -> Iterable[
source_url = chart.query.share_url
elif getattr(chart.result_maker, "query", None) is not None:
source_url = chart.result_maker.query.share_url
elif chart.merge_result_id is not None:
source_url = f"{self._ui_base}/merge?mid={chart.merge_result_id}"
else:
source_url = f"{clean_uri(self.service_connection.hostPort)}/merge?mid={chart.merge_result_id}"
# No query, no result-maker query, and no merge result:
# a data-less Looker tile (text/markdown/decoration). Skip
# instead of emitting a dead {host}/merge?mid=None link.
logger.info(
f"Skipping data-less Looker tile id={chart.id} "
f"title={chart.title!r} type={chart.type}: no query, "
"no result-maker query, no merge result"
)
continue
chart_request = CreateChartRequest(
name=EntityName(chart.id),
displayName=chart.title or chart.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,11 @@ def _get_charts_of_dashboard(
raw_position_data = dashboard_details.position_json

# For Superset 5.0.0+, position_json may be missing from list endpoint
# In this case, fetch individual dashboard details
if not raw_position_data and hasattr(self, "client"):
# In this case, fetch individual dashboard details. Only the API
# client supports this; in DB mode self.client is a SQLAlchemy Engine.
if not raw_position_data and hasattr(
getattr(self, "client", None), "fetch_dashboard"
):
dashboard_response = self.client.fetch_dashboard(dashboard_details.id)
if dashboard_response and dashboard_response.result:
raw_position_data = dashboard_response.result.position_json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ def _get_cross_database_schema_fqn(
) -> Optional[str]: # noqa: UP045
trino_schema_name = None
if trino_table.databaseSchema and trino_table.databaseSchema.name:
trino_schema_name = trino_table.databaseSchema.name.root
# databaseSchema is an EntityReference, whose name is a plain string; only an
# entity's own name is the EntityName wrapper with .root. Accept both.
schema_ref_name = trino_table.databaseSchema.name
trino_schema_name = getattr(schema_ref_name, "root", schema_ref_name)

if not trino_schema_name and trino_table.fullyQualifiedName and trino_table.fullyQualifiedName.root:
trino_table_fqn_parts = fqn.split(trino_table.fullyQualifiedName.root)
Expand Down
37 changes: 33 additions & 4 deletions ingestion/src/metadata/ingestion/source/database/trino/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,15 @@ def _get_columns(self, connection: Connection, table_name: str, schema: str = No
return columns


def _table_names_predicate(table_names: Iterable[str]) -> str:
"""
`and "table_name" IN (...)` clause for TRINO_TABLE_COMMENTS. Names come from Trino's own
listing, but they are still embedded as SQL literals, so single quotes are doubled.
"""
literals = ", ".join("'" + name.replace("'", "''") + "'" for name in sorted(table_names))
return f' and "table_name" IN ({literals})\n'


def get_table_comment( # pylint: disable=unused-argument
self,
connection: Connection,
Expand Down Expand Up @@ -258,10 +267,15 @@ def get_table_comment( # pylint: disable=unused-argument
or schema not in self.processed_schema
):
self.processed_schema.add(schema)
self.get_all_table_comments(
connection,
TRINO_TABLE_COMMENTS.format(catalog_name=catalog_name, schema_name=schema),
)
query = TRINO_TABLE_COMMENTS.format(catalog_name=catalog_name, schema_name=schema)
# Restrict the schema-wide scan to the tables the source kept after applying
# tableFilterPattern (recorded by TrinoSource.get_tables_name_and_type). Without
# this, a run scoped to a few tables of a large schema still reads every row of
# system.metadata.table_comments and can hit the query timeout.
table_names = getattr(self, "comment_table_names", {}).get(schema)
if table_names:
query += _table_names_predicate(table_names)
self.get_all_table_comments(connection, query)
return {"text": self.all_table_comments.get((table_name, schema)) or None}
except error.TrinoQueryError as exe:
if exe.error_name in (error.PERMISSION_DENIED,):
Expand Down Expand Up @@ -378,6 +392,21 @@ def query_table_names_and_types(self, schema_name: str) -> Iterable[TableNameAnd
TableNameAndType(name=name, type_=table_type) for name in self.inspector.get_table_names(schema_name) or []
]

def get_tables_name_and_type(self) -> Optional[Iterable[Tuple[str, TableType]]]: # noqa: UP006, UP045
"""
Materialise the filtered table list of the schema before the first table is
processed and hand it to the dialect, so `get_table_comment` only fetches the
comments of the tables that survived `tableFilterPattern` instead of scanning
`system.metadata.table_comments` for the whole schema.
"""
schema_name = self.context.get().database_schema
tables = list(super().get_tables_name_and_type() or [])
dialect = self.engine.dialect
if not hasattr(dialect, "comment_table_names"):
dialect.comment_table_names = {}
dialect.comment_table_names[schema_name] = {name for name, _ in tables}
yield from tables

def get_database_names(self) -> Iterable[str]:
configured_catalog = self.service_connection.catalog
if configured_catalog:
Expand Down
31 changes: 31 additions & 0 deletions ingestion/tests/unit/source/database/trino/test_lineage.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,34 @@ def test_get_cross_database_schema_fqn_parses_quoted_schema_from_fqn():
)

assert result == 'repro_postgres.source_db."source.schema"'


def test_get_cross_database_schema_fqn_reads_schema_reference_name_as_string():
"""databaseSchema is an EntityReference whose name is a plain string (no .root)."""
from metadata.generated.schema.type.entityReference import EntityReference

metadata = MagicMock()

trino_table = MagicMock()
trino_table.databaseSchema = EntityReference(
id="33333333-3333-3333-3333-333333333333",
type="databaseSchema",
name="source_schema",
fullyQualifiedName="repro_trino.postgres.source_schema",
)
trino_table.fullyQualifiedName.root = "repro_trino.postgres.source_schema.customer"

lineage_source = TrinoLineageSourceTestDouble(metadata)

with patch(
"metadata.ingestion.source.database.trino.lineage.fqn.search_database_schema_from_es",
return_value=None,
) as mock_search_database_schema:
result = lineage_source._get_cross_database_schema_fqn(
"repro_postgres.source_db",
trino_table,
{},
)

assert result == "repro_postgres.source_db.source_schema"
assert mock_search_database_schema.call_args.kwargs["schema_name"] == "source_schema"
70 changes: 70 additions & 0 deletions ingestion/tests/unit/test_sink_lineage_none_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Copyright 2026 Collate
# Licensed under the Collate Community License, Version 1.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
MetadataRestSink.write_lineage must not crash when add_lineage returns None,
which happens when the edge is written but reading back the origin node's
lineage fails (e.g. 404 because its graph references a deleted entity).
"""
from unittest.mock import MagicMock

from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest
from metadata.generated.schema.type.entityLineage import EntitiesEdge
from metadata.generated.schema.type.entityReference import EntityReference
from metadata.ingestion.sink.metadata_rest import (
MetadataRestSink,
MetadataRestSinkConfig,
)

FROM_ID = "ab8f49d7-afba-4164-ba06-a0dc6300c5d2"
TO_ID = "615ff273-1180-4fc2-8682-b5e4a646a6fe"

LINEAGE_REQUEST = AddLineageRequest(
edge=EntitiesEdge(
fromEntity=EntityReference(id=FROM_ID, type="dashboardDataModel"),
toEntity=EntityReference(id=TO_ID, type="chart"),
)
)


def _sink_with_add_lineage_returning(value) -> MetadataRestSink:
metadata = MagicMock()
metadata.add_lineage.return_value = value
return MetadataRestSink(config=MetadataRestSinkConfig(), metadata=metadata)


def test_write_lineage_handles_none_response():
sink = _sink_with_add_lineage_returning(None)

result = sink.write_lineage(LINEAGE_REQUEST)

assert result.left is None
# No FQN to report, so the sink falls back to the "{type}:{uuid}" label.
assert result.right == f"dashboardDataModel:{FROM_ID}"


def test_write_lineage_error_response_is_reported():
sink = _sink_with_add_lineage_returning({"error": "Error 400 trying to PUT"})

result = sink.write_lineage(LINEAGE_REQUEST)

assert result.left is not None
assert "Error 400" in result.left.error


def test_write_lineage_success_returns_entity_fqn():
sink = _sink_with_add_lineage_returning(
{"entity": {"fullyQualifiedName": "service.model_1"}}
)

result = sink.write_lineage(LINEAGE_REQUEST)

assert result.left is None
assert result.right == "service.model_1"
Loading
Loading