Skip to content

Commit 4e37ad0

Browse files
mikebridgeMike Bridge
andauthored
fix(semantic-layer): keep NULL rows in user exclusion filters (#46377)
Co-authored-by: Mike Bridge <michael.bridge@ext.preset.io>
1 parent 6425d6d commit 4e37ad0

13 files changed

Lines changed: 235 additions & 38 deletions

‎UPDATING.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ assists people when migrating to a new version.
2424

2525
## Next
2626

27+
- Semantic-view user exclusions (`!=`, non-empty `NOT IN` without NULL, `NOT LIKE`, and `NOT ILIKE`) reach providers as an OR group with `IS_NULL`; upgrade leaf-only adapters before deploying the host, even if they accepted those operators before. See the [provider filter contract](docs/developer_docs/extensions/extension-points/semantic-layers.md#filter-expressions).
28+
2729
- Semantic views reject Histogram, Calendar Heatmap, Time-series Table, Time-series
2830
Period Pivot, Nightingale Rose, Horizon, and Paired t-test charts instead of
2931
returning misleading or empty data. This includes saved charts and their cached

‎docs/docs/using-superset/semantic-member-selections.mdx‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,14 +158,22 @@ A mixed selection such as `IN ('a', NULL)` means `IN ('a') OR IS NULL`. Its nega
158158
form, `NOT IN ('a', NULL)`, means `NOT IN ('a') AND IS NOT NULL`; it excludes both
159159
`'a'` and missing values. An empty IN selection matches no rows and an empty
160160
NOT IN selection matches every row, including missing values, as in SQL. A total
161-
without grouping still returns one row, for example a count of 0. Non-NULL
162-
comparisons retain their existing semantics.
161+
without grouping still returns one row, for example a count of 0.
162+
163+
Chart and dashboard exclude (`NOT IN`), not-equal (`!=`), `NOT LIKE` and `NOT ILIKE`
164+
filters keep rows with missing values, matching ordinary datasets. For example,
165+
`NOT IN ('a')` becomes `NOT IN ('a') OR IS NULL`. Select NULL explicitly to
166+
exclude those rows too; `!= NULL` remains `IS NOT NULL`.
167+
This user-filter normalization does not change SDK-authored predicates or
168+
literal SQL semantics. A provider that does not support an operator continues
169+
to refuse it as before.
170+
Cached chart results for semantic views and ordinary dataset charts with annotation layers are rebuilt once after deployment.
163171

164172
Host filter-value types accept missing values (`None`) inside list selections
165173
and variable-length tuples, so multi-value selections can preserve NULL members.
166174

167-
Every semantic provider must support mixed positive selections through grouped
168-
OR predicates. NULL-only and mixed negative selections use ordinary leaf
175+
Every semantic provider must support mixed positive selections and NULL-preserving
176+
exclusions through grouped OR predicates. NULL-only and mixed negative selections use ordinary leaf
169177
predicates. Provider adapters must be upgraded before, or together with, the
170178
host/SDK so that mixed selections preserve missing-value rows.
171179

‎superset/common/query_context_processor.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ def _annotation_cache_context( # noqa: C901
684684
context: dict[str, Any] = {
685685
"user_id": get_user_id(),
686686
"source_rls": source_rls,
687-
"semantic_filter_protocol": "semantic-null-filters-v1",
687+
"semantic_filter_protocol": "semantic-null-filters-v2",
688688
"source_versions": metadata_versions,
689689
}
690690
# Omit optional components when empty to preserve unaffected key bytes.

‎superset/semantic_layers/mapper.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,7 @@ def _convert_query_object_filter(
10681068
"Must specify a value for this comparison."
10691069
)
10701070

1071-
return _normalize_membership_filter(
1071+
return _normalize_user_filter(
10721072
Filter(
10731073
type=PredicateType.WHERE,
10741074
column=dimension,
@@ -1078,8 +1078,8 @@ def _convert_query_object_filter(
10781078
)
10791079

10801080

1081-
def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
1082-
"""Normalize NULL equality/membership; empty membership stays a SQL constant.
1081+
def _normalize_user_filter(filter_: Filter) -> set[FilterExpression]:
1082+
"""Normalize user NULL selections and preserve NULL rows in exclusions.
10831083
10841084
An empty ``IN`` is FALSE and an empty ``NOT IN`` is TRUE, NULL rows included,
10851085
at the filter's position in the query. Providers render the constant.
@@ -1090,6 +1090,16 @@ def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
10901090
operator=Operator.IS_NOT_NULL if negated else Operator.IS_NULL,
10911091
value=None,
10921092
)
1093+
if filter_.value is not None and filter_.operator in {
1094+
Operator.NOT_EQUALS,
1095+
Operator.NOT_LIKE,
1096+
Operator.NOT_ILIKE,
1097+
}:
1098+
return {
1099+
OrFilter(
1100+
frozenset({filter_, replace(null_filter, operator=Operator.IS_NULL)})
1101+
)
1102+
}
10931103
if filter_.operator in {Operator.EQUALS, Operator.NOT_EQUALS}:
10941104
return {null_filter} if filter_.value is None else {filter_}
10951105
if filter_.operator not in {Operator.IN, Operator.NOT_IN}:
@@ -1103,6 +1113,16 @@ def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
11031113
if not values:
11041114
return {replace(filter_, value=values)}
11051115
if None not in values:
1116+
# User exclusions keep unselected NULL rows, like ordinary datasets.
1117+
# Keep SDK NOT_IN leaf semantics intact for providers and cache reuse.
1118+
if filter_.operator == Operator.NOT_IN:
1119+
return {
1120+
OrFilter(
1121+
frozenset(
1122+
{filter_, replace(null_filter, operator=Operator.IS_NULL)}
1123+
)
1124+
)
1125+
}
11061126
return {filter_}
11071127

11081128
non_null_values: frozenset[FilterValues] = values - {None}

‎superset/semantic_layers/models.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -892,7 +892,7 @@ def result_cache_discriminator(self) -> tuple[str, str] | None:
892892
def get_extra_cache_keys(self, query_obj: QueryObjectDict) -> list[Hashable]:
893893
discriminator: tuple[str, str] | None = self.result_cache_discriminator
894894
# Separate cached pre-normalization results during rolling deployments.
895-
keys: list[Hashable] = [self.metadata_generation, "semantic-null-filters-v1"]
895+
keys: list[Hashable] = [self.metadata_generation, "semantic-null-filters-v2"]
896896
if discriminator is not None:
897897
keys.append(("semantic-result-version", *discriminator))
898898
return keys

‎tests/unit_tests/common/test_query_context_processor.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3307,7 +3307,7 @@ def test_semantic_annotation_generation_versions_sql_parent(
33073307
assert old == {
33083308
"user_id": 42,
33093309
"source_rls": {"7": ["scope"]},
3310-
"semantic_filter_protocol": "semantic-null-filters-v1",
3310+
"semantic_filter_protocol": "semantic-null-filters-v2",
33113311
"source_versions": {"7": view.metadata_generation},
33123312
}
33133313
assert new != old
@@ -3516,7 +3516,7 @@ def payload(context: QueryContext, **kwargs: Any) -> dict[str, Any]:
35163516
assert current_key != legacy_key
35173517
assert context == {
35183518
**legacy_context,
3519-
"semantic_filter_protocol": "semantic-null-filters-v1",
3519+
"semantic_filter_protocol": "semantic-null-filters-v2",
35203520
"source_versions": {"7": view.metadata_generation},
35213521
}
35223522

‎tests/unit_tests/semantic_layers/cache_or_filters_test.py‎

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,12 @@
4040
SemanticCacheState,
4141
)
4242
from superset.semantic_layers.cache_identity import SemanticCacheIdentityFactory
43-
from superset.semantic_layers.cache_policy import ContainmentCapabilities
43+
from superset.semantic_layers.cache_policy import (
44+
ContainmentCapabilities,
45+
PatternSemantics,
46+
)
4447
from superset.semantic_layers.cache_repository import SemanticCacheRepository
48+
from superset.semantic_layers.mapper import _convert_query_object_filter
4549
from tests.unit_tests.semantic_layers.cache_repository_test import (
4650
_Backend,
4751
_Coordinator,
@@ -88,6 +92,94 @@ def test_group_identity_is_order_independent_and_not_flattened() -> None:
8892
assert ":v5:" in identity
8993

9094

95+
@pytest.mark.parametrize(
96+
"operator,value",
97+
[
98+
("NOT IN", frozenset({"GB"})),
99+
("!=", "GB"),
100+
("NOT LIKE", "G%"),
101+
("NOT ILIKE", "g%"),
102+
],
103+
)
104+
def test_user_exclusion_cannot_reuse_old_null_dropping_results(
105+
operator: str,
106+
value: FilterValues | frozenset[FilterValues],
107+
) -> None:
108+
"""Normalized user exclusion is distinct from its NULL-dropping SDK leaf."""
109+
query: SemanticQuery = build_semantic_query()
110+
leaf: Filter = Filter(
111+
PredicateType.WHERE, query.dimensions[0], Operator(operator), value
112+
)
113+
old: SemanticQuery = replace(query, filters={leaf})
114+
normalized: set[FilterExpression] | None = _convert_query_object_filter(
115+
{
116+
"col": query.dimensions[0].name,
117+
"op": operator,
118+
"val": list(value) if isinstance(value, frozenset) else value,
119+
},
120+
{query.dimensions[0].name: query.dimensions[0]},
121+
)
122+
requested: SemanticQuery = replace(query, filters=normalized)
123+
assert SemanticCacheIdentityFactory.query(
124+
old
125+
) != SemanticCacheIdentityFactory.query(requested)
126+
result: SemanticResult = SemanticResult(
127+
requests=[], results=pa.table({"Country": ["US"], "Revenue": [42.0]})
128+
)
129+
stored: SemanticQuery
130+
lookup: SemanticQuery
131+
for stored, lookup in ((old, requested), (requested, old)):
132+
repository: SemanticCacheRepository = SemanticCacheRepository(
133+
_Backend(), _Coordinator()
134+
)
135+
assert repository.store(build_view_meta(), stored, result)
136+
assert not repository.lookup(
137+
build_view_meta(),
138+
lookup,
139+
ContainmentCapabilities(comparisons=True, membership=True, nulls=True),
140+
).candidates
141+
142+
143+
@pytest.mark.parametrize("operator", ["NOT LIKE", "NOT ILIKE", "!="])
144+
def test_negated_group_reuse_requires_exact_pattern(operator: str) -> None:
145+
"""A broader pattern must not become a cache containment or leftover filter."""
146+
query: SemanticQuery = build_semantic_query()
147+
dimension_name: str = query.dimensions[0].name
148+
queries: list[SemanticQuery] = [
149+
replace(
150+
query,
151+
filters=_convert_query_object_filter(
152+
{"col": dimension_name, "op": operator, "val": pattern},
153+
{dimension_name: query.dimensions[0]},
154+
),
155+
)
156+
for pattern in ("G%", "GB%")
157+
]
158+
result: SemanticResult = SemanticResult(
159+
requests=[], results=pa.table({"Country": [None, "US"], "Revenue": [7.0, 42.0]})
160+
)
161+
stored: SemanticQuery
162+
lookup: SemanticQuery
163+
for stored, lookup in (queries, list(reversed(queries))):
164+
repository: SemanticCacheRepository = SemanticCacheRepository(
165+
_Backend(), _Coordinator()
166+
)
167+
assert repository.store(build_view_meta(), stored, result)
168+
capabilities: ContainmentCapabilities = ContainmentCapabilities(
169+
comparisons=True,
170+
membership=True,
171+
nulls=True,
172+
pattern_semantics=PatternSemantics.sql_like(escape="\\"),
173+
)
174+
assert repository.lookup(build_view_meta(), stored, capabilities).candidates
175+
assert (
176+
not repository.lookup(build_view_meta(), stored, capabilities)
177+
.candidates[0]
178+
.decision.leftover_filters
179+
)
180+
assert not repository.lookup(build_view_meta(), lookup, capabilities).candidates
181+
182+
91183
@pytest.mark.parametrize("location", ["query", "group_limit", "both"])
92184
def test_grouped_query_is_stored_and_served_without_cache_failures(
93185
location: str,

‎tests/unit_tests/semantic_layers/execution_context_test.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ def test_connection_credentials_keys_unchanged(
102102
"col_values:eb5d43a7322c2a03556fc53bc62d54fbbe0b3d26d561d18a0e385c7457abd822",
103103
# Compatibility identity includes changed_on="None" for this view.
104104
"compatible:a2e526c4cd1db4f68fd34cc7dffe06cc4fbd029975f2147b4b11bb55179795b8",
105-
# Recorded on master ffee0a843f: #45133 adds semantic-null-filters-v1
106-
# to chart keys; the execution-context contract adds no discriminator.
107-
"80b906df8cf7f4837b95d21c32c6f71bd6c810fcf7c1896dbeca74a5023ea961",
105+
# NULL-preserving exclusions use semantic-null-filters-v2 in chart keys;
106+
# the execution-context contract adds no discriminator.
107+
"0b34147df459869c54682b7f1c9f65ea642ee8b746193352ed2322e75c318575",
108108
]
109109

110110

‎tests/unit_tests/semantic_layers/mapper_test.py‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
Metric,
4343
Operator,
4444
OrderDirection,
45+
OrFilter,
4546
PredicateType,
4647
SemanticQuery,
4748
SemanticRequest,
@@ -443,6 +444,9 @@ def test_get_filters_from_extras_rejects_sql(extras: dict[str, str]) -> None:
443444
[
444445
{"where": "customer_id > 100"},
445446
{"having": "SUM(sales) > 1000"},
447+
{"having": "SUM(sales) != 1000"},
448+
{"having": "MAX(category) NOT LIKE 'a%'"},
449+
{"having": "MAX(category) NOT ILIKE 'A%'"},
446450
{"where": "region = 'US'", "having": "COUNT(*) > 10"},
447451
],
448452
)
@@ -620,6 +624,20 @@ def test_convert_query_object_filter_ilike(
620624
assert result is not None
621625
assert len(result) == 1
622626
converted: FilterExpression = next(iter(result))
627+
if expected == Operator.NOT_ILIKE:
628+
assert isinstance(converted, OrFilter)
629+
assert (
630+
Filter(
631+
PredicateType.WHERE,
632+
all_dimensions["category"],
633+
Operator.IS_NULL,
634+
None,
635+
)
636+
in converted.filters
637+
)
638+
converted = next(
639+
leaf for leaf in converted.filters if leaf.operator == expected
640+
)
623641
assert isinstance(converted, Filter)
624642
assert converted.operator == expected
625643
assert converted.column == all_dimensions["category"]
@@ -1996,14 +2014,31 @@ def test_convert_query_object_filter(
19962014

19972015
result = _convert_query_object_filter(filter_, all_dimensions)
19982016

1999-
assert result == {
2000-
Filter(
2001-
type=PredicateType.WHERE,
2002-
column=all_dimensions["category"],
2003-
operator=expected_operator,
2004-
value="Electronics",
2005-
)
2006-
}
2017+
expected: Filter = Filter(
2018+
type=PredicateType.WHERE,
2019+
column=all_dimensions["category"],
2020+
operator=expected_operator,
2021+
value="Electronics",
2022+
)
2023+
assert result == (
2024+
{
2025+
OrFilter(
2026+
frozenset(
2027+
{
2028+
expected,
2029+
Filter(
2030+
PredicateType.WHERE,
2031+
all_dimensions["category"],
2032+
Operator.IS_NULL,
2033+
None,
2034+
),
2035+
}
2036+
)
2037+
)
2038+
}
2039+
if filter_op == "!="
2040+
else {expected}
2041+
)
20072042

20082043

20092044
def test_convert_query_object_filter_like() -> None:

‎tests/unit_tests/semantic_layers/metadata_namespace_test.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def test_metadata_aliases_share_result_cache(
174174
web_context.datasource.metadata_generation
175175
)
176176
assert (
177-
"semantic-null-filters-v1"
177+
"semantic-null-filters-v2"
178178
in web_context.datasource.get_extra_cache_keys({})
179179
)
180180

0 commit comments

Comments
 (0)