diff --git a/ingestion/pyproject.toml b/ingestion/pyproject.toml index 66fc22a1ef68..c1297e70ac6e 100644 --- a/ingestion/pyproject.toml +++ b/ingestion/pyproject.toml @@ -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" } diff --git a/ingestion/src/metadata/ingestion/lineage/sql_lineage.py b/ingestion/src/metadata/ingestion/lineage/sql_lineage.py index 35eb410ade16..022dcd19010b 100644 --- a/ingestion/src/metadata/ingestion/lineage/sql_lineage.py +++ b/ingestion/src/metadata/ingestion/lineage/sql_lineage.py @@ -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 (`.*..`) 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 diff --git a/ingestion/src/metadata/ingestion/sink/metadata_rest.py b/ingestion/src/metadata/ingestion/sink/metadata_rest.py index 60b5b8cd3504..ee1c5753cfbb 100644 --- a/ingestion/src/metadata/ingestion/sink/metadata_rest.py +++ b/ingestion/src/metadata/ingestion/sink/metadata_rest.py @@ -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.""" @@ -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", @@ -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]: @@ -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] diff --git a/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py index 048825d00e33..89ee8ed5e086 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py @@ -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, @@ -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), ) @@ -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, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/superset/mixin.py b/ingestion/src/metadata/ingestion/source/dashboard/superset/mixin.py index f29a6cc90e14..9f988041846b 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/superset/mixin.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/superset/mixin.py @@ -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 diff --git a/ingestion/src/metadata/ingestion/source/database/trino/lineage.py b/ingestion/src/metadata/ingestion/source/database/trino/lineage.py index aeaa6f4ffe6b..82a9728f7275 100644 --- a/ingestion/src/metadata/ingestion/source/database/trino/lineage.py +++ b/ingestion/src/metadata/ingestion/source/database/trino/lineage.py @@ -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) diff --git a/ingestion/src/metadata/ingestion/source/database/trino/metadata.py b/ingestion/src/metadata/ingestion/source/database/trino/metadata.py index 33f092fed0b8..f1f09dd65f04 100644 --- a/ingestion/src/metadata/ingestion/source/database/trino/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/trino/metadata.py @@ -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, @@ -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,): @@ -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: diff --git a/ingestion/tests/unit/source/database/trino/test_lineage.py b/ingestion/tests/unit/source/database/trino/test_lineage.py index 233ff756ddde..2d04927366bf 100644 --- a/ingestion/tests/unit/source/database/trino/test_lineage.py +++ b/ingestion/tests/unit/source/database/trino/test_lineage.py @@ -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" diff --git a/ingestion/tests/unit/test_sink_lineage_none_response.py b/ingestion/tests/unit/test_sink_lineage_none_response.py new file mode 100644 index 000000000000..339b9389c685 --- /dev/null +++ b/ingestion/tests/unit/test_sink_lineage_none_response.py @@ -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" diff --git a/ingestion/tests/unit/topology/dashboard/test_superset_charts_fallback.py b/ingestion/tests/unit/topology/dashboard/test_superset_charts_fallback.py new file mode 100644 index 000000000000..c0ba72d9ae7d --- /dev/null +++ b/ingestion/tests/unit/topology/dashboard/test_superset_charts_fallback.py @@ -0,0 +1,75 @@ +# 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. +""" +Tests for the Superset 5.0+ position_json fallback in +SupersetSourceMixin._get_charts_of_dashboard +""" +from types import SimpleNamespace +from unittest.mock import MagicMock + +from metadata.ingestion.source.dashboard.superset.mixin import SupersetSourceMixin +from metadata.ingestion.source.dashboard.superset.models import ( + DashboardResult, + FetchDashboard, + FetchedDashboard, +) + + +def _get_charts_of_dashboard(client, dashboard): + """Call the mixin method unbound: the class is abstract, and the method + only relies on self.client""" + stub_self = SimpleNamespace(client=client) + return SupersetSourceMixin._get_charts_of_dashboard(stub_self, dashboard) + + +def test_db_mode_engine_without_position_json_does_not_call_api_fallback(caplog): + """ + In DB mode self.client is a SQLAlchemy Engine, which has no + fetch_dashboard method. The API fallback must be skipped instead of + raising `'Engine' object has no attribute 'fetch_dashboard'`. + """ + engine = MagicMock(spec=["connect", "execute"]) + dashboard = FetchDashboard(id=464, position_json=None) + + result = _get_charts_of_dashboard(engine, dashboard) + + assert result == [] + assert not any( + "Failed to charts of dashboard" in record.message for record in caplog.records + ) + + +def test_api_mode_fallback_fetches_dashboard_details(): + client = MagicMock(spec=["fetch_dashboard"]) + client.fetch_dashboard.return_value = FetchedDashboard( + id=14, + result=DashboardResult( + position_json='{"CHART-abc": {"meta": {"chartId": 69}}}' + ), + ) + dashboard = FetchDashboard(id=14, position_json=None) + + result = _get_charts_of_dashboard(client, dashboard) + + client.fetch_dashboard.assert_called_once_with(14) + assert result == [69] + + +def test_position_json_present_skips_fallback(): + client = MagicMock(spec=["fetch_dashboard"]) + dashboard = FetchDashboard( + id=7, position_json='{"CHART-abc": {"meta": {"chartId": 42}}}' + ) + + result = _get_charts_of_dashboard(client, dashboard) + + client.fetch_dashboard.assert_not_called() + assert result == [42] diff --git a/ingestion/tests/unit/topology/database/test_trino_metadata.py b/ingestion/tests/unit/topology/database/test_trino_metadata.py index 6af051de7bbd..521d55bdf375 100644 --- a/ingestion/tests/unit/topology/database/test_trino_metadata.py +++ b/ingestion/tests/unit/topology/database/test_trino_metadata.py @@ -12,15 +12,19 @@ """Test Trino Metadata""" import unittest -from unittest.mock import Mock +from unittest.mock import Mock, patch from trino.sqlalchemy.dialect import TrinoDialect from metadata.generated.schema.entity.data.table import TableType -from metadata.ingestion.source.database.common_db_source import TableNameAndType +from metadata.ingestion.source.database.common_db_source import ( + CommonDbSourceService, + TableNameAndType, +) from metadata.ingestion.source.database.trino.metadata import ( TrinoSource, _get_columns, + get_table_comment, get_view_definition, ) @@ -281,5 +285,58 @@ def test_null_comment_is_none(self): assert columns[0]["comment"] is None +class TestTrinoTableCommentsFilter: + """The schema-wide table_comments scan is restricted to the tables the source kept""" + + @staticmethod + def _dialect(comment_table_names): + dialect = Mock() + dialect._get_default_catalog_name.return_value = "test_catalog" + dialect._get_default_schema_name.return_value = None + dialect.processed_schema = set() + dialect.comment_table_names = comment_table_names + dialect.queries = [] + + def record_query(connection, query): + dialect.queries.append(query) + dialect.all_table_comments = {("orders", "test_schema"): "Orders"} + dialect.current_db = connection.engine.url.database + + dialect.get_all_table_comments.side_effect = record_query + return dialect + + def test_query_restricted_to_recorded_tables(self): + dialect = self._dialect({"test_schema": {"orders", "o'neil"}}) + + comment = get_table_comment(dialect, Mock(), "orders", "test_schema") + + assert comment == {"text": "Orders"} + assert len(dialect.queries) == 1 + assert '"schema_name" = \'test_schema\'' in dialect.queries[0] + assert "and \"table_name\" IN ('o''neil', 'orders')" in dialect.queries[0] + + def test_query_unrestricted_without_recorded_tables(self): + dialect = self._dialect({}) + + get_table_comment(dialect, Mock(), "orders", "test_schema") + + assert len(dialect.queries) == 1 + assert '"table_name" IN' not in dialect.queries[0] + + def test_get_tables_name_and_type_records_filtered_tables(self): + source = TrinoSource.__new__(TrinoSource) + source.context = Mock() + source.context.get.return_value.database_schema = "test_schema" + source.engine = Mock() + source.engine.dialect = Mock(spec=[]) + kept = [("orders", TableType.Iceberg), ("customers_v", TableType.View)] + + with patch.object(CommonDbSourceService, "get_tables_name_and_type", return_value=iter(kept)): + tables = list(source.get_tables_name_and_type()) + + assert tables == kept + assert source.engine.dialect.comment_table_names == {"test_schema": {"orders", "customers_v"}} + + if __name__ == "__main__": unittest.main()