From 28211a01577f5e7ee9f3e91eee4be890b56163d6 Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Wed, 18 Nov 2026 21:53:13 +0000 Subject: [PATCH 1/7] fix(ingest/bigquery): qualify regex dataset_pattern entries and rebuild patterns instead of mutating them - AllowDenyPattern._rebuilt(**overrides): derive a pattern without carrying the compiled-regex cache; used by with_deny and the probe's trial pattern. - BigQuery: dataset_pattern is rebuilt, not edited in place, so a pattern that was already used no longer keeps matching its old entries. Entries are qualified per alternation branch, and only a separator dot (`\.` or `.` before a name character) marks an entry as project-qualified, so `^staging_.*` and `a|b` work. schema_pattern is no longer aliased. - Snowflake: deny `^(.*\.)?INFORMATION_SCHEMA$` instead of `.*INFORMATION_SCHEMA$`, so MY_INFORMATION_SCHEMA is no longer dropped; container_blind recognises the new shape. - Use is_allow_all() instead of comparing against allow_all(), except in the Dataplex validator, where it would reject recipes accepted today. --- docs/how/breaking-changes.md | 16 ++ .../src/datahub/configuration/common.py | 16 +- .../datahub/ingestion/agent/filter_check.py | 11 +- .../src/datahub/ingestion/agent/verdicts.py | 15 +- .../ingestion/source/bigquery_v2/bigquery.py | 3 +- .../source/bigquery_v2/bigquery_config.py | 138 +++++++++-- .../source/data_lake_common/path_spec.py | 2 +- .../source/dataplex/dataplex_config.py | 4 + .../ingestion/source/powerbi/config.py | 12 +- .../ingestion/source/redshift/config.py | 3 +- .../ingestion/source/redshift/redshift.py | 3 +- .../source/snowflake/snowflake_config.py | 12 +- .../src/datahub/ingestion/source/superset.py | 8 +- .../agent/test_sql_structural_verdicts.py | 19 +- .../bigquery/test_bigquery_dataset_pattern.py | 234 ++++++++++++++++++ .../unit/bigquery/test_bigquery_source.py | 6 +- .../tests/unit/config/test_allow_deny.py | 18 ++ .../unit/snowflake/test_snowflake_source.py | 22 +- 18 files changed, 473 insertions(+), 69 deletions(-) create mode 100644 metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index e90b33a8e0274..2a9ba0b501621 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -15,6 +15,22 @@ the one you are on and the one you are moving to, not just the target. ## Next +### BigQuery `dataset_pattern` entries written as regular expressions + +When `match_fully_qualified_names` is on (the default), BigQuery `dataset_pattern` entries that name +datasets with a regular expression, such as `^staging_.*` or `a|b`, now match those datasets. Before, +any entry containing a `.` was treated as already naming the project, so `^staging_.*` matched nothing +and an `allow` entry like that ingested no datasets, while a `deny` entry denied nothing. Only the +first alternative of an entry like `a|b` was matched. If you added such an entry to `deny` and it seemed +to do nothing, it now takes effect. Entries that name the project, such as `my-project.my_dataset`, +`my-project\.prod_.*` or `.*\.my_dataset`, are unchanged. + +### Snowflake schemas whose names end in `INFORMATION_SCHEMA` + +Snowflake ingestion now skips only the `INFORMATION_SCHEMA` schema itself. A schema such as +`MY_INFORMATION_SCHEMA` used to be skipped silently and is now ingested like any other schema. To keep +skipping it, add it to `schema_pattern.deny`. + ### CLI initialization from scripts When you run `datahub init` without an interactive terminal, it now stops if an existing diff --git a/metadata-ingestion/src/datahub/configuration/common.py b/metadata-ingestion/src/datahub/configuration/common.py index c971d7e4cc857..700ae15d0845f 100644 --- a/metadata-ingestion/src/datahub/configuration/common.py +++ b/metadata-ingestion/src/datahub/configuration/common.py @@ -514,16 +514,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._rebuilt(deny=deduplicate_list([*self.deny, *rules])) + + def _rebuilt(self, **overrides: Any) -> 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 c1d4acf783ee1..c1183129e7f75 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. + Rebuilt (see `AllowDenyPattern._rebuilt`), 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._rebuilt(**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 862e01ad163be..1d3b2491d4a32 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 e80b95faca39f..2c7149d510514 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, @@ -279,7 +278,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 6cccf5c64477d..15991fb44cad6 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 @@ -338,6 +338,107 @@ class GcsDatasetLineageProviderConfigBase(ConfigModel): ) +# `dataset_pattern` is matched against `.` when +# `match_fully_qualified_names` is set (the default), so an entry written for +# the dataset name alone is prefixed with "any project". BigQuery dataset names +# cannot contain a dot, so a dot that separates two names can only be the +# project/dataset separator: `\.`, or a bare `.` followed by a name character +# (`my-project.my_dataset`). Any other `.` is the regex wildcard (`staging_.*`) +# and says nothing about the project. +_DATASET_NAME_CHAR = re.compile(r"[A-Za-z0-9_\-]") +# Entries that begin by matching anything already reach past the project. +_SPANS_PROJECT_PREFIXES = (".*", "^.*", ".+", "^.+") +_ANY_PROJECT_PREFIX = r".*\." + + +def _top_level_branches(regex: str) -> List[str]: + """`regex` split on the `|` that are outside groups and character classes.""" + branches: List[str] = [] + depth = 0 + in_class = False + start = 0 + i = 0 + while i < len(regex): + char = regex[i] + if char == "\\": + i += 2 + continue + if in_class: + if char == "]": + in_class = False + elif char == "[": + in_class = True + # A `]` first in the class (after an optional `^`) is literal. + if regex.startswith("^", i + 1): + i += 1 + if regex.startswith("]", i + 1): + i += 1 + elif char == "(": + depth += 1 + elif char == ")": + depth -= 1 + elif char == "|" and depth == 0: + branches.append(regex[start:i]) + start = i + 1 + i += 1 + branches.append(regex[start:]) + return branches + + +def _names_project(regex: str) -> bool: + """Whether `regex` has a project/dataset separator dot (see above).""" + in_class = False + i = 0 + while i < len(regex): + char = regex[i] + if char == "\\": + if regex.startswith(".", i + 1): + return True + i += 2 + continue + if in_class: + if char == "]": + in_class = False + elif char == "[": + in_class = True + elif char == "." and _DATASET_NAME_CHAR.match(regex, i + 1): + return True + i += 1 + return False + + +def _qualify_branch(branch: str) -> str: + if ( + not branch + or branch.startswith(_SPANS_PROJECT_PREFIXES) + or _names_project(branch) + ): + return branch + if branch.startswith("^"): + return "^" + _ANY_PROJECT_PREFIX + branch[1:] + return _ANY_PROJECT_PREFIX + branch + + +def _qualify_dataset_regex(regex: str) -> str: + r"""`regex` made to match `.`, for a + `dataset_pattern` entry written against the dataset name alone. + + Each top-level alternation branch is judged on its own, so `a|b` becomes + `.*\.a|.*\.b`. A branch that already names the project or starts with a + match-anything is kept as written, so the rewrite is idempotent. An entry + whose rewrite does not compile (e.g. a leading inline flag) is kept as + written. + """ + qualified = "|".join(_qualify_branch(b) for b in _top_level_branches(regex)) + if qualified == regex: + return regex + try: + re.compile(qualified) + except re.error: + return regex + return qualified + + class BigQueryFilterConfig(SQLFilterConfig): project_ids: Annotated[List[str], Qualifier()] = Field( default_factory=list, @@ -403,33 +504,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._rebuilt. 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._rebuilt() 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 ): @@ -439,17 +539,11 @@ 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._rebuilt(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 a05129b9567cc..ce7e152cd806f 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 5f6b52cc9a0e8..b036aba835299 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 4bccd1c61b97d..d61ef48f579b9 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 e2841215ed864..591f8cdd1cecd 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 261acde273f08..18484af550ec5 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 38e2feadfa7dd..96107e627c833 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/snowflake/snowflake_config.py @@ -56,6 +56,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- # @@ -286,7 +292,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( @@ -296,7 +302,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 61fcf69b737d7..ade0edc8f2000 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 1da48c2628410..b0aa805d26098 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 0000000000000..a65449e4a7661 --- /dev/null +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py @@ -0,0 +1,234 @@ +"""`dataset_pattern` qualification under `match_fully_qualified_names`. + +With the flag on (the default) the connector matches `dataset_pattern` against +`.`, so `backward_compatibility_configs_set` prefixes +entries written for the dataset name alone with "any project". 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 + + +def _filter(dataset_pattern: Dict[str, Any]) -> BigQueryFilter: + config = BigQueryV2Config.model_validate({"dataset_pattern": dataset_pattern}) + assert config.match_fully_qualified_names + return BigQueryFilter(config, BigQueryV2Report()) + + +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], + ), + {}, + ) + ) + + +@pytest.mark.parametrize( + "allow,dataset", + [ + (["staging_events"], "staging_events"), + (["^staging_.*"], "staging_events"), + (["staging_.*"], "staging_events"), + (["^staging_.*$"], "staging_events"), + (["^(a|b)$"], "b"), + (["a|b"], "a"), + (["a|b"], "b"), + (["^a$|^b$"], "b"), + ], +) +def test_dataset_name_regex_allows_its_dataset(allow: List[str], dataset: str) -> None: + assert _filter({"allow": allow}).is_dataset_allowed(dataset, PROJECT) + + +@pytest.mark.parametrize( + "allow,dataset", + [ + (["^staging_.*"], "prod_events"), + (["a|b"], "c"), + (["^a$|^b$"], "ab"), + ], +) +def test_dataset_name_regex_still_filters(allow: List[str], dataset: str) -> None: + assert not _filter({"allow": allow}).is_dataset_allowed(dataset, PROJECT) + + +@pytest.mark.parametrize("deny", [["^restricted_.*"], ["x|restricted_pii"]]) +def test_dataset_name_regex_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}.prod_.*", + f"{PROJECT}\\.prod_.*", + "^my-.*\\.prod_.*", + ".*\\.prod_.*", + ".*prod_.*", + ], +) +def test_project_qualified_entry_is_kept_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) + + +def test_escaped_dot_names_the_project() -> None: + """Dataset names cannot contain a dot, so `a\\.b` can only mean project + `a`, dataset `b`; it is not read as a dataset-name regex.""" + filters = _filter({"allow": ["my_dataset\\.v2"]}) + assert filters.filter_config.dataset_pattern.allow == ["my_dataset\\.v2"] + assert filters.is_dataset_allowed("v2", "my_dataset") + assert not filters.is_dataset_allowed("v2", PROJECT) + + +def test_entry_whose_qualified_form_does_not_compile_is_kept() -> None: + # A global inline flag must stay at the start of the expression. + filters = _filter({"allow": ["(?i)staging"]}) + assert filters.filter_config.dataset_pattern.allow == ["(?i)staging"] + + +def test_qualification_is_idempotent() -> None: + config = BigQueryV2Config.model_validate( + {"dataset_pattern": {"allow": ["^staging_.*", "a|b"], "deny": ["^tmp$"]}} + ) + qualified = config.dataset_pattern + assert qualified.allow == [r"^.*\.staging_.*", r".*\.a|.*\.b"] + assert qualified.deny == [r"^.*\.tmp$"] + validate_pattern_at(config, "dataset_pattern", qualified) + assert config.dataset_pattern.allow == qualified.allow + assert config.dataset_pattern.deny == qualified.deny + + +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) + filters = BigQueryFilter(config, BigQueryV2Report()) + assert filters.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) + filters = BigQueryFilter(config, BigQueryV2Report()) + assert filters.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 test_not_qualified_when_matching_bare_names() -> None: + config = BigQueryV2Config.model_validate( + { + "dataset_pattern": {"allow": ["^staging_.*"]}, + "match_fully_qualified_names": False, + } + ) + assert config.dataset_pattern.allow == ["^staging_.*"] + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "staging_events", PROJECT + ) + + +def test_regex_allow_entry_ingests_the_matching_dataset() -> None: + """End to end: with allow `^staging_.*`, staging_events must be ingested.""" + schema_gen = make_schema_gen( + dataset_pattern={"allow": ["^staging_.*"]}, + include_views=False, + include_table_snapshots=False, + include_table_constraints=False, + ) + + urns = _status_urns( + _run_over_datasets(schema_gen, ["staging_events", "prod_events"]) + ) + + assert any(urn.endswith("staging_events.t1,PROD)") for urn in urns), urns + assert not any("prod_events" in urn for urn in urns), urns + + +def test_regex_deny_entry_keeps_the_matching_dataset_out() -> None: + """End to end: with deny `^restricted_.*`, restricted_pii must be dropped.""" + schema_gen = make_schema_gen( + dataset_pattern={"deny": ["^restricted_.*"]}, + 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/bigquery/test_bigquery_source.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py index 00fbd7e0eb1f6..0d389e02a3a2f 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py @@ -1796,9 +1796,9 @@ def test_bigquery_config_deprecated_schema_pattern(): "dataset_pattern": AllowDenyPattern(deny=["temp.*"]), } config = BigQueryV2Config.model_validate(config_with_dataset_pattern) - assert config.dataset_pattern == AllowDenyPattern( - deny=["temp.*"] - ) # dataset_pattern + # dataset_pattern, qualified with "any project": `.*` is a wildcard, not + # a project separator + assert config.dataset_pattern == AllowDenyPattern(deny=[r".*\.temp.*"]) @pytest.mark.parametrize( diff --git a/metadata-ingestion/tests/unit/config/test_allow_deny.py b/metadata-ingestion/tests/unit/config/test_allow_deny.py index e3bbe4f14d732..cb881156b8e28 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_rebuilt_matches_the_new_lists_not_the_cached_ones() -> None: + p = AllowDenyPattern(allow=["old"], ignoreCase=False) + assert p.allowed("old") # warms _compiled_allow + p2 = p._rebuilt(allow=["new"]) + assert p2.allowed("new") + assert not p2.allowed("old") + assert p2.ignoreCase is False + assert p.allow == ["old"] + + +def test_rebuilt_without_overrides_is_an_independent_equal_copy() -> None: + p = AllowDenyPattern(allow=["a"], deny=["b"]) + p2 = p._rebuilt() + 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 19ddfab0ead56..3c97a99818191 100644 --- a/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py +++ b/metadata-ingestion/tests/unit/snowflake/test_snowflake_source.py @@ -21,6 +21,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, ) @@ -1693,7 +1694,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") @@ -1712,6 +1715,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") From c7ca469e6ed5171d4777a5ec86f79067a932053e Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Wed, 18 Nov 2026 21:53:46 +0000 Subject: [PATCH 2/7] docs: link breaking-change entries to the PR --- docs/how/breaking-changes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index 2a9ba0b501621..d4ff26771c2ec 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -15,7 +15,7 @@ the one you are on and the one you are moving to, not just the target. ## Next -### BigQuery `dataset_pattern` entries written as regular expressions +### BigQuery `dataset_pattern` entries written as regular expressions ([#21430](https://github.com/datahub-project/datahub/pull/21430)) When `match_fully_qualified_names` is on (the default), BigQuery `dataset_pattern` entries that name datasets with a regular expression, such as `^staging_.*` or `a|b`, now match those datasets. Before, @@ -25,7 +25,7 @@ first alternative of an entry like `a|b` was matched. If you added such an entry to do nothing, it now takes effect. Entries that name the project, such as `my-project.my_dataset`, `my-project\.prod_.*` or `.*\.my_dataset`, are unchanged. -### Snowflake schemas whose names end in `INFORMATION_SCHEMA` +### Snowflake schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) Snowflake ingestion now skips only the `INFORMATION_SCHEMA` schema itself. A schema such as `MY_INFORMATION_SCHEMA` used to be skipped silently and is now ingested like any other schema. To keep From 2d10c3e1835152e36e7f6c1bbc50675b3f0bd8f7 Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Wed, 18 Nov 2026 21:59:16 +0000 Subject: [PATCH 3/7] fix(ingest/bigquery): keep project-qualified wildcard entries matching An entry whose only dots may be either the project separator or a regex wildcard (`my-project.*`, `^staging_.*`) now gets an optional "any project" prefix, `(?:.*\.)?`, so it keeps every match it had on master and also matches as a dataset-name regex. Entries with no dot keep the `.*\.` prefix. Leading inline flags stay in front of the prefix, and an entry that still cannot be qualified logs a warning. --- docs/how/breaking-changes.md | 4 +- .../source/bigquery_v2/bigquery_config.py | 115 +++++++++++------- .../bigquery/test_bigquery_dataset_pattern.py | 32 ++++- .../unit/bigquery/test_bigquery_source.py | 6 +- 4 files changed, 101 insertions(+), 56 deletions(-) diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index d4ff26771c2ec..591057db85e83 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -22,7 +22,9 @@ datasets with a regular expression, such as `^staging_.*` or `a|b`, now match th any entry containing a `.` was treated as already naming the project, so `^staging_.*` matched nothing and an `allow` entry like that ingested no datasets, while a `deny` entry denied nothing. Only the first alternative of an entry like `a|b` was matched. If you added such an entry to `deny` and it seemed -to do nothing, it now takes effect. Entries that name the project, such as `my-project.my_dataset`, +to do nothing, it now takes effect. An entry such as `my-project.*`, where the `.` could be either +the project separator or a wildcard, keeps matching what it matched before and now also matches +datasets whose names fit it. Entries that clearly name the project, such as `my-project.my_dataset`, `my-project\.prod_.*` or `.*\.my_dataset`, are unchanged. ### Snowflake schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) 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 15991fb44cad6..9bb779a56c3a9 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 @@ -340,22 +340,44 @@ class GcsDatasetLineageProviderConfigBase(ConfigModel): # `dataset_pattern` is matched against `.` when # `match_fully_qualified_names` is set (the default), so an entry written for -# the dataset name alone is prefixed with "any project". BigQuery dataset names -# cannot contain a dot, so a dot that separates two names can only be the -# project/dataset separator: `\.`, or a bare `.` followed by a name character -# (`my-project.my_dataset`). Any other `.` is the regex wildcard (`staging_.*`) -# and says nothing about the project. -_DATASET_NAME_CHAR = re.compile(r"[A-Za-z0-9_\-]") -# Entries that begin by matching anything already reach past the project. +# the dataset name alone has to be prefixed with "any project". Each top-level +# alternation branch is judged on its own: +# +# - no `.` at all: a dataset name, prefixed with `.*\.`; +# - starts with a match-anything (`.*`, `.+`): already reaches past the +# project, kept; +# - a separator dot -- `\.`, or a bare `.` followed by a name character, as in +# `my-project.my_dataset` -- names the project, kept. BigQuery dataset names +# cannot contain a dot, so such a dot can only separate project and dataset; +# - any other `.` (`staging_.*`, `my-project.*`) is ambiguous: the regex +# wildcard in a dataset-name regex, or the separator in a project-qualified +# one. Prefixed with an optional `(?:.*\.)?`, so it keeps every match it had +# and also matches as a dataset name. +_SEPARATOR_FOLLOWER = re.compile(r"[A-Za-z0-9_]") _SPANS_PROJECT_PREFIXES = (".*", "^.*", ".+", "^.+") _ANY_PROJECT_PREFIX = r".*\." +_OPTIONAL_PROJECT_PREFIX = r"(?:.*\.)?" +# Global inline flags must stay at the start of the expression. +_LEADING_INLINE_FLAGS = re.compile(r"^\(\?[aiLmsux]+\)") + + +def _class_end(regex: str, start: int) -> int: + """Index just past the character class opening at `regex[start]`.""" + i = start + 1 + # A `]` first in the class (after an optional `^`) is literal. + if regex.startswith("^", i): + i += 1 + if regex.startswith("]", i): + i += 1 + while i < len(regex) and regex[i] != "]": + i += 2 if regex[i] == "\\" else 1 + return i + 1 def _top_level_branches(regex: str) -> List[str]: """`regex` split on the `|` that are outside groups and character classes.""" branches: List[str] = [] depth = 0 - in_class = False start = 0 i = 0 while i < len(regex): @@ -363,17 +385,10 @@ def _top_level_branches(regex: str) -> List[str]: if char == "\\": i += 2 continue - if in_class: - if char == "]": - in_class = False - elif char == "[": - in_class = True - # A `]` first in the class (after an optional `^`) is literal. - if regex.startswith("^", i + 1): - i += 1 - if regex.startswith("]", i + 1): - i += 1 - elif char == "(": + if char == "[": + i = _class_end(regex, i) + continue + if char == "(": depth += 1 elif char == ")": depth -= 1 @@ -385,56 +400,64 @@ def _top_level_branches(regex: str) -> List[str]: return branches -def _names_project(regex: str) -> bool: - """Whether `regex` has a project/dataset separator dot (see above).""" - in_class = False +def _dots(regex: str) -> Tuple[bool, bool]: + """(has a separator dot, has any other dot); see the rules above. A dot + inside a character class counts as other.""" + separator = other = False i = 0 while i < len(regex): char = regex[i] if char == "\\": if regex.startswith(".", i + 1): - return True + separator = True i += 2 continue - if in_class: - if char == "]": - in_class = False - elif char == "[": - in_class = True - elif char == "." and _DATASET_NAME_CHAR.match(regex, i + 1): - return True + if char == "[": + end = _class_end(regex, i) + other = other or "." in regex[i:end] + i = end + continue + if char == ".": + if _SEPARATOR_FOLLOWER.match(regex, i + 1): + separator = True + else: + other = True i += 1 - return False + return separator, other def _qualify_branch(branch: str) -> str: - if ( - not branch - or branch.startswith(_SPANS_PROJECT_PREFIXES) - or _names_project(branch) - ): + if not branch or branch.startswith(_SPANS_PROJECT_PREFIXES): + return branch + separator, other = _dots(branch) + if separator: return branch + prefix = _OPTIONAL_PROJECT_PREFIX if other else _ANY_PROJECT_PREFIX if branch.startswith("^"): - return "^" + _ANY_PROJECT_PREFIX + branch[1:] - return _ANY_PROJECT_PREFIX + branch + return "^" + prefix + branch[1:] + return prefix + branch def _qualify_dataset_regex(regex: str) -> str: r"""`regex` made to match `.`, for a - `dataset_pattern` entry written against the dataset name alone. - - Each top-level alternation branch is judged on its own, so `a|b` becomes - `.*\.a|.*\.b`. A branch that already names the project or starts with a - match-anything is kept as written, so the rewrite is idempotent. An entry - whose rewrite does not compile (e.g. a leading inline flag) is kept as - written. + `dataset_pattern` entry that may be written against the dataset name + alone: `a|b` becomes `.*\.a|.*\.b`, `^staging_.*` becomes + `^(?:.*\.)?staging_.*`. Idempotent: a qualified branch is kept as is. """ - qualified = "|".join(_qualify_branch(b) for b in _top_level_branches(regex)) + flags_match = _LEADING_INLINE_FLAGS.match(regex) + flags = flags_match.group(0) if flags_match else "" + body = regex[len(flags) :] + qualified = flags + "|".join(_qualify_branch(b) for b in _top_level_branches(body)) if qualified == regex: return regex try: re.compile(qualified) except re.error: + logger.warning( + "dataset_pattern entry %r could not be qualified with the project, " + "so it is matched as written against `.`.", + regex, + ) return regex return qualified diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py index a65449e4a7661..1431460b42b2d 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py @@ -28,7 +28,7 @@ from tests.unit.bigquery.conftest import PROJECT, as_mock, make_schema_gen, make_table -def _filter(dataset_pattern: Dict[str, Any]) -> BigQueryFilter: +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()) @@ -127,6 +127,25 @@ def test_project_qualified_entry_is_kept_as_written(entry: str) -> None: assert filters.is_dataset_allowed("prod_events", PROJECT) +@pytest.mark.parametrize( + "entry", + [ + f"{PROJECT}.*", + f"^{PROJECT}.*", + f"{PROJECT}.+", + f"{PROJECT}.(my_dataset|other)$", + f"{PROJECT}.[a-z_]+$", + f"{PROJECT}.\\w+", + f"{PROJECT}[.]my_dataset", + ], +) +def test_project_qualified_entry_with_a_wildcard_dot_still_matches(entry: str) -> None: + """A `.` that may be the separator keeps matching as it did, in both + lists: the dataset-name reading is added, never substituted.""" + assert _filter({"allow": [entry]}).is_dataset_allowed("my_dataset", PROJECT) + assert not _filter({"deny": [entry]}).is_dataset_allowed("my_dataset", PROJECT) + + def test_escaped_dot_names_the_project() -> None: """Dataset names cannot contain a dot, so `a\\.b` can only mean project `a`, dataset `b`; it is not read as a dataset-name regex.""" @@ -136,10 +155,11 @@ def test_escaped_dot_names_the_project() -> None: assert not filters.is_dataset_allowed("v2", PROJECT) -def test_entry_whose_qualified_form_does_not_compile_is_kept() -> None: - # A global inline flag must stay at the start of the expression. - filters = _filter({"allow": ["(?i)staging"]}) - assert filters.filter_config.dataset_pattern.allow == ["(?i)staging"] +@pytest.mark.parametrize("entry", ["(?i)STAGING_events", "(?i)^STAGING_.*"]) +def test_leading_inline_flags_stay_in_front(entry: str) -> None: + filters = _filter({"allow": [entry]}) + assert filters.filter_config.dataset_pattern.allow[0].startswith("(?i)") + assert filters.is_dataset_allowed("staging_events", PROJECT) def test_qualification_is_idempotent() -> None: @@ -147,7 +167,7 @@ def test_qualification_is_idempotent() -> None: {"dataset_pattern": {"allow": ["^staging_.*", "a|b"], "deny": ["^tmp$"]}} ) qualified = config.dataset_pattern - assert qualified.allow == [r"^.*\.staging_.*", r".*\.a|.*\.b"] + assert qualified.allow == [r"^(?:.*\.)?staging_.*", r".*\.a|.*\.b"] assert qualified.deny == [r"^.*\.tmp$"] validate_pattern_at(config, "dataset_pattern", qualified) assert config.dataset_pattern.allow == qualified.allow diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py index 0d389e02a3a2f..1dbd26a6a224c 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py @@ -1796,9 +1796,9 @@ def test_bigquery_config_deprecated_schema_pattern(): "dataset_pattern": AllowDenyPattern(deny=["temp.*"]), } config = BigQueryV2Config.model_validate(config_with_dataset_pattern) - # dataset_pattern, qualified with "any project": `.*` is a wildcard, not - # a project separator - assert config.dataset_pattern == AllowDenyPattern(deny=[r".*\.temp.*"]) + # dataset_pattern, optionally qualified with "any project": its `.` may be + # the wildcard of a dataset-name regex + assert config.dataset_pattern == AllowDenyPattern(deny=[r"(?:.*\.)?temp.*"]) @pytest.mark.parametrize( From 8b0e3ee294c739770286d1ac82b9605ff65aeaac Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Thu, 19 Nov 2026 13:48:15 +0000 Subject: [PATCH 4/7] refactor(ingest/bigquery): replace dataset_pattern regex parsing with a simple wrap Keep master's rule for which entries get the project prefix (no `.` means a dataset name; any `.` means matched as written), but wrap the qualified entry in a group, `.*\.(?:)`, so every alternative of `a|b` is qualified. The rebuild instead of in-place edits, the separate schema_pattern object and the rest of the fix are unchanged. --- docs/how/breaking-changes.md | 23 +- .../source/bigquery_v2/bigquery_config.py | 128 +--------- .../bigquery/test_bigquery_dataset_pattern.py | 229 +++++++----------- .../unit/bigquery/test_bigquery_source.py | 10 +- 4 files changed, 109 insertions(+), 281 deletions(-) diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index 591057db85e83..ad6f70b78e147 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -15,17 +15,18 @@ the one you are on and the one you are moving to, not just the target. ## Next -### BigQuery `dataset_pattern` entries written as regular expressions ([#21430](https://github.com/datahub-project/datahub/pull/21430)) - -When `match_fully_qualified_names` is on (the default), BigQuery `dataset_pattern` entries that name -datasets with a regular expression, such as `^staging_.*` or `a|b`, now match those datasets. Before, -any entry containing a `.` was treated as already naming the project, so `^staging_.*` matched nothing -and an `allow` entry like that ingested no datasets, while a `deny` entry denied nothing. Only the -first alternative of an entry like `a|b` was matched. If you added such an entry to `deny` and it seemed -to do nothing, it now takes effect. An entry such as `my-project.*`, where the `.` could be either -the project separator or a wildcard, keeps matching what it matched before and now also matches -datasets whose names fit it. Entries that clearly name the project, such as `my-project.my_dataset`, -`my-project\.prod_.*` or `.*\.my_dataset`, are unchanged. +### BigQuery `dataset_pattern` entries with alternatives ([#21430](https://github.com/datahub-project/datahub/pull/21430)) + +When `match_fully_qualified_names` is on (the default), BigQuery `dataset_pattern` entries are matched +against `.`. An entry without a `.` names the dataset only, so the project +part is added for you. That now covers every alternative of an entry such as `staging|prod`. Before, +only the first alternative was qualified: `prod` matched nothing, so an `allow` entry like that missed +those datasets and a `deny` entry did not exclude them. If such a `deny` entry seemed to have no +effect, it now takes effect. + +An entry that contains a `.` is matched exactly as written, as before. A dataset-name regex with a `.`, +such as `^staging_.*`, therefore matches nothing; include the project part instead, for example +`.*\.staging_.*`. ### Snowflake schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) 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 9bb779a56c3a9..cb8849fe02b71 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 @@ -338,128 +338,18 @@ class GcsDatasetLineageProviderConfigBase(ConfigModel): ) -# `dataset_pattern` is matched against `.` when -# `match_fully_qualified_names` is set (the default), so an entry written for -# the dataset name alone has to be prefixed with "any project". Each top-level -# alternation branch is judged on its own: -# -# - no `.` at all: a dataset name, prefixed with `.*\.`; -# - starts with a match-anything (`.*`, `.+`): already reaches past the -# project, kept; -# - a separator dot -- `\.`, or a bare `.` followed by a name character, as in -# `my-project.my_dataset` -- names the project, kept. BigQuery dataset names -# cannot contain a dot, so such a dot can only separate project and dataset; -# - any other `.` (`staging_.*`, `my-project.*`) is ambiguous: the regex -# wildcard in a dataset-name regex, or the separator in a project-qualified -# one. Prefixed with an optional `(?:.*\.)?`, so it keeps every match it had -# and also matches as a dataset name. -_SEPARATOR_FOLLOWER = re.compile(r"[A-Za-z0-9_]") -_SPANS_PROJECT_PREFIXES = (".*", "^.*", ".+", "^.+") -_ANY_PROJECT_PREFIX = r".*\." -_OPTIONAL_PROJECT_PREFIX = r"(?:.*\.)?" -# Global inline flags must stay at the start of the expression. -_LEADING_INLINE_FLAGS = re.compile(r"^\(\?[aiLmsux]+\)") - - -def _class_end(regex: str, start: int) -> int: - """Index just past the character class opening at `regex[start]`.""" - i = start + 1 - # A `]` first in the class (after an optional `^`) is literal. - if regex.startswith("^", i): - i += 1 - if regex.startswith("]", i): - i += 1 - while i < len(regex) and regex[i] != "]": - i += 2 if regex[i] == "\\" else 1 - return i + 1 - - -def _top_level_branches(regex: str) -> List[str]: - """`regex` split on the `|` that are outside groups and character classes.""" - branches: List[str] = [] - depth = 0 - start = 0 - i = 0 - while i < len(regex): - char = regex[i] - if char == "\\": - i += 2 - continue - if char == "[": - i = _class_end(regex, i) - continue - if char == "(": - depth += 1 - elif char == ")": - depth -= 1 - elif char == "|" and depth == 0: - branches.append(regex[start:i]) - start = i + 1 - i += 1 - branches.append(regex[start:]) - return branches - - -def _dots(regex: str) -> Tuple[bool, bool]: - """(has a separator dot, has any other dot); see the rules above. A dot - inside a character class counts as other.""" - separator = other = False - i = 0 - while i < len(regex): - char = regex[i] - if char == "\\": - if regex.startswith(".", i + 1): - separator = True - i += 2 - continue - if char == "[": - end = _class_end(regex, i) - other = other or "." in regex[i:end] - i = end - continue - if char == ".": - if _SEPARATOR_FOLLOWER.match(regex, i + 1): - separator = True - else: - other = True - i += 1 - return separator, other - - -def _qualify_branch(branch: str) -> str: - if not branch or branch.startswith(_SPANS_PROJECT_PREFIXES): - return branch - separator, other = _dots(branch) - if separator: - return branch - prefix = _OPTIONAL_PROJECT_PREFIX if other else _ANY_PROJECT_PREFIX - if branch.startswith("^"): - return "^" + prefix + branch[1:] - return prefix + branch - - def _qualify_dataset_regex(regex: str) -> str: - r"""`regex` made to match `.`, for a - `dataset_pattern` entry that may be written against the dataset name - alone: `a|b` becomes `.*\.a|.*\.b`, `^staging_.*` becomes - `^(?:.*\.)?staging_.*`. Idempotent: a qualified branch is kept as is. + r"""A `dataset_pattern` entry with no `.` names the dataset alone, so it is + made to match `.`: `a|b` becomes `.*\.(?:a|b)`. + The group keeps every alternative 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. """ - flags_match = _LEADING_INLINE_FLAGS.match(regex) - flags = flags_match.group(0) if flags_match else "" - body = regex[len(flags) :] - qualified = flags + "|".join(_qualify_branch(b) for b in _top_level_branches(body)) - if qualified == regex: - return regex - try: - re.compile(qualified) - except re.error: - logger.warning( - "dataset_pattern entry %r could not be qualified with the project, " - "so it is matched as written against `.`.", - regex, - ) + if "." in regex: return regex - return qualified + if regex.startswith("^"): + return r"^.*\.(?:" + regex[1:] + ")" + return r".*\.(?:" + regex + ")" class BigQueryFilterConfig(SQLFilterConfig): diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py index 1431460b42b2d..5af285806f276 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py @@ -1,8 +1,8 @@ """`dataset_pattern` qualification under `match_fully_qualified_names`. With the flag on (the default) the connector matches `dataset_pattern` against -`.`, so `backward_compatibility_configs_set` prefixes -entries written for the dataset name alone with "any project". These tests go +`.`. An entry with no `.` is wrapped as +`.*\\.(?:)`; an entry with a `.` is matched as written. These tests go through `BigQueryFilter`, the filter the source actually uses. """ @@ -27,6 +27,12 @@ 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}) @@ -34,144 +40,62 @@ def _filter(dataset_pattern: Dict[str, List[str]]) -> BigQueryFilter: return BigQueryFilter(config, BigQueryV2Report()) -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], - ), - {}, - ) - ) - - -@pytest.mark.parametrize( - "allow,dataset", - [ - (["staging_events"], "staging_events"), - (["^staging_.*"], "staging_events"), - (["staging_.*"], "staging_events"), - (["^staging_.*$"], "staging_events"), - (["^(a|b)$"], "b"), - (["a|b"], "a"), - (["a|b"], "b"), - (["^a$|^b$"], "b"), - ], -) -def test_dataset_name_regex_allows_its_dataset(allow: List[str], dataset: str) -> None: - assert _filter({"allow": allow}).is_dataset_allowed(dataset, PROJECT) +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( - "allow,dataset", - [ - (["^staging_.*"], "prod_events"), - (["a|b"], "c"), - (["^a$|^b$"], "ab"), - ], -) -def test_dataset_name_regex_still_filters(allow: List[str], dataset: str) -> None: - assert not _filter({"allow": allow}).is_dataset_allowed(dataset, 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_.*"], ["x|restricted_pii"]]) -def test_dataset_name_regex_denies_its_dataset(deny: List[str]) -> None: +@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}.prod_.*", - f"{PROJECT}\\.prod_.*", - "^my-.*\\.prod_.*", - ".*\\.prod_.*", - ".*prod_.*", - ], + "entry", [f"{PROJECT}.*", f"{PROJECT}\\.prod_.*", ".*\\.prod_.*", ".*prod_.*"] ) -def test_project_qualified_entry_is_kept_as_written(entry: str) -> None: +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.parametrize( - "entry", - [ - f"{PROJECT}.*", - f"^{PROJECT}.*", - f"{PROJECT}.+", - f"{PROJECT}.(my_dataset|other)$", - f"{PROJECT}.[a-z_]+$", - f"{PROJECT}.\\w+", - f"{PROJECT}[.]my_dataset", - ], -) -def test_project_qualified_entry_with_a_wildcard_dot_still_matches(entry: str) -> None: - """A `.` that may be the separator keeps matching as it did, in both - lists: the dataset-name reading is added, never substituted.""" - assert _filter({"allow": [entry]}).is_dataset_allowed("my_dataset", PROJECT) - assert not _filter({"deny": [entry]}).is_dataset_allowed("my_dataset", 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) -def test_escaped_dot_names_the_project() -> None: - """Dataset names cannot contain a dot, so `a\\.b` can only mean project - `a`, dataset `b`; it is not read as a dataset-name regex.""" - filters = _filter({"allow": ["my_dataset\\.v2"]}) - assert filters.filter_config.dataset_pattern.allow == ["my_dataset\\.v2"] - assert filters.is_dataset_allowed("v2", "my_dataset") - assert not filters.is_dataset_allowed("v2", PROJECT) - -@pytest.mark.parametrize("entry", ["(?i)STAGING_events", "(?i)^STAGING_.*"]) -def test_leading_inline_flags_stay_in_front(entry: str) -> None: - filters = _filter({"allow": [entry]}) - assert filters.filter_config.dataset_pattern.allow[0].startswith("(?i)") - assert filters.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": ["^staging_.*", "a|b"], "deny": ["^tmp$"]}} + {"dataset_pattern": {"allow": ["a|b"], "deny": ["^tmp$"]}} ) qualified = config.dataset_pattern - assert qualified.allow == [r"^(?:.*\.)?staging_.*", r".*\.a|.*\.b"] - assert qualified.deny == [r"^.*\.tmp$"] validate_pattern_at(config, "dataset_pattern", qualified) - assert config.dataset_pattern.allow == qualified.allow - assert config.dataset_pattern.deny == qualified.deny + assert config.dataset_pattern.allow == [r".*\.(?:a|b)"] + assert config.dataset_pattern.deny == [r"^.*\.(?:tmp$)"] def test_qualification_ignores_a_warm_regex_cache() -> None: @@ -180,8 +104,9 @@ def test_qualification_ignores_a_warm_regex_cache() -> None: pattern = AllowDenyPattern(allow=["mydataset"]) assert pattern.allowed("mydataset") # warms _compiled_allow config = BigQueryV2Config(dataset_pattern=pattern) - filters = BigQueryFilter(config, BigQueryV2Report()) - assert filters.is_dataset_allowed("mydataset", PROJECT) + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "mydataset", PROJECT + ) assert pattern.allow == ["mydataset"] @@ -190,8 +115,9 @@ def test_revalidating_a_warm_pattern_qualifies_it() -> None: pattern = AllowDenyPattern(allow=["mydataset"]) assert pattern.allowed("mydataset") # warms _compiled_allow validate_pattern_at(config, "dataset_pattern", pattern) - filters = BigQueryFilter(config, BigQueryV2Report()) - assert filters.is_dataset_allowed("mydataset", PROJECT) + assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( + "mydataset", PROJECT + ) assert pattern.allow == ["mydataset"] @@ -206,40 +132,51 @@ def test_schema_pattern_fallback_is_an_independent_pattern() -> None: ) -def test_not_qualified_when_matching_bare_names() -> None: - config = BigQueryV2Config.model_validate( - { - "dataset_pattern": {"allow": ["^staging_.*"]}, - "match_fully_qualified_names": False, - } - ) - assert config.dataset_pattern.allow == ["^staging_.*"] - assert BigQueryFilter(config, BigQueryV2Report()).is_dataset_allowed( - "staging_events", PROJECT - ) +def _columns( + by_table: Dict[str, List[BigqueryColumn]], +) -> FileBackedDict[List[BigqueryColumn]]: + columns: FileBackedDict[List[BigqueryColumn]] = FileBackedDict() + columns.update(by_table) + return columns -def test_regex_allow_entry_ingests_the_matching_dataset() -> None: - """End to end: with allow `^staging_.*`, staging_events must be ingested.""" - schema_gen = make_schema_gen( - dataset_pattern={"allow": ["^staging_.*"]}, - include_views=False, - include_table_snapshots=False, - include_table_constraints=False, - ) +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 - urns = _status_urns( - _run_over_datasets(schema_gen, ["staging_events", "prod_events"]) - ) - assert any(urn.endswith("staging_events.t1,PROD)") for urn in urns), urns - assert not any("prod_events" in urn for urn in urns), urns +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_regex_deny_entry_keeps_the_matching_dataset_out() -> None: - """End to end: with deny `^restricted_.*`, restricted_pii must be dropped.""" +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": ["^restricted_.*"]}, + dataset_pattern={"deny": ["tmp|restricted_pii"]}, include_views=False, include_table_snapshots=False, include_table_constraints=False, diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py index 1dbd26a6a224c..6bb5ab6b609e5 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py @@ -120,12 +120,12 @@ def test_bigquery_dataset_pattern(): } ) assert config.dataset_pattern.allow == [ - r".*\.test-dataset", + r".*\.(?:test-dataset)", r"test-project.test-dataset", r".*test-dataset", ] assert config.dataset_pattern.deny == [ - r"^.*\.test-dataset-2$", + r"^.*\.(?:test-dataset-2$)", r"project\.second_dataset", ] @@ -1796,9 +1796,9 @@ def test_bigquery_config_deprecated_schema_pattern(): "dataset_pattern": AllowDenyPattern(deny=["temp.*"]), } config = BigQueryV2Config.model_validate(config_with_dataset_pattern) - # dataset_pattern, optionally qualified with "any project": its `.` may be - # the wildcard of a dataset-name regex - assert config.dataset_pattern == AllowDenyPattern(deny=[r"(?:.*\.)?temp.*"]) + assert config.dataset_pattern == AllowDenyPattern( + deny=["temp.*"] + ) # dataset_pattern @pytest.mark.parametrize( From 00b0e47752c8d1f7a8883d97c41ed6a4333ae467 Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Thu, 19 Nov 2026 13:54:21 +0000 Subject: [PATCH 5/7] docs: clarify the BigQuery and Snowflake breaking-change notes --- docs/how/breaking-changes.md | 52 ++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index ad6f70b78e147..4ad6686bb5483 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -15,24 +15,48 @@ the one you are on and the one you are moving to, not just the target. ## Next -### BigQuery `dataset_pattern` entries with alternatives ([#21430](https://github.com/datahub-project/datahub/pull/21430)) +### BigQuery: `dataset_pattern` entries listing several datasets with `|` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) -When `match_fully_qualified_names` is on (the default), BigQuery `dataset_pattern` entries are matched -against `.`. An entry without a `.` names the dataset only, so the project -part is added for you. That now covers every alternative of an entry such as `staging|prod`. Before, -only the first alternative was qualified: `prod` matched nothing, so an `allow` entry like that missed -those datasets and a `deny` entry did not exclude them. If such a `deny` entry seemed to have no -effect, it now takes effect. +**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 `|`: -An entry that contains a `.` is matched exactly as written, as before. A dataset-name regex with a `.`, -such as `^staging_.*`, therefore matches nothing; include the project part instead, for example -`.*\.staging_.*`. +```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. -### Snowflake schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) +### Snowflake: schemas whose names end in `INFORMATION_SCHEMA` ([#21430](https://github.com/datahub-project/datahub/pull/21430)) -Snowflake ingestion now skips only the `INFORMATION_SCHEMA` schema itself. A schema such as -`MY_INFORMATION_SCHEMA` used to be skipped silently and is now ingested like any other schema. To keep -skipping it, add it to `schema_pattern.deny`. +**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$" +``` ### CLI initialization from scripts From 46da344ecfe8f2213746e915079e3afbc185bb88 Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Fri, 27 Nov 2026 13:36:16 +0000 Subject: [PATCH 6/7] fix(ingest/bigquery): group dataset_pattern entries only when they contain | Entries without alternation keep master's qualified spelling (.*\.foo), so anything comparing or displaying the qualified pattern is unchanged. Also narrow _rebuilt's override types and document the mixed-alternation case in the breaking-changes entry. --- docs/how/breaking-changes.md | 4 ++++ .../src/datahub/configuration/common.py | 2 +- .../source/bigquery_v2/bigquery_config.py | 16 +++++++++------- .../bigquery/test_bigquery_dataset_pattern.py | 11 ++++++----- .../tests/unit/bigquery/test_bigquery_source.py | 4 ++-- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index f8fab32b37862..269caa996c507 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -37,6 +37,10 @@ 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)) diff --git a/metadata-ingestion/src/datahub/configuration/common.py b/metadata-ingestion/src/datahub/configuration/common.py index 3559338cd1bb4..0079a428b3f71 100644 --- a/metadata-ingestion/src/datahub/configuration/common.py +++ b/metadata-ingestion/src/datahub/configuration/common.py @@ -527,7 +527,7 @@ def with_deny(self, *rules: str) -> Self: duplicates already in the deny list are collapsed too.""" return self._rebuilt(deny=deduplicate_list([*self.deny, *rules])) - def _rebuilt(self, **overrides: Any) -> Self: + def _rebuilt(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, 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 61999cbc0bfc8..a9a9202818147 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 @@ -353,16 +353,18 @@ 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|b` becomes `.*\.(?:a|b)`. - The group keeps every alternative 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. + 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 - if regex.startswith("^"): - return r"^.*\.(?:" + regex[1:] + ")" - return r".*\.(?:" + regex + ")" + anchor, body = ("^", regex[1:]) if regex.startswith("^") else ("", regex) + if "|" in body: + body = "(?:" + body + ")" + return anchor + r".*\." + body class BigQueryFilterConfig(SQLFilterConfig): diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py index 5af285806f276..545043e5f3001 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_dataset_pattern.py @@ -1,9 +1,10 @@ """`dataset_pattern` qualification under `match_fully_qualified_names`. With the flag on (the default) the connector matches `dataset_pattern` against -`.`. An entry with no `.` is wrapped as -`.*\\.(?:)`; an entry with a `.` is matched as written. These tests go -through `BigQueryFilter`, the filter the source actually uses. +`.`. 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 @@ -42,7 +43,7 @@ def _filter(dataset_pattern: Dict[str, List[str]]) -> BigQueryFilter: 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.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) @@ -95,7 +96,7 @@ def test_qualification_is_idempotent() -> None: 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$)"] + assert config.dataset_pattern.deny == [r"^.*\.tmp$"] def test_qualification_ignores_a_warm_regex_cache() -> None: diff --git a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py index a8a5fcae07e29..d81961ae32bb6 100644 --- a/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py +++ b/metadata-ingestion/tests/unit/bigquery/test_bigquery_source.py @@ -124,12 +124,12 @@ def test_bigquery_dataset_pattern(): } ) assert config.dataset_pattern.allow == [ - r".*\.(?:test-dataset)", + r".*\.test-dataset", r"test-project.test-dataset", r".*test-dataset", ] assert config.dataset_pattern.deny == [ - r"^.*\.(?:test-dataset-2$)", + r"^.*\.test-dataset-2$", r"project\.second_dataset", ] From c0bdb50e721b89b88086f30f7105a2df99cdac47 Mon Sep 17 00:00:00 2001 From: Sergio Gomez Date: Fri, 27 Nov 2026 14:39:22 +0000 Subject: [PATCH 7/7] refactor(ingest): rename AllowDenyPattern._rebuilt to with_fields It is called from other modules and documented as the way to derive a pattern, so give it a public name alongside with_deny. --- metadata-ingestion/src/datahub/configuration/common.py | 4 ++-- .../src/datahub/ingestion/agent/filter_check.py | 4 ++-- .../ingestion/source/bigquery_v2/bigquery_config.py | 8 +++++--- metadata-ingestion/tests/unit/config/test_allow_deny.py | 8 ++++---- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/metadata-ingestion/src/datahub/configuration/common.py b/metadata-ingestion/src/datahub/configuration/common.py index 0079a428b3f71..2d27b9dc10299 100644 --- a/metadata-ingestion/src/datahub/configuration/common.py +++ b/metadata-ingestion/src/datahub/configuration/common.py @@ -525,9 +525,9 @@ 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.""" - return self._rebuilt(deny=deduplicate_list([*self.deny, *rules])) + return self.with_fields(deny=deduplicate_list([*self.deny, *rules])) - def _rebuilt(self, **overrides: Union[List[str], bool]) -> Self: + 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, diff --git a/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py b/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py index c1183129e7f75..b7d9b28c91e50 100644 --- a/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py +++ b/metadata-ingestion/src/datahub/ingestion/agent/filter_check.py @@ -321,7 +321,7 @@ def _trial_pattern( """The recipe's pattern with each --try-* flag replacing only its own half, every other field (`ignoreCase`) kept. - Rebuilt (see `AllowDenyPattern._rebuilt`), not model_copy'd. + 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 @@ -339,7 +339,7 @@ def _trial_pattern( overrides["allow"] = list(try_allow) if try_deny: overrides["deny"] = list(try_deny) - return recipe_pattern._rebuilt(**overrides) + return recipe_pattern.with_fields(**overrides) def _with_trial_pattern( 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 a9a9202818147..0d55c79dfb67a 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 @@ -434,7 +434,7 @@ class BigQueryFilterConfig(SQLFilterConfig): def backward_compatibility_configs_set(self) -> Any: # 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._rebuilt. + # the old entries. See AllowDenyPattern.with_fields. if ( self.dataset_pattern.is_allow_all() and not self.schema_pattern.is_allow_all() @@ -443,7 +443,7 @@ def backward_compatibility_configs_set(self) -> Any: "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 = self.schema_pattern._rebuilt() + self.dataset_pattern = self.schema_pattern.with_fields() elif ( not self.dataset_pattern.is_allow_all() and not self.schema_pattern.is_allow_all() @@ -471,7 +471,9 @@ def backward_compatibility_configs_set(self) -> Any: 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._rebuilt(allow=allow, deny=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/tests/unit/config/test_allow_deny.py b/metadata-ingestion/tests/unit/config/test_allow_deny.py index cb881156b8e28..dd3a5d3585c0e 100644 --- a/metadata-ingestion/tests/unit/config/test_allow_deny.py +++ b/metadata-ingestion/tests/unit/config/test_allow_deny.py @@ -115,19 +115,19 @@ class Sub(AllowDenyPattern): assert type(Sub().with_deny("x")) is Sub -def test_rebuilt_matches_the_new_lists_not_the_cached_ones() -> None: +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._rebuilt(allow=["new"]) + 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_rebuilt_without_overrides_is_an_independent_equal_copy() -> None: +def test_with_fields_without_overrides_is_an_independent_equal_copy() -> None: p = AllowDenyPattern(allow=["a"], deny=["b"]) - p2 = p._rebuilt() + p2 = p.with_fields() assert p2 is not p assert p2 == p assert p2.allow is not p.allow