diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index 1eaccfe29df9..269caa996c50 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -15,6 +15,53 @@ the one you are on and the one you are moving to, not just the target. ## Next +### BigQuery: `dataset_pattern` entries listing several datasets with `|` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) + +**Affected config:** a BigQuery recipe with `match_fully_qualified_names: true` (the default) and a +`dataset_pattern` allow or deny entry that has no `.` and uses `|`: + +```yaml +dataset_pattern: + deny: + - "staging|tmp" +``` + +**Before:** only the first alternative got the project prefix: `.*\.staging|tmp`. The `tmp` alternative +was compared against `.` and matched only when the project ID itself started +with `tmp`. So `tmp` datasets were not denied (in `allow`, they were not ingested), while every dataset +in a project whose ID starts with `tmp` was. + +**Now:** the entry becomes `.*\.(?:staging|tmp)`, so in every project, datasets whose names start with +`staging` or `tmp` are denied (or, in `allow`, ingested). Review such entries: datasets they used to miss +are now filtered or ingested. + +**Unchanged:** an entry that contains a `.` is still matched as written against +`.`. `^staging_.*` still matches nothing; write `.*\.staging_.*` instead. +This includes an entry with `|` where any alternative has a `.`, such as `a|proj\.b`: it is kept +as written, so its `a` alternative is still matched against the start of +`.`, that is, against project IDs. Write each alternative in full +(`.*\.a|proj\.b`) or split the entry into one per dataset. + +### Snowflake: schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) + +**Affected config:** any Snowflake recipe for an account with a schema whose name ends in +`INFORMATION_SCHEMA` but is not `INFORMATION_SCHEMA` itself, such as `MY_INFORMATION_SCHEMA`. + +**Before:** every recipe got the deny rule `.*INFORMATION_SCHEMA$`, which is matched case-insensitively +against the schema name (or `.` with `match_fully_qualified_names: true`). It also +matched `MY_INFORMATION_SCHEMA`, so that schema was skipped silently. + +**Now:** the rule is `^(.*\.)?INFORMATION_SCHEMA$`. It skips only `INFORMATION_SCHEMA` itself, and +schemas such as `MY_INFORMATION_SCHEMA` are ingested. A recipe that already lists `.*INFORMATION_SCHEMA$` +in `schema_pattern.deny` keeps that entry and still skips them. To keep skipping such a schema, add +it to the deny list, in either matching mode: + +```yaml +schema_pattern: + deny: + - ".*MY_INFORMATION_SCHEMA$" +``` + ### `tags_to_term` transformer matches full tag names and maps column tags to columns The `tags_to_term` ingestion transformer has changed in four ways ([PR #21479](https://github.com/datahub-project/datahub/pull/21479)): diff --git a/metadata-ingestion/src/datahub/configuration/common.py b/metadata-ingestion/src/datahub/configuration/common.py index bc7b23a6eadc..2d27b9dc1029 100644 --- a/metadata-ingestion/src/datahub/configuration/common.py +++ b/metadata-ingestion/src/datahub/configuration/common.py @@ -524,16 +524,22 @@ def is_allow_all(self) -> bool: def with_deny(self, *rules: str) -> Self: """A new pattern with `rules` added to the deny list, each listed once: - duplicates already in the deny list are collapsed too. Rebuilt rather - than mutated or model_copy'd: the copy would carry this instance's - compiled-regex caches. + duplicates already in the deny list are collapsed too.""" + return self.with_fields(deny=deduplicate_list([*self.deny, *rules])) + + def with_fields(self, **overrides: Union[List[str], bool]) -> Self: + """A fresh pattern with this one's fields, `overrides` replacing some. + + Use this to derive a pattern; never edit `allow`/`deny` in place, + and never `model_copy` (or `copy.deepcopy`). The compiled regexes are + cached on first `allowed()`/`denied()` call, and those keep `__dict__`, + so the result would go on matching the old lists. The rebuild round-trips through `model_dump()`, so a subclass is only preserved faithfully if its fields survive that: no excluded or aliased fields. """ - deny = deduplicate_list([*self.deny, *rules]) - return type(self).model_validate({**self.model_dump(), "deny": deny}) + return type(self).model_validate({**self.model_dump(), **overrides}) def allowed(self, string: str) -> bool: if self.denied(string): diff --git a/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py b/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py index c1d4acf783ee..b7d9b28c91e5 100644 --- a/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py +++ b/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py @@ -321,8 +321,7 @@ def _trial_pattern( """The recipe's pattern with each --try-* flag replacing only its own half, every other field (`ignoreCase`) kept. - Rebuilt rather than model_copy'd: the copy carries the compiled regexes - the recipe's pattern cached on first use, and would match those. + Built with `AllowDenyPattern.with_fields`, not model_copy'd. """ # Compiled here, before any hook runs: AllowDenyPattern compiles lazily, # so a malformed regex would otherwise surface inside a connector's hook @@ -335,12 +334,12 @@ def _trial_pattern( raise ProbeArgumentError( f"{flag} {regex!r} is not a valid regular expression ({exc.msg})" ) from None - fields = recipe_pattern.model_dump() + overrides: Dict[str, List[str]] = {} if try_allow: - fields["allow"] = list(try_allow) + overrides["allow"] = list(try_allow) if try_deny: - fields["deny"] = list(try_deny) - return type(recipe_pattern).model_validate(fields) + overrides["deny"] = list(try_deny) + return recipe_pattern.with_fields(**overrides) def _with_trial_pattern( diff --git a/metadata-ingestion/src/datahub/ingestion/agent/verdicts.py b/metadata-ingestion/src/datahub/ingestion/agent/verdicts.py index 862e01ad163b..1d3b2491d4a3 100644 --- a/metadata-ingestion/src/datahub/ingestion/agent/verdicts.py +++ b/metadata-ingestion/src/datahub/ingestion/agent/verdicts.py @@ -150,12 +150,13 @@ def _listing_command_for(config: object, container_kind: str) -> Optional[str]: return listing_command_for_kind(config, provider_cls, container_kind) -# An entry of the form `^?.*$`, where the literal carries no dot or -# regex syntax, matches `.` exactly when it matches ``: -# the suffix cannot reach back across the dot. So the question is not whether a -# pattern filters -- a deny list filters and is still blind to the container -- -# but whether the container could change what it says. -_CONTAINER_BLIND = re.compile(r"\^?\.\*[A-Za-z0-9_\-]*\$") +# An entry of the form `^?.*$` or `^(.*\.)?$`, where the +# literal carries no dot or regex syntax, matches `.` exactly +# when it matches ``: the suffix cannot reach back across the dot. So the +# question is not whether a pattern filters -- a deny list filters and is still +# blind to the container -- but whether the container could change what it +# says. +_CONTAINER_BLIND = re.compile(r"(?:\^?\.\*|\^\(\.\*\\\.\)\?)[A-Za-z0-9_\-]*\$") # Allow entries that admit every name, so the container cannot change them. _MATCHES_ANYTHING = frozenset({".*", "^.*", ".*$", "^.*$", ".+", "^.+", ".+$", "^.+$"}) @@ -176,7 +177,7 @@ def container_blind(pattern: Optional[AllowDenyPattern]) -> bool: False keeps the verdict unasked; True lets it stand on the bare name. Testing "filters nothing" instead refused recipes whose verdict no container could alter -- every Snowflake recipe, because - `validate_legacy_schema_pattern` always appends a `.*INFORMATION_SCHEMA$` + `validate_legacy_schema_pattern` always appends an INFORMATION_SCHEMA deny, and a `dataset_pattern` denying `.*_staging$` for the same reason. """ if pattern is None: diff --git a/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery.py b/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery.py index e69d27352d19..e043c6e9530b 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery.py +++ b/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery.py @@ -1,7 +1,6 @@ import logging from typing import Iterable, Optional -from datahub.configuration.common import AllowDenyPattern from datahub.ingestion.api.common import PipelineContext from datahub.ingestion.api.decorators import ( SupportStatus, @@ -284,7 +283,7 @@ def _warn_deprecated_configs(self): self.config.match_fully_qualified_names is not None and not self.config.match_fully_qualified_names and self.config.schema_pattern is not None - and self.config.schema_pattern != AllowDenyPattern.allow_all() + and not self.config.schema_pattern.is_allow_all() ): self.report.warning( message="Please update `schema_pattern` to match against fully qualified schema name `.` and set config `match_fully_qualified_names : True`." diff --git a/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery_config.py b/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery_config.py index 9111fd717371..0d55c79dfb67 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery_config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/bigquery_v2/bigquery_config.py @@ -351,6 +351,22 @@ class GcsDatasetLineageProviderConfigBase(ConfigModel): ) +def _qualify_dataset_regex(regex: str) -> str: + r"""A `dataset_pattern` entry with no `.` names the dataset alone, so it is + made to match `.`: `a` becomes `.*\.a`. An entry + with a `|` is also wrapped in a group, `a|b` becomes `.*\.(?:a|b)`, so every + alternative stays behind the prefix. An entry with a `.` is taken to name + the project already and is kept as written, including a dataset-name regex + such as `staging_.*`: write `.*\.staging_.*` instead. + """ + if "." in regex: + return regex + anchor, body = ("^", regex[1:]) if regex.startswith("^") else ("", regex) + if "|" in body: + body = "(?:" + body + ")" + return anchor + r".*\." + body + + class BigQueryFilterConfig(SQLFilterConfig): project_ids: Annotated[List[str], Qualifier()] = Field( default_factory=list, @@ -416,33 +432,32 @@ class BigQueryFilterConfig(SQLFilterConfig): @model_validator(mode="after") def backward_compatibility_configs_set(self) -> Any: - dataset_pattern = self.dataset_pattern - schema_pattern = self.schema_pattern - + # Patterns are replaced, never edited in place: a pattern that was + # already used caches its compiled regexes, and would keep matching + # the old entries. See AllowDenyPattern.with_fields. if ( - dataset_pattern == AllowDenyPattern.allow_all() - and schema_pattern != AllowDenyPattern.allow_all() + self.dataset_pattern.is_allow_all() + and not self.schema_pattern.is_allow_all() ): logging.warning( "dataset_pattern is not set but schema_pattern is set, using schema_pattern as dataset_pattern. " "schema_pattern will be deprecated, please use dataset_pattern instead." ) - self.dataset_pattern = schema_pattern - dataset_pattern = schema_pattern + self.dataset_pattern = self.schema_pattern.with_fields() elif ( - dataset_pattern != AllowDenyPattern.allow_all() - and schema_pattern != AllowDenyPattern.allow_all() + not self.dataset_pattern.is_allow_all() + and not self.schema_pattern.is_allow_all() ): logging.warning( "schema_pattern will be ignored in favour of dataset_pattern. schema_pattern will be deprecated," " please use dataset_pattern only." ) + dataset_pattern = self.dataset_pattern match_fully_qualified_names = self.match_fully_qualified_names if ( - dataset_pattern is not None - and dataset_pattern != AllowDenyPattern.allow_all() + not dataset_pattern.is_allow_all() and match_fully_qualified_names is not None and not match_fully_qualified_names ): @@ -452,17 +467,13 @@ def backward_compatibility_configs_set(self) -> Any: "The config option `match_fully_qualified_names` is deprecated and will be " "removed in a future release." ) - elif match_fully_qualified_names and dataset_pattern is not None: - adjusted = False - for lst in [dataset_pattern.allow, dataset_pattern.deny]: - for i, pattern in enumerate(lst): - if "." not in pattern: - if pattern.startswith("^"): - lst[i] = r"^.*\." + pattern[1:] - else: - lst[i] = r".*\." + pattern - adjusted = True - if adjusted: + elif match_fully_qualified_names: + allow = [_qualify_dataset_regex(p) for p in dataset_pattern.allow] + deny = [_qualify_dataset_regex(p) for p in dataset_pattern.deny] + if allow != dataset_pattern.allow or deny != dataset_pattern.deny: + self.dataset_pattern = dataset_pattern.with_fields( + allow=allow, deny=deny + ) logger.warning( "`dataset_pattern` was adjusted to match against fully qualified schema names," " of the form `.`." diff --git a/metadata-ingestion/src/datahub/ingestion/source/data_lake_common/path_spec.py b/metadata-ingestion/src/datahub/ingestion/source/data_lake_common/path_spec.py index a05129b9567c..ce7e152cd806 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/data_lake_common/path_spec.py +++ b/metadata-ingestion/src/datahub/ingestion/source/data_lake_common/path_spec.py @@ -510,7 +510,7 @@ def validate_path_spec_comprehensive(self): raise ValueError( "path_spec.file_types is not applicable when emit_folders_only is set" ) - if self.tables_filter_pattern != AllowDenyPattern.allow_all(): + if not self.tables_filter_pattern.is_allow_all(): raise ValueError( "path_spec.tables_filter_pattern is not applicable when " "emit_folders_only is set; use exclude to skip folders" diff --git a/metadata-ingestion/src/datahub/ingestion/source/dataplex/dataplex_config.py b/metadata-ingestion/src/datahub/ingestion/source/dataplex/dataplex_config.py index 5f6b52cc9a0e..b036aba83529 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/dataplex/dataplex_config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/dataplex/dataplex_config.py @@ -451,6 +451,10 @@ def _validate_project_labels_format(cls, v: List[str]) -> List[str]: @model_validator(mode="after") def validate_project_ids(self) -> "DataplexConfig": """Ensure at least one means of selecting projects is configured.""" + # Deliberately structural, not `not is_allow_all()`: a recipe whose only + # selector is an allow-all spelled differently (`ignoreCase: false`, + # `allow: [".*", "x"]`) is accepted today, and is_allow_all() would + # start rejecting it. has_non_default_pattern = ( self.project_id_pattern != AllowDenyPattern.allow_all() ) diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py index 4bccd1c61b97..d61ef48f579b 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py @@ -1004,7 +1004,7 @@ def validate_workspace_apis_mode(self) -> "PowerBiDashboardSourceConfig": ("extract_endorsements_to_tags", self.extract_endorsements_to_tags), ( "filter_dataset_endorsements", - self.filter_dataset_endorsements != AllowDenyPattern.allow_all(), + not self.filter_dataset_endorsements.is_allow_all(), ), ) if enabled @@ -1151,10 +1151,7 @@ def map_data_platform(cls, value): @model_validator(mode="after") def workspace_id_backward_compatibility(self) -> "PowerBiDashboardSourceConfig": - if ( - self.workspace_id_pattern == AllowDenyPattern.allow_all() - and self.workspace_id - ): + if self.workspace_id_pattern.is_allow_all() and self.workspace_id: logger.warning( "workspace_id_pattern is not set but workspace_id is set, setting workspace_id as " "workspace_id_pattern. workspace_id will be deprecated, please use workspace_id_pattern instead." @@ -1162,10 +1159,7 @@ def workspace_id_backward_compatibility(self) -> "PowerBiDashboardSourceConfig": self.workspace_id_pattern = AllowDenyPattern( allow=[f"^{self.workspace_id}$"] ) - elif ( - self.workspace_id_pattern != AllowDenyPattern.allow_all() - and self.workspace_id - ): + elif not self.workspace_id_pattern.is_allow_all() and self.workspace_id: logger.warning( "workspace_id will be ignored in favour of workspace_id_pattern. workspace_id will be deprecated, " "please use workspace_id_pattern only." diff --git a/metadata-ingestion/src/datahub/ingestion/source/redshift/config.py b/metadata-ingestion/src/datahub/ingestion/source/redshift/config.py index e2841215ed86..591f8cdd1cec 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/redshift/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/redshift/config.py @@ -7,7 +7,6 @@ from pydantic.fields import Field from datahub.configuration.common import ( - AllowDenyPattern, HiddenFromDocs, Qualifier, ) @@ -261,7 +260,7 @@ def default_schemas(cls) -> FrozenSet[str]: def backward_compatibility_configs_set(self) -> "RedshiftConfig": if ( self.schema_pattern is not None - and self.schema_pattern != AllowDenyPattern.allow_all() + and not self.schema_pattern.is_allow_all() and self.match_fully_qualified_names is not None and not self.match_fully_qualified_names ): diff --git a/metadata-ingestion/src/datahub/ingestion/source/redshift/redshift.py b/metadata-ingestion/src/datahub/ingestion/source/redshift/redshift.py index 261acde273f0..18484af550ec 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/redshift/redshift.py +++ b/metadata-ingestion/src/datahub/ingestion/source/redshift/redshift.py @@ -7,7 +7,6 @@ # These imports verify that the dependencies are available. import redshift_connector -from datahub.configuration.common import AllowDenyPattern from datahub.configuration.pattern_utils import is_schema_allowed from datahub.configuration.time_window_config import BaseTimeWindowConfig from datahub.emitter.mce_builder import ( @@ -364,7 +363,7 @@ def _warn_deprecated_configs(self): self.config.match_fully_qualified_names is not None and not self.config.match_fully_qualified_names and self.config.schema_pattern is not None - and self.config.schema_pattern != AllowDenyPattern.allow_all() + and not self.config.schema_pattern.is_allow_all() ): self.report.warning( message="Please update `schema_pattern` to match against fully qualified schema name `.` and set config `match_fully_qualified_names : True`." diff --git a/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py b/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py index b161a456e440..2e98f8e38978 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py @@ -61,6 +61,12 @@ logger = logging.Logger(__name__) +# Denied in every recipe. Matches the schema both bare and qualified +# (`DB.INFORMATION_SCHEMA`) but not a schema that merely ends in the name +# (`DB.MY_INFORMATION_SCHEMA`). `agent.verdicts.container_blind` recognises +# this shape; keep the two in step. +SNOWFLAKE_INFORMATION_SCHEMA_DENY = r"^(.*\.)?INFORMATION_SCHEMA$" + # FIVETRAN creates temporary tables in schema named FIVETRAN_xxx_STAGING. # Ref - https://support.fivetran.com/hc/en-us/articles/1500003507122-Why-Is-There-an-Empty-Schema-Named-Fivetran-staging-in-the-Destination- # @@ -291,7 +297,7 @@ class SnowflakeFilterConfig(SQLFilterConfig): @model_validator(mode="after") def validate_legacy_schema_pattern(self) -> "SnowflakeFilterConfig": if ( - self.schema_pattern != AllowDenyPattern.allow_all() + not self.schema_pattern.is_allow_all() and not self.match_fully_qualified_names ): logger.warning( @@ -301,7 +307,9 @@ def validate_legacy_schema_pattern(self) -> "SnowflakeFilterConfig": ) # Always exclude reporting metadata for INFORMATION_SCHEMA schema - self.schema_pattern = self.schema_pattern.with_deny(r".*INFORMATION_SCHEMA$") + self.schema_pattern = self.schema_pattern.with_deny( + SNOWFLAKE_INFORMATION_SCHEMA_DENY + ) return self diff --git a/metadata-ingestion/src/datahub/ingestion/source/superset.py b/metadata-ingestion/src/datahub/ingestion/source/superset.py index 61fcf69b737d..ade0edc8f200 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/superset.py +++ b/metadata-ingestion/src/datahub/ingestion/source/superset.py @@ -1159,7 +1159,7 @@ def _process_dashboard(self, dashboard_data: Any) -> Iterable[MetadataWorkUnit]: dashboard_title=dashboard_title, ) - if self.config.database_pattern != AllowDenyPattern.allow_all(): + if not self.config.database_pattern.is_allow_all(): self._report_filtered_chart_references( position_data=position_data, dashboard_id=dashboard_id, @@ -1723,7 +1723,7 @@ def _process_chart(self, chart_data: Any) -> Iterable[MetadataWorkUnit]: return # TODO: Make helper methods for database_pattern - if self.config.database_pattern != AllowDenyPattern.allow_all(): + if not self.config.database_pattern.is_allow_all(): datasource_id = chart_data.get("datasource_id") if datasource_id: @@ -1797,7 +1797,7 @@ def _process_chart(self, chart_data: Any) -> Iterable[MetadataWorkUnit]: title="Incomplete Ingestion", ) - if self.config.dataset_pattern != AllowDenyPattern.allow_all(): + if not self.config.dataset_pattern.is_allow_all(): datasource_id = chart_data.get("datasource_id") if datasource_id: dataset_response = self.get_dataset_info(datasource_id) @@ -2225,7 +2225,7 @@ def _process_dataset(self, dataset_data: Any) -> Iterable[MetadataWorkUnit]: f"Dataset '{dataset_name}' filtered by dataset_pattern" ) return - if self.config.database_pattern != AllowDenyPattern.allow_all(): + if not self.config.database_pattern.is_allow_all(): dataset_response = self.get_dataset_info(dataset_id) database_name = ( dataset_response.get("result", {}) diff --git a/metadata-ingestion/tests/unit/agent/test_sql_structural_verdicts.py b/metadata-ingestion/tests/unit/agent/test_sql_structural_verdicts.py index 1da48c262841..b0aa805d2609 100644 --- a/metadata-ingestion/tests/unit/agent/test_sql_structural_verdicts.py +++ b/metadata-ingestion/tests/unit/agent/test_sql_structural_verdicts.py @@ -23,6 +23,7 @@ ContainerUnknown, Verdict, VerdictContext, + container_blind, ) from datahub.ingestion.source.common.subtypes import ( DatasetContainerSubTypes, @@ -251,8 +252,8 @@ def test_a_pattern_that_filters_nothing_is_not_refused_for_being_spelled_oddly() def test_a_deny_the_source_appended_does_not_cost_the_recipe_its_answer() -> None: """A deny list filters, and is still blind to the container. - `validate_legacy_schema_pattern` appends `.*INFORMATION_SCHEMA$` to every - Snowflake recipe, including one that sets no filter of its own. Keying the + `validate_legacy_schema_pattern` appends `^(.*\\.)?INFORMATION_SCHEMA$` to + every Snowflake recipe, including one that sets no filter of its own. Keying the carve-out on "filters nothing" therefore refused a recipe the caller never filtered, for want of a container that could not have changed its verdict: a suffix anchored past a dot cannot reach back across one. @@ -274,6 +275,20 @@ def test_a_deny_the_source_appended_does_not_cost_the_recipe_its_answer() -> Non assert _rows(result) == [("MY_SCHEMA", "MY_SCHEMA", True, None)] +@pytest.mark.parametrize( + "deny,blind", + [ + (r".*INFORMATION_SCHEMA$", True), + (r"^(.*\.)?INFORMATION_SCHEMA$", True), + # The literal must not reach across the dot, in either shape. + (r"^(.*\.)?DB\.INFORMATION_SCHEMA$", False), + (r"^DB\.(.*\.)?INFORMATION_SCHEMA$", False), + ], +) +def test_container_blind_suffix_shapes(deny: str, blind: bool) -> None: + assert container_blind(AllowDenyPattern(deny=[deny])) is blind + + def test_an_allow_anchored_past_the_dot_answers_where_a_qualified_one_refuses() -> None: """The carve-out turns on whether the container could change the verdict, not on whether the pattern filters. diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py new file mode 100644 index 000000000000..545043e5f300 --- /dev/null +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py @@ -0,0 +1,192 @@ +"""`dataset_pattern` qualification under `match_fully_qualified_names`. + +With the flag on (the default) the connector matches `dataset_pattern` against +`.`. An entry with no `.` gets the `.*\\.` prefix, +grouped as `.*\\.(?:)` when it has a `|`; an entry with a `.` is +matched as written. These tests go through `BigQueryFilter`, the filter the +source actually uses. +""" + +from typing import Any, Dict, Iterable, List +from unittest.mock import patch + +import pytest + +from datahub.configuration.common import AllowDenyPattern +from datahub.emitter.mcp import MetadataChangeProposalWrapper +from datahub.ingestion.agent.pattern_path import validate_pattern_at +from datahub.ingestion.api.workunit import MetadataWorkUnit +from datahub.ingestion.source.bigquery_v2.bigquery_config import BigQueryV2Config +from datahub.ingestion.source.bigquery_v2.bigquery_report import BigQueryV2Report +from datahub.ingestion.source.bigquery_v2.bigquery_schema import ( + BigqueryColumn, + BigqueryDataset, + BigqueryProject, +) +from datahub.ingestion.source.bigquery_v2.common import BigQueryFilter +from datahub.metadata.schema_classes import StatusClass +from datahub.utilities.file_backed_collections import FileBackedDict +from tests.unit.bigquery.conftest import PROJECT, as_mock, make_schema_gen, make_table + +_DOTTED_ENTRIES_AS_WRITTEN = ( + "An entry containing a `.` is matched as written against " + "`.`; a dataset-name regex with a `.` must " + "include the project part, e.g. `.*\\.staging_.*`." +) + + +def _filter(dataset_pattern: Dict[str, List[str]]) -> BigQueryFilter: + config = BigQueryV2Config.model_validate({"dataset_pattern": dataset_pattern}) + assert config.match_fully_qualified_names + return BigQueryFilter(config, BigQueryV2Report()) + + +def test_dataset_name_is_qualified_and_still_matches() -> None: + filters = _filter({"allow": ["staging_events"]}) + assert filters.filter_config.dataset_pattern.allow == [r".*\.staging_events"] + assert filters.is_dataset_allowed("staging_events", PROJECT) + assert not filters.is_dataset_allowed("prod_events", PROJECT) + + +@pytest.mark.parametrize("dataset", ["a", "b"]) +def test_every_alternative_is_qualified(dataset: str) -> None: + filters = _filter({"allow": ["a|b"]}) + assert filters.filter_config.dataset_pattern.allow == [r".*\.(?:a|b)"] + assert filters.is_dataset_allowed(dataset, PROJECT) + assert not filters.is_dataset_allowed("c", PROJECT) + + +@pytest.mark.parametrize("deny", [["restricted_pii"], ["^tmp|restricted_pii$"]]) +def test_deny_entry_denies_its_dataset(deny: List[str]) -> None: + filters = _filter({"deny": deny}) + assert not filters.is_dataset_allowed("restricted_pii", PROJECT) + assert filters.is_dataset_allowed("public_events", PROJECT) + + +@pytest.mark.parametrize( + "entry", [f"{PROJECT}.*", f"{PROJECT}\\.prod_.*", ".*\\.prod_.*", ".*prod_.*"] +) +def test_entry_with_a_dot_is_matched_as_written(entry: str) -> None: + filters = _filter({"allow": [entry]}) + assert filters.filter_config.dataset_pattern.allow == [entry] + assert filters.is_dataset_allowed("prod_events", PROJECT) + assert not _filter({"deny": [entry]}).is_dataset_allowed("prod_events", PROJECT) + + +@pytest.mark.xfail(reason=_DOTTED_ENTRIES_AS_WRITTEN, strict=True) +@pytest.mark.parametrize("allow", [["^staging_.*"], ["staging_.*"]]) +def test_dataset_name_regex_with_a_dot(allow: List[str]) -> None: + assert _filter({"allow": allow}).is_dataset_allowed("staging_events", PROJECT) + + +@pytest.mark.xfail( + reason="Only a leading `^` is moved in front of the project prefix; a `^` " + "inside the entry is kept, so `^a|^b` qualifies to `^.*\\.(?:a|^b)` and " + "its second alternative cannot match a qualified name.", + strict=True, +) +def test_anchor_in_every_alternative() -> None: + assert _filter({"allow": ["^a|^b"]}).is_dataset_allowed("b", PROJECT) + + +def test_qualification_is_idempotent() -> None: + config = BigQueryV2Config.model_validate( + {"dataset_pattern": {"allow": ["a|b"], "deny": ["^tmp$"]}} + ) + qualified = config.dataset_pattern + validate_pattern_at(config, "dataset_pattern", qualified) + assert config.dataset_pattern.allow == [r".*\.(?:a|b)"] + assert config.dataset_pattern.deny == [r"^.*\.tmp$"] + + +def test_qualification_ignores_a_warm_regex_cache() -> None: + """A pattern that was already used caches its compiled regexes; the + qualified pattern must match its own entries, not the cached ones.""" + pattern = AllowDenyPattern(allow=["mydataset"]) + assert pattern.allowed("mydataset") # warms _compiled_allow + config = BigQueryV2Config(dataset_pattern=pattern) + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "mydataset", PROJECT + ) + assert pattern.allow == ["mydataset"] + + +def test_revalidating_a_warm_pattern_qualifies_it() -> None: + config = BigQueryV2Config.model_validate({}) + pattern = AllowDenyPattern(allow=["mydataset"]) + assert pattern.allowed("mydataset") # warms _compiled_allow + validate_pattern_at(config, "dataset_pattern", pattern) + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "mydataset", PROJECT + ) + assert pattern.allow == ["mydataset"] + + +def test_schema_pattern_fallback_is_an_independent_pattern() -> None: + config = BigQueryV2Config.model_validate( + {"schema_pattern": {"allow": ["mydataset"]}} + ) + assert config.dataset_pattern is not config.schema_pattern + assert config.schema_pattern.allow == ["mydataset"] + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "mydataset", PROJECT + ) + + +def _columns( + by_table: Dict[str, List[BigqueryColumn]], +) -> FileBackedDict[List[BigqueryColumn]]: + columns: FileBackedDict[List[BigqueryColumn]] = FileBackedDict() + columns.update(by_table) + return columns + + +def _status_urns(wus: Iterable[MetadataWorkUnit]) -> List[str]: + out: List[str] = [] + for wu in wus: + if isinstance(wu.metadata, MetadataChangeProposalWrapper) and isinstance( + wu.metadata.aspect, StatusClass + ): + assert wu.metadata.entityUrn + out.append(wu.metadata.entityUrn) + return out + + +def _run_over_datasets(schema_gen: Any, names: List[str]) -> List[MetadataWorkUnit]: + """Run the project's dataset loop over `names`, one table each.""" + as_mock(schema_gen.schema_api.get_columns_for_dataset).side_effect = ( + lambda *_, **__: _columns({}) + ) + with patch.object( + schema_gen, + "get_tables_for_dataset", + side_effect=lambda project_id, dataset: [make_table("t1")], + ): + return list( + schema_gen._process_project_datasets( + BigqueryProject( + PROJECT, + PROJECT, + datasets=[BigqueryDataset(name=n) for n in names], + ), + {}, + ) + ) + + +def test_alternation_deny_keeps_every_alternative_out() -> None: + """End to end: with deny `tmp|restricted_pii`, restricted_pii is dropped.""" + schema_gen = make_schema_gen( + dataset_pattern={"deny": ["tmp|restricted_pii"]}, + include_views=False, + include_table_snapshots=False, + include_table_constraints=False, + ) + + urns = _status_urns( + _run_over_datasets(schema_gen, ["restricted_pii", "public_events"]) + ) + + assert not any("restricted_pii" in urn for urn in urns), urns + assert any("public_events" in urn for urn in urns), urns + assert "restricted_pii.*" in schema_gen.report.filtered diff --git a/metadata-ingestion/tests/unit/config/test_allow_deny.py b/metadata-ingestion/tests/unit/config/test_allow_deny.py index e3bbe4f14d73..dd3a5d3585c0 100644 --- a/metadata-ingestion/tests/unit/config/test_allow_deny.py +++ b/metadata-ingestion/tests/unit/config/test_allow_deny.py @@ -113,3 +113,21 @@ class Sub(AllowDenyPattern): pass assert type(Sub().with_deny("x")) is Sub + + +def test_with_fields_matches_the_new_lists_not_the_cached_ones() -> None: + p = AllowDenyPattern(allow=["old"], ignoreCase=False) + assert p.allowed("old") # warms _compiled_allow + p2 = p.with_fields(allow=["new"]) + assert p2.allowed("new") + assert not p2.allowed("old") + assert p2.ignoreCase is False + assert p.allow == ["old"] + + +def test_with_fields_without_overrides_is_an_independent_equal_copy() -> None: + p = AllowDenyPattern(allow=["a"], deny=["b"]) + p2 = p.with_fields() + assert p2 is not p + assert p2 == p + assert p2.allow is not p.allow diff --git a/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py b/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py index 886f85c8b672..dfda389655aa 100644 --- a/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py +++ b/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py @@ -22,6 +22,7 @@ from datahub.ingestion.source.snowflake.oauth_config import OAuthConfiguration from datahub.ingestion.source.snowflake.snowflake_config import ( DEFAULT_TEMP_TABLES_PATTERNS, + SNOWFLAKE_INFORMATION_SCHEMA_DENY, SnowflakeIdentifierConfig, SnowflakeV2Config, ) @@ -1705,7 +1706,9 @@ def _info_schema_config(**extra: Any) -> SnowflakeV2Config: def test_snowflake_information_schema_deny_survives_round_trip() -> None: cfg = _info_schema_config(schema_pattern={"allow": ["DB\\..*"]}) round_tripped = SnowflakeV2Config.model_validate(cfg.model_dump()) - assert round_tripped.schema_pattern.deny.count(r".*INFORMATION_SCHEMA$") == 1 + assert ( + round_tripped.schema_pattern.deny.count(SNOWFLAKE_INFORMATION_SCHEMA_DENY) == 1 + ) assert not round_tripped.schema_pattern.allowed("DB.INFORMATION_SCHEMA") @@ -1724,6 +1727,21 @@ def test_snowflake_information_schema_deny_not_duplicated_on_revalidation() -> N assert new_pattern.allowed("DB.INFORMATION_SCHEMA") # warms _compiled_deny validate_pattern_at(cfg, "schema_pattern", new_pattern) validate_pattern_at(cfg, "schema_pattern", cfg.schema_pattern) - assert cfg.schema_pattern.deny.count(r".*INFORMATION_SCHEMA$") == 1 + assert cfg.schema_pattern.deny.count(SNOWFLAKE_INFORMATION_SCHEMA_DENY) == 1 assert not cfg.schema_pattern.allowed("DB.INFORMATION_SCHEMA") assert new_pattern.deny == [] + + +@pytest.mark.parametrize("match_fully_qualified_names", [True, False]) +def test_snowflake_information_schema_deny_spares_lookalike_schemas( + match_fully_qualified_names: bool, +) -> None: + """Only INFORMATION_SCHEMA itself is denied, bare or qualified; a schema + that merely ends in the name is a user schema.""" + cfg = _info_schema_config(match_fully_qualified_names=match_fully_qualified_names) + pattern = cfg.schema_pattern + assert not pattern.allowed("INFORMATION_SCHEMA") + assert not pattern.allowed("DB.INFORMATION_SCHEMA") + assert not pattern.allowed("db.information_schema") + assert pattern.allowed("MY_INFORMATION_SCHEMA") + assert pattern.allowed("DB.MY_INFORMATION_SCHEMA")