diff --git a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py index 14ea960d380b..bba36661196e 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py @@ -213,8 +213,11 @@ def get_org_workspace_data(self) -> Iterable[Group | None]: self.dashboard_listing, ) ) + # Tiles and tables are read only for the dashboards and data models the + # filters keep; the workspace still lists every one, for the listing counters. for dashboard in workspace.dashboards: - # add the tiles to the dashboards + if not self._kept_dashboard(dashboard): + continue dashboard.tiles.extend( self.client.api_client.fetch_all_org_tiles(group_id=workspace.id, dashboard_id=dashboard.id) or [] @@ -236,7 +239,8 @@ def get_org_workspace_data(self) -> Iterable[Group | None]: ) ) for dataset in workspace.datasets: - # add the tables to the datasets + if not self._kept_datamodel(dataset): + continue dataset.tables.extend( self.client.api_client.fetch_dataset_tables(group_id=workspace.id, dataset_id=dataset.id) or [] @@ -245,6 +249,15 @@ def get_org_workspace_data(self) -> Iterable[Group | None]: else: logger.error("Unable to fetch any PowerBI workspaces") + def _kept_dashboard(self, dashboard: PowerBIDashboard) -> bool: + """Whether `get_dashboard` will process the dashboard. Decides only; it does not report.""" + name = self.get_dashboard_name(dashboard) + return bool(name) and not filter_by_dashboard(self.source_config.dashboardFilterPattern, name) + + def _kept_datamodel(self, dataset: Dataset) -> bool: + """Whether `_filtered_datamodels` will keep the dataset. Decides only; it does not report.""" + return bool(dataset.name) and not filter_by_datamodel(self.source_config.dataModelFilterPattern, dataset.name) + def _paginate_project_filter_pattern(self, filter_pattern): """ paginate include filters if more then `10` filters diff --git a/ingestion/src/metadata/ingestion/source/database/common_db_source.py b/ingestion/src/metadata/ingestion/source/database/common_db_source.py index b170f1f95a2c..26ec69c4911c 100644 --- a/ingestion/src/metadata/ingestion/source/database/common_db_source.py +++ b/ingestion/src/metadata/ingestion/source/database/common_db_source.py @@ -429,6 +429,7 @@ def get_tables_name_and_type(self) -> Iterable[tuple[str, TableType]] | None: database_name=self.context.get().database, schema_name=self.context.get().database_schema, table_name=view_name, + skip_es_search=True, ) if filter_by_table( diff --git a/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py b/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py index 86e2ccca197a..3bbd6d343908 100644 --- a/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py +++ b/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py @@ -165,6 +165,10 @@ def get_schema_name_list(self) -> list[str]: need to be overridden by sources """ + def get_raw_database_schema_names(self) -> Iterable[str]: + """List schemas without filtering or reporting; mark-deleted filters them itself.""" + yield from self.get_schema_name_list() + def get_database_schema_names(self) -> Iterable[str]: for schema in self.get_schema_name_list(): schema_fqn = fqn.build( @@ -251,6 +255,7 @@ def get_tables_name_and_type(self) -> Iterable[tuple[str, TableType]] | None: database_name=self.context.get().database, schema_name=self.context.get().database_schema, table_name=table_name, + skip_es_search=True, ) if filter_by_table( self.source_config.tableFilterPattern, diff --git a/ingestion/src/metadata/ingestion/source/database/database_service.py b/ingestion/src/metadata/ingestion/source/database/database_service.py index 3c0b31dbad0a..e6b72f5a4da9 100644 --- a/ingestion/src/metadata/ingestion/source/database/database_service.py +++ b/ingestion/src/metadata/ingestion/source/database/database_service.py @@ -849,14 +849,12 @@ def mark_databases_as_deleted(self): f"Mark Deleted Databases set to True. Processing service [{self.context.get().database_service}]" ) - # We need to include ALL databases from the source in the source state - # This includes both processed databases and all databases (filtered-in and filtered-out) - # to ensure we mark as deleted any databases that were previously ingested but are now - # filtered out, as well as any databases that were processed in this run + # Keep every database the filter lets in, processed or not; a database that is now + # filtered out is left out, so one ingested earlier is marked as deleted. Ingestion + # already reported the excluded ones, so this listing does not report them again. all_database_fqns = set() - # Get all databases from the source (both filtered-in and filtered-out) - for database_name in self._get_filtered_database_names(): + for database_name in self._get_filtered_database_names(add_to_status=False): database_fqn = fqn.build( self.metadata, entity_type=Database, diff --git a/ingestion/src/metadata/utils/filters.py b/ingestion/src/metadata/utils/filters.py index 0b5ee16a3be8..4b3764b6a123 100644 --- a/ingestion/src/metadata/utils/filters.py +++ b/ingestion/src/metadata/utils/filters.py @@ -102,7 +102,7 @@ def filter_by_schema(schema_filter_pattern: FilterPattern | None, schema_name: s """ Return True if the schema needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param schema_filter_pattern: Model defining schema filtering logic :param schema fqn: table schema fqn @@ -115,7 +115,7 @@ def filter_by_table(table_filter_pattern: FilterPattern | None, table_name: str) """ Return True if the table needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param table_filter_pattern: Model defining schema filtering logic :param table_fqn: table fqn @@ -139,7 +139,7 @@ def filter_by_chart(chart_filter_pattern: FilterPattern | None, chart_name: str) """ Return True if the chart needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param chart_filter_pattern: Model defining chart filtering logic :param chart_name: chart name @@ -152,7 +152,7 @@ def filter_by_topic(topic_filter_pattern: FilterPattern | None, topic_name: str) """ Return True if the topic needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param topic_filter_pattern: Model defining chart filtering logic :param topic_name: topic name @@ -165,7 +165,7 @@ def filter_by_dashboard(dashboard_filter_pattern: FilterPattern | None, dashboar """ Return True if the dashboard needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param dashboard_filter_pattern: Model defining dashboard filtering logic :param dashboard_name: dashboard name @@ -181,7 +181,7 @@ def filter_by_stored_procedure( """ Return True if the stored procedure needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param stored_procedure_filter_pattern: Model defining stored procedure filtering logic :param stored_procedure_name: stored procedure name @@ -194,7 +194,7 @@ def filter_by_fqn(fqn_filter_pattern: FilterPattern | None, fqn: str) -> bool: """ Return True if the FQN needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param fqn_filter_pattern: Model defining FQN filtering logic :param fqn: table FQN name @@ -207,7 +207,7 @@ def filter_by_database(database_filter_pattern: FilterPattern | None, database_n """ Return True if the schema needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param database_filter_pattern: Model defining database filtering logic :param database_name: database name @@ -220,7 +220,7 @@ def filter_by_pipeline(pipeline_filter_pattern: FilterPattern | None, pipeline_n """ Return True if the schema needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param pipeline_filter_pattern: Model defining the pipeline filtering logic :param pipeline_name: pipeline name @@ -233,7 +233,7 @@ def filter_by_mlmodel(mlmodel_filter_pattern: FilterPattern | None, mlmodel_name """ Return True if the mlmodel needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param mlmodel_filter_pattern: Model defining the mlmodel filtering logic :param mlmodel_name: mlmodel name @@ -246,7 +246,7 @@ def filter_by_container(container_filter_pattern: FilterPattern | None, containe """ Return True if the container needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param container_filter_pattern: Container defining the container filtering logic :param container_name: container name @@ -259,7 +259,7 @@ def filter_by_datamodel(datamodel_filter_pattern: FilterPattern | None, datamode """ Return True if the models needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param datamodel_filter_pattern: Model defining data model filtering logic :param datamodel_name: data model name @@ -272,7 +272,7 @@ def filter_by_project(project_filter_pattern: FilterPattern | None, project_name """ Return True if the project needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param project_filter_pattern: Model defining project filtering logic :param project_name: project name @@ -285,7 +285,7 @@ def filter_by_search_index(search_index_filter_pattern: FilterPattern | None, se """ Return True if the models needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param search_index_filter_pattern: Model defining search index filtering logic :param search_index_name: search index name @@ -298,7 +298,7 @@ def filter_by_classification(classification_pattern: FilterPattern | None, class """ Return True if the models needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param search_index_filter_pattern: Model defining search index filtering logic :param search_index_name: search index name @@ -346,7 +346,7 @@ def filter_by_collection(collection_pattern: FilterPattern | None, collection_na """ Return True if the models needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param collection_pattern: Model defining collection filtering logic :param collection_name: collection name @@ -359,7 +359,7 @@ def filter_by_endpoint(endpoint_pattern: FilterPattern | None, endpoint_name: st """ Return True if the endpoint needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param endpoint_pattern: Model defining endpoint filtering logic :param endpoint_name: endpoint name @@ -372,7 +372,7 @@ def filter_by_tag(tag_pattern: FilterPattern | None, tag_name: str) -> bool: """ Return True if the models needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param tag_pattern: Model defining tag filtering logic :param tag_name: tag name @@ -385,7 +385,7 @@ def filter_by_spreadsheet(spreadsheet_filter_pattern: FilterPattern | None, spre """ Return True if the spreadsheet needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param spreadsheet_filter_pattern: Model defining spreadsheet filtering logic :param spreadsheet_name: spreadsheet name @@ -398,7 +398,7 @@ def filter_by_directory(directory_filter_pattern: FilterPattern | None, director """ Return True if the directory needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param directory_filter_pattern: Model defining directory filtering logic :param directory_name: directory name @@ -411,7 +411,7 @@ def filter_by_file(file_filter_pattern: FilterPattern | None, file_name: str) -> """ Return True if the file needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param file_filter_pattern: Model defining file filtering logic :param file_name: file name @@ -424,7 +424,7 @@ def filter_by_worksheet(worksheet_filter_pattern: FilterPattern | None, workshee """ Return True if the worksheet needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param worksheet_filter_pattern: Model defining worksheet filtering logic :param worksheet_name: worksheet name @@ -437,7 +437,7 @@ def filter_by_server(server_filter_pattern: FilterPattern | None, server_name: s """ Return True if the MCP server needs to be filtered, False otherwise - Include takes precedence over exclude + Exclude takes precedence over include :param server_filter_pattern: Model defining server filtering logic :param server_name: server name diff --git a/ingestion/tests/unit/topology/dashboard/test_powerbi_fetch_pruning.py b/ingestion/tests/unit/topology/dashboard/test_powerbi_fetch_pruning.py new file mode 100644 index 000000000000..3d25f25e0aaa --- /dev/null +++ b/ingestion/tests/unit/topology/dashboard/test_powerbi_fetch_pruning.py @@ -0,0 +1,114 @@ +# Copyright 2025 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. +""" +Non-admin PowerBI reads tiles and dataset tables only for the dashboards and data models the +filters keep. Filtering itself, and its counters and reports, stay where they were. +""" + +from unittest.mock import MagicMock, patch + +import pytest + +from metadata.ingestion.source.dashboard.powerbi.metadata import PowerbiSource +from metadata.ingestion.source.dashboard.powerbi.models import Dataset, Group, PowerBIDashboard + +SERVICE_NAME = "powerbi_pruning" + + +@pytest.fixture +def make_source(): + def _make(**pipeline) -> PowerbiSource: + config = { + "type": "powerbi", + "serviceName": SERVICE_NAME, + "serviceConnection": { + "config": { + "type": "PowerBI", + "clientId": "client_id", + "clientSecret": "secret", + "tenantId": "tenant_id", + "useAdminApis": False, + } + }, + "sourceConfig": {"config": {"type": "DashboardMetadata", "includeOwners": False, **pipeline}}, + } + with ( + patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection"), + patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") as create_connection, + ): + create_connection.return_value.client = False + source = PowerbiSource.create(config, MagicMock()) + source.client = MagicMock() + source.context.get = MagicMock(return_value=MagicMock(dashboard_service=SERVICE_NAME)) + api = source.client.api_client + api.fetch_all_workspaces.return_value = [Group(id="ws-1", name="Sales")] + api.fetch_all_org_dashboards.return_value = [ + PowerBIDashboard(id="d-keep", displayName="kept board"), + PowerBIDashboard(id="d-skip", displayName="skip board"), + ] + api.fetch_all_org_reports.return_value = [] + api.fetch_all_org_datasets.return_value = [ + Dataset(id="ds-keep", name="kept model"), + Dataset(id="ds-skip", name="skip model"), + ] + api.fetch_all_org_tiles.return_value = [] + api.fetch_dataset_tables.return_value = [] + return source + + return _make + + +def _read_workspaces(source: PowerbiSource) -> list[Group]: + return list(source.get_org_workspace_data()) + + +def test_tiles_are_read_only_for_dashboards_the_filter_keeps(make_source): + source = make_source(dashboardFilterPattern={"excludes": ["skip.*"]}) + + _read_workspaces(source) + + fetched = [c.kwargs["dashboard_id"] for c in source.client.api_client.fetch_all_org_tiles.call_args_list] + assert fetched == ["d-keep"] + + +def test_dataset_tables_are_read_only_for_data_models_the_filter_keeps(make_source): + source = make_source(dataModelFilterPattern={"excludes": ["skip.*"]}) + + _read_workspaces(source) + + fetched = [c.kwargs["dataset_id"] for c in source.client.api_client.fetch_dataset_tables.call_args_list] + assert fetched == ["ds-keep"] + + +def test_without_filters_every_dashboard_and_data_model_is_read(make_source): + source = make_source() + + _read_workspaces(source) + + api = source.client.api_client + assert [c.kwargs["dashboard_id"] for c in api.fetch_all_org_tiles.call_args_list] == ["d-keep", "d-skip"] + assert [c.kwargs["dataset_id"] for c in api.fetch_dataset_tables.call_args_list] == ["ds-keep", "ds-skip"] + + +def test_excluded_items_are_still_listed_counted_and_reported_once(make_source): + source = make_source( + dashboardFilterPattern={"excludes": ["skip.*"]}, + dataModelFilterPattern={"excludes": ["skip.*"]}, + ) + (workspace,) = _read_workspaces(source) + source.context.get.return_value.workspace = workspace + source.state.enter(workspace) + + # The workspace still carries every item, so the listing counters see the excluded ones. + assert [d.id for d in workspace.dashboards] == ["d-keep", "d-skip"] + assert [d.id for d in workspace.datasets] == ["ds-keep", "ds-skip"] + assert [d.id for d in source._filtered_datamodels()] == ["ds-keep"] + assert source.status.filtered == [{"skip model": "Data model filtered out."}] diff --git a/ingestion/tests/unit/topology/database/test_filter_decisions.py b/ingestion/tests/unit/topology/database/test_filter_decisions.py new file mode 100644 index 000000000000..7de8d825ddef --- /dev/null +++ b/ingestion/tests/unit/topology/database/test_filter_decisions.py @@ -0,0 +1,103 @@ +# Copyright 2025 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. +"""Filter decisions in the database topology: no search lookups to decide, each exclusion reported once.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from metadata.generated.schema.entity.data.table import TableType +from metadata.generated.schema.type.filterPattern import FilterPattern +from metadata.ingestion.source.database.common_db_source import CommonDbSourceService, TableNameAndType +from metadata.ingestion.source.database.common_nosql_source import CommonNoSQLSource +from metadata.ingestion.source.database.common_nosql_source import TableNameAndType as CollectionNameAndType +from metadata.ingestion.source.database.database_service import DatabaseServiceSource + +SEARCH = "metadata.utils.fqn.search_table_from_es" +EXCLUDE_SKIP = FilterPattern(excludes=[".*skip.*"]) + + +def _source(**source_config) -> MagicMock: + source = MagicMock() + source.source_config = MagicMock(useFqnForFiltering=False, **source_config) + context = source.context.get.return_value + context.database_service = "svc" + context.database = "db" + context.database_schema = "sch" + return source + + +@pytest.mark.parametrize("use_fqn", [False, True]) +def test_views_are_filtered_without_a_search_lookup(use_fqn): + source = _source(includeTables=False, includeViews=True, tableFilterPattern=EXCLUDE_SKIP) + source.source_config.useFqnForFiltering = use_fqn + source.query_view_names_and_types.return_value = [ + TableNameAndType(name="keep_view", type_=TableType.View), + TableNameAndType(name="skip_view", type_=TableType.View), + ] + source.standardize_table_name.side_effect = lambda _schema, name: name + + with patch(SEARCH) as search: + kept = list(CommonDbSourceService.get_tables_name_and_type(source)) + + search.assert_not_called() + assert kept == [("keep_view", TableType.View)] + source.status.filter.assert_called_once_with("svc.db.sch.skip_view", "Table Filtered Out") + + +def test_nosql_collections_are_filtered_without_a_search_lookup(): + source = _source(includeTables=True, includeViews=False, tableFilterPattern=EXCLUDE_SKIP) + source.query_table_names_and_types.return_value = [ + CollectionNameAndType(name="keep_coll"), + CollectionNameAndType(name="skip_coll"), + ] + + with patch(SEARCH) as search: + kept = list(CommonNoSQLSource.get_tables_name_and_type(source)) + + search.assert_not_called() + assert kept == [("keep_coll", TableType.Regular)] + + +def test_nosql_mark_deleted_listing_does_not_report_excluded_schemas_again(): + source = _source(schemaFilterPattern=EXCLUDE_SKIP) + source.get_schema_name_list.return_value = ["keep_db", "skip_db"] + source.get_database_schema_names = CommonNoSQLSource.get_database_schema_names.__get__(source) + source.get_raw_database_schema_names = CommonNoSQLSource.get_raw_database_schema_names.__get__(source) + + kept = list(DatabaseServiceSource._get_filtered_schema_names(source, add_to_status=False)) + + assert kept == ["keep_db"] + source.status.filter.assert_not_called() + + +def test_nosql_ingestion_still_reports_each_excluded_schema(): + source = _source(schemaFilterPattern=EXCLUDE_SKIP) + source.get_schema_name_list.return_value = ["keep_db", "skip_db"] + + assert list(CommonNoSQLSource.get_database_schema_names(source)) == ["keep_db"] + source.status.filter.assert_called_once_with("svc.db.skip_db", "Schema Filtered Out") + + +def test_mark_deleted_databases_does_not_report_excluded_databases_again(): + source = _source(markDeletedDatabases=True, databaseFilterPattern=EXCLUDE_SKIP) + source.get_database_names_raw.return_value = ["keep_db", "skip_db"] + source.database_entity_source_state = {"svc.keep_db"} + source._get_filtered_database_names = DatabaseServiceSource._get_filtered_database_names.__get__(source) + + with patch( + "metadata.ingestion.source.database.database_service.delete_entity_from_source", return_value=iter(()) + ) as delete: + list(DatabaseServiceSource.mark_databases_as_deleted(source)) + + source.status.filter.assert_not_called() + # The seen-set is unchanged: the processed databases plus every filtered-in one. + assert delete.call_args.kwargs["entity_source_state"] == {"svc.keep_db"}