Skip to content
Merged
2 changes: 2 additions & 0 deletions UPDATING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ assists people when migrating to a new version.

## Next

- 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).

- Dashboard lookups by ID or slug return HTTP 403 when the dashboard exists but
the caller cannot view it, rather than treating an access-filtered dashboard
as missing. Missing and soft-deleted dashboards still return HTTP 404, as do
Expand Down
18 changes: 14 additions & 4 deletions docs/developer_docs/extensions/extension-points/semantic-layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,13 @@ membership reaches providers as one `IN` or `NOT_IN` leaf with an empty
`frozenset`: render empty `IN` as FALSE and empty `NOT IN` as TRUE (NULL rows
included), never as an empty SQL list. NULL comparison/LIKE operands are rejected
before provider calls.
User exclusions with non-NULL operands become
`OrFilter(NOT_EQUALS(value), IS_NULL)`, `OrFilter(NOT_LIKE(value), IS_NULL)` or
`OrFilter(NOT_ILIKE(value), IS_NULL)`. Non-empty `NOT_IN` selections without NULL
become `OrFilter(NOT_IN(values), IS_NULL)` too. These groups keep missing-value
rows, matching ordinary datasets. Explicit NULL exclusion and empty membership
retain the leaf shapes above. This normalization applies to host user filters,
not SDK-authored predicates; unsupported operators must still be refused.
Scalar comparisons use the first collection value, or NULL for an empty collection,
matching native datasources.

Expand All @@ -300,7 +307,8 @@ semantic views; explicit query filters still apply, including group-limit filter
`OrFilter` is mandatory core vocabulary, not an optional capability. Every
provider must render groups for main queries, row counts and group-limit
subqueries. Upgrade adapters before, or atomically with, the host/SDK upgrade;
leaf-only adapters cannot consume mixed positive NULL selections. `get_values` retains
leaf-only adapters cannot consume mixed positive NULL selections or NULL-preserving
exclusions, even if they previously accepted the exclusion as a leaf. `get_values` retains
`set[Filter] | None`; its host caller supplies only a LIKE leaf or no filter.

Query and group-limit readers need `isinstance` narrowing before accessing leaf
Expand All @@ -327,9 +335,11 @@ adapter module so older SDKs can still load the legacy leaf path.

### Result caches

The host includes `semantic-null-filters-v1` in semantic result-cache keys. This
separates legacy answers during rolling deployment without flushing unrelated
caches. Keep this protocol marker alongside any metadata-generation cache keys.
The host includes `semantic-null-filters-v2` in semantic result-cache keys. This
separates answers computed before NULL-preserving exclusions during rolling
deployment. Annotation cache context also includes this marker for every
datasource, so ordinary dataset charts with annotation layers rebuild their
cached results too. Keep this marker alongside metadata-generation cache keys.

Containment-cache identities use format `v5`, separating grouped predicates from
older leaf-only entries during rolling upgrades. OR groups require identical
Expand Down
16 changes: 12 additions & 4 deletions docs/docs/using-superset/semantic-member-selections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,22 @@ A mixed selection such as `IN ('a', NULL)` means `IN ('a') OR IS NULL`. Its nega
form, `NOT IN ('a', NULL)`, means `NOT IN ('a') AND IS NOT NULL`; it excludes both
`'a'` and missing values. An empty IN selection matches no rows and an empty
NOT IN selection matches every row, including missing values, as in SQL. A total
without grouping still returns one row, for example a count of 0. Non-NULL
comparisons retain their existing semantics.
without grouping still returns one row, for example a count of 0.

Chart and dashboard exclude (`NOT IN`), not-equal (`!=`), `NOT LIKE` and `NOT ILIKE`
filters keep rows with missing values, matching ordinary datasets. For example,
`NOT IN ('a')` becomes `NOT IN ('a') OR IS NULL`. Select NULL explicitly to
exclude those rows too; `!= NULL` remains `IS NOT NULL`.
This user-filter normalization does not change SDK-authored predicates or
literal SQL semantics. A provider that does not support an operator continues
to refuse it as before.
Comment on lines +165 to +166

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a blocker, and +1 to @aminghadersohi's note below on the provider contract. One measured case for this sentence: a provider that accepts != or NOT IN as a leaf but rejects groups goes from answering to refusing. The in-repo E2E stub (tests/e2e_extensions/semantic_stub) is one, since it rejects every OrFilter: both filters return 200 before this change and 400 with it. Could we add an UPDATING.md line, like the earlier semantic NULL filter change and the dataset != / NOT LIKE change both got, and teach the stub groups here or in a follow-up?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the UPDATING.md compatibility line in a0e416c.

You're right that the stub rejects every OR group. Teaching it grouped predicates is left as a separate follow-up rather than changing provider execution in this docs/test patch.

Cached chart results for semantic views and ordinary dataset charts with annotation layers are rebuilt once after deployment.

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

Every semantic provider must support mixed positive selections through grouped
OR predicates. NULL-only and mixed negative selections use ordinary leaf
Every semantic provider must support mixed positive selections and NULL-preserving
exclusions through grouped OR predicates. NULL-only and mixed negative selections use ordinary leaf
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
predicates. Provider adapters must be upgraded before, or together with, the
host/SDK so that mixed selections preserve missing-value rows.

Expand Down
2 changes: 1 addition & 1 deletion superset/common/query_context_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ def _annotation_cache_context( # noqa: C901
context: dict[str, Any] = {
"user_id": get_user_id(),
"source_rls": source_rls,
"semantic_filter_protocol": "semantic-null-filters-v1",
"semantic_filter_protocol": "semantic-null-filters-v2",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a blocker, and I might be missing the intent. semantic_filter_protocol goes into the annotation context for every datasource, so this bump also rotates the key of ordinary dataset charts that carry an annotation layer. I checked a SqlaTable chart: with a native annotation layer its key changes with this PR, and without a layer it stays the same. The body and the docs scope the one-time rebuild to semantic views. Worth saying so there, or should the field only be added when a source is a SemanticView?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right: the annotation context includes the marker for ordinary datasets too, so a dataset chart with a native annotation layer also gets a one-time rebuild. The docs now say so in a0e416c; cache-key behavior itself is unchanged by the follow-up.

"source_versions": metadata_versions,
}
# Omit optional components when empty to preserve unaffected key bytes.
Expand Down
26 changes: 23 additions & 3 deletions superset/semantic_layers/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ def _convert_query_object_filter(
"Must specify a value for this comparison."
)

return _normalize_membership_filter(
return _normalize_user_filter(
Filter(
type=PredicateType.WHERE,
column=dimension,
Expand All @@ -1053,8 +1053,8 @@ def _convert_query_object_filter(
)


def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
"""Normalize NULL equality/membership; empty membership stays a SQL constant.
def _normalize_user_filter(filter_: Filter) -> set[FilterExpression]:
"""Normalize user NULL selections and preserve NULL rows in exclusions.

An empty ``IN`` is FALSE and an empty ``NOT IN`` is TRUE, NULL rows included,
at the filter's position in the query. Providers render the constant.
Expand All @@ -1065,6 +1065,16 @@ def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
operator=Operator.IS_NOT_NULL if negated else Operator.IS_NULL,
value=None,
)
if filter_.value is not None and filter_.operator in {
Operator.NOT_EQUALS,
Operator.NOT_LIKE,
Operator.NOT_ILIKE,
}:
return {
OrFilter(
frozenset({filter_, replace(null_filter, operator=Operator.IS_NULL)})
)
}
if filter_.operator in {Operator.EQUALS, Operator.NOT_EQUALS}:
return {null_filter} if filter_.value is None else {filter_}
if filter_.operator not in {Operator.IN, Operator.NOT_IN}:
Expand All @@ -1078,6 +1088,16 @@ def _normalize_membership_filter(filter_: Filter) -> set[FilterExpression]:
if not values:
return {replace(filter_, value=values)}
if None not in values:
# User exclusions keep unselected NULL rows, like ordinary datasets.
# Keep SDK NOT_IN leaf semantics intact for providers and cache reuse.
if filter_.operator == Operator.NOT_IN:
return {
OrFilter(
frozenset(
{filter_, replace(null_filter, operator=Operator.IS_NULL)}
)
)
}
return {filter_}

non_null_values: frozenset[FilterValues] = values - {None}
Expand Down
2 changes: 1 addition & 1 deletion superset/semantic_layers/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ def result_cache_discriminator(self) -> tuple[str, str] | None:
def get_extra_cache_keys(self, query_obj: QueryObjectDict) -> list[Hashable]:
discriminator: tuple[str, str] | None = self.result_cache_discriminator
# Separate cached pre-normalization results during rolling deployments.
keys: list[Hashable] = [self.metadata_generation, "semantic-null-filters-v1"]
keys: list[Hashable] = [self.metadata_generation, "semantic-null-filters-v2"]
if discriminator is not None:
keys.append(("semantic-result-version", *discriminator))
return keys
Expand Down
4 changes: 2 additions & 2 deletions tests/unit_tests/common/test_query_context_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3307,7 +3307,7 @@ def test_semantic_annotation_generation_versions_sql_parent(
assert old == {
"user_id": 42,
"source_rls": {"7": ["scope"]},
"semantic_filter_protocol": "semantic-null-filters-v1",
"semantic_filter_protocol": "semantic-null-filters-v2",
"source_versions": {"7": view.metadata_generation},
}
assert new != old
Expand Down Expand Up @@ -3516,7 +3516,7 @@ def payload(context: QueryContext, **kwargs: Any) -> dict[str, Any]:
assert current_key != legacy_key
assert context == {
**legacy_context,
"semantic_filter_protocol": "semantic-null-filters-v1",
"semantic_filter_protocol": "semantic-null-filters-v2",
"source_versions": {"7": view.metadata_generation},
}

Expand Down
94 changes: 93 additions & 1 deletion tests/unit_tests/semantic_layers/cache_or_filters_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@
SemanticCacheState,
)
from superset.semantic_layers.cache_identity import SemanticCacheIdentityFactory
from superset.semantic_layers.cache_policy import ContainmentCapabilities
from superset.semantic_layers.cache_policy import (
ContainmentCapabilities,
PatternSemantics,
)
from superset.semantic_layers.cache_repository import SemanticCacheRepository
from superset.semantic_layers.mapper import _convert_query_object_filter
from tests.unit_tests.semantic_layers.cache_repository_test import (
_Backend,
_Coordinator,
Expand Down Expand Up @@ -88,6 +92,94 @@ def test_group_identity_is_order_independent_and_not_flattened() -> None:
assert ":v5:" in identity


@pytest.mark.parametrize(
"operator,value",
[
("NOT IN", frozenset({"GB"})),
("!=", "GB"),
("NOT LIKE", "G%"),
("NOT ILIKE", "g%"),
],
)
def test_user_exclusion_cannot_reuse_old_null_dropping_results(
operator: str,
value: FilterValues | frozenset[FilterValues],
) -> None:
"""Normalized user exclusion is distinct from its NULL-dropping SDK leaf."""
query: SemanticQuery = build_semantic_query()
leaf: Filter = Filter(
PredicateType.WHERE, query.dimensions[0], Operator(operator), value
)
old: SemanticQuery = replace(query, filters={leaf})
normalized: set[FilterExpression] | None = _convert_query_object_filter(
{
"col": query.dimensions[0].name,
"op": operator,
"val": list(value) if isinstance(value, frozenset) else value,
},
{query.dimensions[0].name: query.dimensions[0]},
)
requested: SemanticQuery = replace(query, filters=normalized)
assert SemanticCacheIdentityFactory.query(
old
) != SemanticCacheIdentityFactory.query(requested)
result: SemanticResult = SemanticResult(
requests=[], results=pa.table({"Country": ["US"], "Revenue": [42.0]})
)
stored: SemanticQuery
lookup: SemanticQuery
for stored, lookup in ((old, requested), (requested, old)):
repository: SemanticCacheRepository = SemanticCacheRepository(
_Backend(), _Coordinator()
)
assert repository.store(build_view_meta(), stored, result)
assert not repository.lookup(
build_view_meta(),
lookup,
ContainmentCapabilities(comparisons=True, membership=True, nulls=True),
).candidates


@pytest.mark.parametrize("operator", ["NOT LIKE", "NOT ILIKE", "!="])
def test_negated_group_reuse_requires_exact_pattern(operator: str) -> None:
"""A broader pattern must not become a cache containment or leftover filter."""
query: SemanticQuery = build_semantic_query()
dimension_name: str = query.dimensions[0].name
queries: list[SemanticQuery] = [
replace(
query,
filters=_convert_query_object_filter(
{"col": dimension_name, "op": operator, "val": pattern},
{dimension_name: query.dimensions[0]},
),
)
for pattern in ("G%", "GB%")
]
result: SemanticResult = SemanticResult(
requests=[], results=pa.table({"Country": [None, "US"], "Revenue": [7.0, 42.0]})
)
stored: SemanticQuery
lookup: SemanticQuery
for stored, lookup in (queries, list(reversed(queries))):
repository: SemanticCacheRepository = SemanticCacheRepository(
_Backend(), _Coordinator()
)
assert repository.store(build_view_meta(), stored, result)
capabilities: ContainmentCapabilities = ContainmentCapabilities(
comparisons=True,
membership=True,
nulls=True,
pattern_semantics=PatternSemantics.sql_like(escape="\\"),
)
assert repository.lookup(build_view_meta(), stored, capabilities).candidates
assert (
not repository.lookup(build_view_meta(), stored, capabilities)
.candidates[0]
.decision.leftover_filters
)
assert not repository.lookup(build_view_meta(), lookup, capabilities).candidates


@pytest.mark.parametrize("location", ["query", "group_limit", "both"])
def test_grouped_query_is_stored_and_served_without_cache_failures(
location: str,
Expand Down
6 changes: 3 additions & 3 deletions tests/unit_tests/semantic_layers/execution_context_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ def test_connection_credentials_keys_unchanged(
"col_values:eb5d43a7322c2a03556fc53bc62d54fbbe0b3d26d561d18a0e385c7457abd822",
# Compatibility identity includes changed_on="None" for this view.
"compatible:a2e526c4cd1db4f68fd34cc7dffe06cc4fbd029975f2147b4b11bb55179795b8",
# Recorded on master ffee0a843f: #45133 adds semantic-null-filters-v1
# to chart keys; the execution-context contract adds no discriminator.
"80b906df8cf7f4837b95d21c32c6f71bd6c810fcf7c1896dbeca74a5023ea961",
# NULL-preserving exclusions use semantic-null-filters-v2 in chart keys;
# the execution-context contract adds no discriminator.
"0b34147df459869c54682b7f1c9f65ea642ee8b746193352ed2322e75c318575",
]


Expand Down
51 changes: 43 additions & 8 deletions tests/unit_tests/semantic_layers/mapper_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
Metric,
Operator,
OrderDirection,
OrFilter,
PredicateType,
SemanticQuery,
SemanticRequest,
Expand Down Expand Up @@ -443,6 +444,9 @@ def test_get_filters_from_extras_rejects_sql(extras: dict[str, str]) -> None:
[
{"where": "customer_id > 100"},
{"having": "SUM(sales) > 1000"},
{"having": "SUM(sales) != 1000"},
{"having": "MAX(category) NOT LIKE 'a%'"},
{"having": "MAX(category) NOT ILIKE 'A%'"},
{"where": "region = 'US'", "having": "COUNT(*) > 10"},
],
)
Expand Down Expand Up @@ -620,6 +624,20 @@ def test_convert_query_object_filter_ilike(
assert result is not None
assert len(result) == 1
converted: FilterExpression = next(iter(result))
if expected == Operator.NOT_ILIKE:
assert isinstance(converted, OrFilter)
assert (
Filter(
PredicateType.WHERE,
all_dimensions["category"],
Operator.IS_NULL,
None,
)
in converted.filters
)
converted = next(
leaf for leaf in converted.filters if leaf.operator == expected
)
assert isinstance(converted, Filter)
assert converted.operator == expected
assert converted.column == all_dimensions["category"]
Expand Down Expand Up @@ -1996,14 +2014,31 @@ def test_convert_query_object_filter(

result = _convert_query_object_filter(filter_, all_dimensions)

assert result == {
Filter(
type=PredicateType.WHERE,
column=all_dimensions["category"],
operator=expected_operator,
value="Electronics",
)
}
expected: Filter = Filter(
type=PredicateType.WHERE,
column=all_dimensions["category"],
operator=expected_operator,
value="Electronics",
)
assert result == (
{
OrFilter(
frozenset(
{
expected,
Filter(
PredicateType.WHERE,
all_dimensions["category"],
Operator.IS_NULL,
None,
),
}
)
)
}
if filter_op == "!="
else {expected}
)


def test_convert_query_object_filter_like() -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def test_metadata_aliases_share_result_cache(
web_context.datasource.metadata_generation
)
assert (
"semantic-null-filters-v1"
"semantic-null-filters-v2"
in web_context.datasource.get_extra_cache_keys({})
)

Expand Down
Loading
Loading