This is an automated email from the ASF dual-hosted git repository.

gabotorresruiz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new 4ac8bfe29f0 fix(semantic-layer): avoid truncating cached rollups 
(#46022)
4ac8bfe29f0 is described below

commit 4ac8bfe29f0399752197f489979d41f6b46c2f9b
Author: Mike Bridge <[email protected]>
AuthorDate: Thu Nov 12 17:57:21 2026 -0600

    fix(semantic-layer): avoid truncating cached rollups (#46022)
---
 UPDATING.md                                        |   7 +
 .../extensions/extension-points/semantic-layers.md |   8 +
 .../semantic-layer-provider-testing.md             |   7 +-
 .../src/superset_core/semantic_layers/types.py     |  20 +-
 .../src/superset_core/semantic_layers/view.py      |   3 +-
 superset/semantic_layers/cache.py                  |   4 +
 superset/semantic_layers/cache_policy.py           |   9 +-
 superset/semantic_layers/cache_transform.py        |  21 +-
 .../semantic_layers/default_order_test.py          | 222 +++++++++++++++++++--
 9 files changed, 267 insertions(+), 34 deletions(-)

diff --git a/UPDATING.md b/UPDATING.md
index f7e7e0d03be..c7486c0121c 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,13 @@ assists people when migrating to a new version.
 
 ## Next
 
+- Semantic cache rollups serve limited queries only when the post-filter,
+  rolled-up result fits within the limit. Queries with nonzero row offsets 
bypass
+  containment reuse. Larger rolled-up results fall back to
+  the provider, preserving page membership when NULL placement, tie order or
+  collation differs from the cache's local sort. NULL placement and tie order
+  remain provider-defined; no provider update or cache reset is required.
+
 - Snowflake default catalogs from unquoted connection-URI identifiers resolve 
to
   uppercase (`sales` becomes `SALES`); double-quoted identifiers preserve case.
   Resolved defaults and catalogs selected from listings are quoted when opening
diff --git a/docs/developer_docs/extensions/extension-points/semantic-layers.md 
b/docs/developer_docs/extensions/extension-points/semantic-layers.md
index 1e3bbd7ddcb..1efbfb583e9 100644
--- a/docs/developer_docs/extensions/extension-points/semantic-layers.md
+++ b/docs/developer_docs/extensions/extension-points/semantic-layers.md
@@ -492,6 +492,13 @@ and missing or invalid coordination each disable only 
containment, log a fixed
 warning without configuration or query content, and leave provider execution
 available.
 
+The host will not cut a rolled-up cache result to satisfy a limit: when the
+rolled-up row count exceeds the limit, it requests the provider's page.
+Reusing an exact cached match or projecting the requested columns from a cached
+superset preserves the provider's stored row order. Queries with a nonzero row
+offset bypass containment reuse and run against the provider; a local sort 
cannot
+preserve which leading rows the provider would skip.
+
 Roll out to a canary worker cohort after recording provider latency, error 
rate,
 and cache-backend health for a comparable baseline. Observe at least one normal
 traffic cycle. Alert ownership should sit with the semantic-platform operator.
@@ -500,6 +507,7 @@ Track `semantic_cache.containment.enabled`, 
`semantic_cache.containment.hit`,
 `semantic_cache.containment.store_skipped`, 
`semantic_cache.containment.store_failure`,
 `semantic_cache.containment.lookup_failure`, 
`semantic_cache.containment.transform_failure`,
 `semantic_cache.containment.prune_failure`, 
`semantic_cache.containment.fence_reject`,
+`semantic_cache.containment.rollup_refused`,
 `semantic_cache.containment.coordination_failure`,
 `semantic_cache.containment.unsupported`, and 
`semantic_cache.containment.invalid_configuration`.
 Alert on the `semantic_cache.containment.store_failure`,
diff --git a/docs/developer_docs/semantic-layer-provider-testing.md 
b/docs/developer_docs/semantic-layer-provider-testing.md
index 34bf85d9ab1..4f885670b20 100644
--- a/docs/developer_docs/semantic-layer-provider-testing.md
+++ b/docs/developer_docs/semantic-layer-provider-testing.md
@@ -90,9 +90,10 @@ Render the empty selection as a constant or an equivalent 
native predicate, neve
 as an empty SQL list; SQLite accepts `IN ()`, so the example cannot catch a
 dialect that rejects it, and provider renderer tests should pin that instead.
 Multi-row query and capability cases must supply explicit order keys that 
totally
-order the expected rows, without ties. Do not rely on where NULLs sort unless 
the
-provider defines that behavior; the example orders nullable groups by their
-non-null, distinct metric values.
+order the expected rows, without ties. NULL placement and the order of rows 
tied
+on every key are provider-defined; the SDK imposes no NULLS FIRST/LAST rule.
+The example orders nullable groups by their non-null, distinct metric values.
+For host cache reuse policy, see [semantic-layer 
containment](extensions/extension-points/semantic-layers.md#semantic-result-containment-caching).
 
 The catalog check detects duplicate metric names, duplicate dimension 
name/grain
 pairs, metric/dimension name collisions, and unstable selection names across
diff --git a/superset-core/src/superset_core/semantic_layers/types.py 
b/superset-core/src/superset_core/semantic_layers/types.py
index 031a2b756f0..fddc155c528 100644
--- a/superset-core/src/superset_core/semantic_layers/types.py
+++ b/superset-core/src/superset_core/semantic_layers/types.py
@@ -380,20 +380,22 @@ class SemanticQuery:
     Truncating first and sorting the truncated page returns a different, and
     wrong, answer. ``order`` entries are ``(member, direction)`` pairs whose
     member must be defined by the view; an adhoc expression is only a valid
-    order key for a view declaring ``ADHOC_EXPRESSIONS_IN_ORDERBY``.
+    order key for a view declaring ``ADHOC_EXPRESSIONS_IN_ORDERBY``. NULL 
placement
+    and the order of rows tied on every order key are provider-defined.
 
     **Default chronological order.** When ``order`` is empty (``None`` or
     ``[]``) and ``dimensions`` includes a date, timestamp or time dimension, 
the
     host sorts ascending by the first such dimension in ``dimensions`` (by list
     position, not ``SemanticView.preferred_temporal_dimension``), before
-    ``offset`` and ``limit``. Rows that tie on it come back in no particular
-    order, and where its NULL values sort is not specified. The host applies
-    this both to the ``get_table`` query it sends the provider and to results 
it
-    serves from its cache. It is a default, never a prefix: a non-empty
-    ``order`` is used exactly as given. A ``get_table`` call therefore receives
-    an empty ``order`` only when no temporal dimension is selected, and may 
then
-    return rows in any order. ``get_row_count`` gets no default, since order
-    cannot change a count.
+    ``offset`` and ``limit``. The SDK does not specify NULL placement or tie
+    order; a provider's placement is kept as returned, and a cache-served 
rollup
+    keeps the provider's rows but may order NULL and tied rows differently.
+    The host applies this default both to the ``get_table`` query it sends the
+    provider and to results it serves from its cache. It is a default, never a
+    prefix: a non-empty ``order`` is used exactly as given. A ``get_table`` 
call
+    therefore receives an empty ``order`` only when no temporal dimension is
+    selected, and may then return rows in any order. ``get_row_count`` gets no
+    default, since order cannot change a count.
 
     ``group_limit`` is a separate ranking, with its own metric, direction and
     optional filters.
diff --git a/superset-core/src/superset_core/semantic_layers/view.py 
b/superset-core/src/superset_core/semantic_layers/view.py
index 0b84a67b468..6b064428291 100644
--- a/superset-core/src/superset_core/semantic_layers/view.py
+++ b/superset-core/src/superset_core/semantic_layers/view.py
@@ -174,7 +174,8 @@ class SemanticView(ABC):
 
         Sort by ``query.order`` before applying ``query.offset`` and
         ``query.limit``; truncating before sorting returns the wrong rows. Name
-        each result column after the member that produced it.
+        each result column after the member that produced it. NULL placement 
and
+        the order of rows tied on every order key are provider-defined.
 
         Raise 
``superset_core.semantic_layers.errors.SemanticResultCompletenessError``
         when the result is incomplete or its completeness cannot be verified;
diff --git a/superset/semantic_layers/cache.py 
b/superset/semantic_layers/cache.py
index 01b2c345451..dac289964d4 100644
--- a/superset/semantic_layers/cache.py
+++ b/superset/semantic_layers/cache.py
@@ -58,6 +58,7 @@ from superset.semantic_layers.cache_repository import (
     ViewMeta,
 )
 from superset.semantic_layers.cache_transform import (
+    SemanticCacheRollupRefusedError,
     SemanticCacheTransformationError,
     transform_result,
 )
@@ -352,6 +353,9 @@ class SemanticCacheService:
                     candidate.decision,
                     capabilities,
                 )
+            except SemanticCacheRollupRefusedError:
+                self._increment("rollup_refused")
+                continue
             except SemanticCacheTransformationError:
                 self._increment("transform_failure")
                 continue
diff --git a/superset/semantic_layers/cache_policy.py 
b/superset/semantic_layers/cache_policy.py
index 4609aad150a..b65ad4a11fd 100644
--- a/superset/semantic_layers/cache_policy.py
+++ b/superset/semantic_layers/cache_policy.py
@@ -345,7 +345,11 @@ def select_reuse(
     entry: CachedEntry,
     capabilities: ContainmentCapabilities,
 ) -> ReuseDecision | None:
-    """Prove whether and how a cached descriptor can satisfy a query."""
+    """Prove descriptor compatibility; transformation checks rollup row bounds.
+
+    Descriptors do not contain the post-filter, post-rollup cardinality needed
+    to prove that a limited result can be served without cutting rows.
+    """
     # Compare the order the rows were cut by, defaults included: two unordered
     # queries can default to different temporal dimensions.
     order_compatible: bool = (
@@ -373,7 +377,8 @@ def select_reuse(
         return None
     # EXACT and PROJECT keep the cached row order. A rollup comes from an
     # unlimited entry and is re-sorted by the default order, so the order the
-    # entry was stored in does not matter.
+    # entry was stored in does not matter. The transform must refuse a limited
+    # rollup if it would cut rows under provider-defined NULL/tie ordering.
     if mode is not ReuseMode.ROLLUP and not order_compatible:
         return None
     if mode is ReuseMode.ROLLUP and query.order:
diff --git a/superset/semantic_layers/cache_transform.py 
b/superset/semantic_layers/cache_transform.py
index 8044ffb739d..8e23441490f 100644
--- a/superset/semantic_layers/cache_transform.py
+++ b/superset/semantic_layers/cache_transform.py
@@ -77,6 +77,10 @@ class SemanticCacheTransformationError(RuntimeError):
     """Cached data cannot safely satisfy an otherwise eligible query."""
 
 
+class SemanticCacheRollupRefusedError(SemanticCacheTransformationError):
+    """A valid rollup cannot preserve the provider's limited page 
membership."""
+
+
 def _comparison_mask(
     series: pd.Series, operator: Operator, value: object
 ) -> pd.Series | None:
@@ -214,9 +218,8 @@ def _rollup(frame: pd.DataFrame, query: SemanticQuery) -> 
pd.DataFrame:
 def _sort_by_default_order(frame: pd.DataFrame, query: SemanticQuery) -> 
pd.DataFrame:
     """Restore the default order a rollup's grouping replaced, before the 
limit.
 
-    NULL values of the default column sort last. The SDK leaves NULL placement
-    unspecified, so on an engine that sorts NULLs first a limited rollup and a
-    provider miss may keep different rows.
+    NULL placement and tie order can differ from the provider. Limited rollups
+    are accepted only when this local order cannot cut rows from the result.
     """
     dimension: Dimension | None = default_order_dimension(query)
     if dimension is None:
@@ -261,10 +264,20 @@ def transform_result(
             table: pa.Table = result.results.select(columns).slice(offset, 
length)
             return SemanticResult(requests=result.requests, results=table)
 
+        if decision.mode is ReuseMode.ROLLUP and query.offset:
+            raise SemanticCacheRollupRefusedError(
+                "A rollup cannot preserve provider-defined row offsets"
+            )
+
         frame: pd.DataFrame = 
result.results.to_pandas(types_mapper=_pandas_dtype)
         frame = _apply_leftovers(frame, decision.leftover_filters, 
capabilities)
         if decision.mode is ReuseMode.ROLLUP:
-            frame = _sort_by_default_order(_rollup(frame, query), query)
+            frame = _rollup(frame, query)
+            if query.limit is not None and len(frame) > query.limit:
+                raise SemanticCacheRollupRefusedError(
+                    "A limited rollup cannot choose rows using 
provider-defined order"
+                )
+            frame = _sort_by_default_order(frame, query)
         frame = _project(frame, query)
         frame = _slice(frame, query)
         return SemanticResult(
diff --git a/tests/unit_tests/semantic_layers/default_order_test.py 
b/tests/unit_tests/semantic_layers/default_order_test.py
index 94a85770762..50a7f96c5db 100644
--- a/tests/unit_tests/semantic_layers/default_order_test.py
+++ b/tests/unit_tests/semantic_layers/default_order_test.py
@@ -20,7 +20,7 @@
 from collections.abc import Callable
 from dataclasses import replace
 from datetime import date, datetime
-from unittest.mock import Mock
+from unittest.mock import call, Mock
 
 import pyarrow as pa
 import pytest
@@ -36,13 +36,22 @@ from superset_core.semantic_layers.types import (
 )
 
 from superset.semantic_layers import mapper
-from superset.semantic_layers.cache import SemanticCacheOutcome
+from superset.semantic_layers.cache import (
+    SemanticCacheOutcome,
+    SemanticCacheService,
+    SemanticCacheState,
+)
 from superset.semantic_layers.cache_policy import ContainmentCapabilities
 from superset.semantic_layers.cache_repository import SemanticCacheRepository
-from superset.semantic_layers.cache_transform import transform_result
+from superset.semantic_layers.cache_transform import (
+    SemanticCacheRollupRefusedError,
+    SemanticCacheTransformationError,
+    transform_result,
+)
 from superset.semantic_layers.cache_types import (
     CachedEntry,
     CachedResultCandidate,
+    ReuseDecision,
     ReuseMode,
     SemanticCacheLookupResult,
 )
@@ -156,8 +165,8 @@ def test_row_count_dispatch_bypasses_the_cache(mocker: 
MockerFixture) -> None:
         "build_cache_configuration",
         return_value=(mocker.Mock(), mocker.Mock()),
     )
-    service.execute_provider.side_effect = lambda query, dispatch: (
-        SemanticCacheOutcome(dispatch(query), cache_hit=False)
+    service.execute_provider.side_effect = lambda query, dispatch: 
SemanticCacheOutcome(
+        dispatch(query), cache_hit=False
     )
     provider: Mock = mocker.Mock(return_value=EMPTY_RESULT)
     query: SemanticQuery = SemanticQuery(metrics=[SALES], 
dimensions=[ORDER_DATE])
@@ -225,14 +234,17 @@ def _serve_from_cache(
     if not lookup.candidates:
         return None
     candidate: CachedResultCandidate = lookup.candidates[0]
-    served: SemanticResult = transform_result(
-        candidate.result, query, candidate.decision, ContainmentCapabilities()
-    )
+    try:
+        served: SemanticResult = transform_result(
+            candidate.result, query, candidate.decision, 
ContainmentCapabilities()
+        )
+    except SemanticCacheTransformationError:
+        return None
     return served.results.to_pydict()
 
 
-def test_rollup_hit_applies_the_default_order_before_the_limit() -> None:
-    """A rolled-up hit returns the earliest rows overall, as the provider 
would."""
+def test_rollup_that_would_cut_rows_is_not_served_from_cache() -> None:
+    """A local chronological sort cannot prove the provider's page 
membership."""
     stored_query: SemanticQuery = SemanticQuery(
         metrics=[SUMMED_SALES], dimensions=[REGION, PRODUCT, ORDER_DATE]
     )
@@ -253,11 +265,7 @@ def 
test_rollup_hit_applies_the_default_order_before_the_limit() -> None:
         metrics=[SUMMED_SALES], dimensions=[REGION, ORDER_DATE], limit=2
     )
 
-    assert _serve_from_cache(stored_query, stored_rows, query) == {
-        "region": ["West", "East"],
-        "order_date": [date(2026, 1, 1), date(2026, 1, 2)],
-        "total_sales": [5.0, 2.0],
-    }
+    assert _serve_from_cache(stored_query, stored_rows, query) is None
 
 
 def test_limited_hit_is_not_reused_under_a_different_default_order() -> None:
@@ -374,3 +382,187 @@ def 
test_store_replaces_a_descriptor_written_without_the_default_order() -> None
     assert [candidate.decision.mode for candidate in lookup.candidates] == [
         ReuseMode.EXACT
     ]
+
+
[email protected]("case", ["null_first", "split_tie"])
+def test_limited_rollup_defers_to_provider_when_page_membership_can_differ(
+    case: str,
+) -> None:
+    """A local sort must not choose a different limited page from the 
provider."""
+    repository: SemanticCacheRepository = SemanticCacheRepository(
+        _MemoryBackend(),
+        _InlineCoordinator(),
+        clock=lambda: 10.0,
+    )
+    stored_query: SemanticQuery = SemanticQuery(
+        [SUMMED_SALES],
+        [REGION, PRODUCT, ORDER_DATE],
+    )
+    query: SemanticQuery = SemanticQuery([SUMMED_SALES], [REGION, ORDER_DATE], 
limit=1)
+    if case == "null_first":
+        stored_rows: dict[str, list[object]] = {
+            "region": ["West", "East", "East"],
+            "product": ["p1", "p1", "p2"],
+            "order_date": [None, date(2026, 1, 1), date(2026, 1, 2)],
+            "total_sales": [5.0, 1.0, 2.0],
+        }
+        provider_rows: dict[str, list[object]] = {
+            "region": ["West"],
+            "order_date": [None],
+            "total_sales": [5.0],
+        }
+    else:
+        stored_rows = {
+            "region": ["Zulu", "Alpha", "Zulu"],
+            "product": ["p1", "p1", "p2"],
+            "order_date": [date(2026, 1, 1)] * 3,
+            "total_sales": [2.0, 7.0, 3.0],
+        }
+        provider_rows = {
+            "region": ["Zulu"],
+            "order_date": [date(2026, 1, 1)],
+            "total_sales": [5.0],
+        }
+    source_schema: pa.Schema = pa.schema(
+        [
+            *(pa.field(d.name, d.type) for d in stored_query.dimensions),
+            pa.field(SUMMED_SALES.name, SUMMED_SALES.type),
+        ]
+    )
+    requested_schema: pa.Schema = pa.schema(
+        [
+            *(pa.field(d.name, d.type) for d in query.dimensions),
+            pa.field(SUMMED_SALES.name, SUMMED_SALES.type),
+        ]
+    )
+    repository.store(
+        build_view_meta(),
+        stored_query,
+        SemanticResult(
+            requests=[],
+            results=pa.Table.from_pydict(stored_rows, schema=source_schema),
+        ),
+    )
+    candidates: SemanticCacheLookupResult = repository.lookup(
+        build_view_meta(),
+        query,
+        ContainmentCapabilities(),
+    )
+    assert candidates.candidates[0].decision.mode is ReuseMode.ROLLUP
+    result: SemanticResult = SemanticResult(
+        requests=[],
+        results=pa.Table.from_pydict(provider_rows, schema=requested_schema),
+    )
+    provider: Mock = Mock(return_value=result)
+    metrics: Mock = Mock()
+    service: SemanticCacheService = SemanticCacheService(
+        SemanticCacheState.enabled(),
+        repository,
+        metrics,
+    )
+    outcome: SemanticCacheOutcome = service.execute(
+        build_view_meta(),
+        query,
+        provider,
+        capabilities=ContainmentCapabilities(),
+    )
+    assert outcome.result.results.equals(result.results)
+    assert outcome.cache_hit is False
+    provider.assert_called_once_with(query)
+    metrics.incr.assert_any_call("semantic_cache.containment.rollup_refused")
+    metrics.incr.assert_any_call("semantic_cache.containment.miss")
+    assert all(
+        call.args != ("semantic_cache.containment.transform_failure",)
+        for call in metrics.incr.call_args_list
+    )
+    cached: SemanticCacheOutcome = service.execute(
+        build_view_meta(),
+        query,
+        provider,
+        capabilities=ContainmentCapabilities(),
+    )
+    assert cached.cache_hit is True
+    assert metrics.incr.call_args_list == [
+        call("semantic_cache.containment.rollup_refused"),
+        call("semantic_cache.containment.miss"),
+        call("semantic_cache.containment.hit"),
+    ]
+    assert cached.result.results.equals(result.results)
+    provider.assert_called_once_with(query)
+
+
[email protected]("limit", [None, 2, 3])
[email protected]("kind", ["dates", "null_time", "ties"])
+def test_complete_rollup_remains_reusable_with_a_fitting_limit(
+    limit: int | None,
+    kind: str,
+) -> None:
+    """The row bound uses actual groups, not the larger cached input count."""
+    stored_query: SemanticQuery = SemanticQuery(
+        [SUMMED_SALES],
+        [REGION, PRODUCT, ORDER_DATE],
+    )
+    stored_rows: dict[str, list[object]] = {
+        "region": ["East", "East", "West", "West"],
+        "product": ["p1", "p2", "p1", "p2"],
+        "order_date": [
+            date(2026, 1, 1),
+            date(2026, 1, 1),
+            date(2026, 1, 2),
+            date(2026, 1, 2),
+        ],
+        "total_sales": [1.0, 2.0, 3.0, 4.0],
+    }
+    expected: dict[str, list[object]] = {
+        "region": ["East", "West"],
+        "order_date": [date(2026, 1, 1), date(2026, 1, 2)],
+        "total_sales": [3.0, 7.0],
+    }
+    if kind == "null_time":
+        stored_rows["order_date"] = [None, None, date(2026, 1, 2), date(2026, 
1, 2)]
+        expected = {
+            "region": ["West", "East"],
+            "order_date": [date(2026, 1, 2), None],
+            "total_sales": [7.0, 3.0],
+        }
+    elif kind == "ties":
+        stored_rows["order_date"] = [
+            date(2026, 1, 1),
+            date(2026, 1, 1),
+            date(2026, 1, 1),
+            date(2026, 1, 1),
+        ]
+        expected["order_date"] = [date(2026, 1, 1), date(2026, 1, 1)]
+    query: SemanticQuery = SemanticQuery(
+        [SUMMED_SALES],
+        [REGION, ORDER_DATE],
+        limit=limit,
+    )
+    assert _serve_from_cache(stored_query, stored_rows, query) == expected
+
+
[email protected]("limit", [None, 2])
+def test_rollup_with_offset_is_refused_even_when_all_groups_fit(
+    limit: int | None,
+) -> None:
+    """A local sort cannot decide which provider rows an offset skips."""
+    query: SemanticQuery = SemanticQuery(
+        [SUMMED_SALES], [ORDER_DATE], offset=1, limit=limit
+    )
+    result: SemanticResult = SemanticResult(
+        requests=[],
+        results=pa.table(
+            {
+                "order_date": pa.array([None, date(2026, 1, 1)], pa.date32()),
+                "product": ["p1", "p2"],
+                "total_sales": [1.0, 2.0],
+            }
+        ),
+    )
+    with pytest.raises(SemanticCacheRollupRefusedError):
+        transform_result(
+            result,
+            query,
+            ReuseDecision(ReuseMode.ROLLUP, frozenset()),
+            ContainmentCapabilities(),
+        )

Reply via email to