You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "mikebridge (via GitHub)" <gi...@apache.org> on 2026/08/04 21:00:50 UTC

[PR] feat(semantic-layers): add safe containment result cache [superset]

mikebridge opened a new pull request, #42760:
URL: https://github.com/apache/superset/pull/42760

   Title: `feat(semantic-layers): add safe containment result cache`
   
   ### SUMMARY
   
   Adds an experimental, default-off containment cache for semantic-layer results.
   Superset can reuse exact, projected, filtered, or additive-rollup results only when
   the provider explicitly delegates cache responsibility and declares compatible
   semantics. Identities include the semantic definition, provider material, and
   either a global declaration or typed request security context.
   
   The implementation replaces the original monolithic cache with separate identity,
   proof-policy, transformation, repository, coordination, host-adapter, and
   application-service boundaries. Descriptor mutation uses bounded Redis owner-token
   leases; expected cache failures fall back to the provider, while transformation or
   programming defects remain visible. Forced queries bypass reads but store successful
   fresh output under the canonical non-force identity. Responses and the chart cache
   pill distinguish semantic containment hits from ordinary result-cache hits.
   
   | Superseded PR | Contribution retained here |
   |---|---|
   | #40221 | Core containment proofs, transformation, result propagation, and UI indicator (Beto attribution retained) |
   | #41824 | Owner-safe descriptor mutation and concurrency regressions |
   | #41825 | `force_query` excluded from ordinary result identity |
   | #41826 | Successful forced refresh stored after read bypass |
   | #41856 | SQL NULL semantics and complete correctness coverage |
   
   Shortcut: SC-106828. The old PRs should remain open until this replacement is
   created and its supersession plan is explicitly approved.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   The existing cached pill remains visually unchanged. Its tooltip says “semantic
   query result” for containment hits and “query result” for ordinary cache hits.
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   pytest --cov=superset/semantic_layers/ --cov-branch --cov-fail-under=100 \
     tests/unit_tests/semantic_layers/ -q
   pytest -q tests/unit_tests/queries/query_object_test.py \
     tests/unit_tests/utils/test_cache_manager.py \
     tests/unit_tests/async_events/test_cache_backend.py \
     tests/unit_tests/config_test.py tests/unit_tests/initialization_test.py
   ```
   
   Run the focused CachedLabel and ChartPills Jest tests, frontend type checking,
   targeted Python/frontend pre-commit hooks, and `pre-commit run --all-files` as
   recorded in the linked verification artifact. The dedicated CI job also exercises
   pinned Redis and Sentinel services with expiry, stale-release, concurrent writer,
   prune/store, parity, descriptor-bound, and lock-free healthy-read assertions.
   
   Rollout requires both `SEMANTIC_LAYERS` and
   `SEMANTIC_LAYER_CONTAINMENT_CACHE`, plus supported distributed coordination.
   Canary one worker cohort after capturing latency/error/cache-health baselines and
   observe one normal traffic cycle. Roll back by disabling the dedicated flag and
   restarting every web/worker process; confirm an enabled gauge of zero and normal
   provider success.
   
   ### ADDITIONAL INFORMATION
   
   - [x] Has associated issue: Shortcut SC-106828
   - [x] Required feature flags: `SEMANTIC_LAYERS`, `SEMANTIC_LAYER_CONTAINMENT_CACHE`
   - [x] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4032855081


##########
superset/charts/data/api.py:
##########
@@ -575,6 +575,9 @@ def _process_data(query_data: Any) -> Any:
                 )
             resp = make_response(response_data, 200)
             resp.headers["Content-Type"] = "application/json; charset=utf-8"
+            resp.headers["X-Superset-Semantic-Cache"] = SemanticCacheStatus.combine(

Review Comment:
   For `result_type=results`, query-actions reduces each payload to its results whitelist and drops `semantic_cache_status`; this new header therefore combines only `None` values and reports `MISS` even when containment served the query. Could the results payload retain the status before computing the header?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5447448059

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4009553027


##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()

Review Comment:
   addressed in ab42028cf9 — the descriptor/value commit is now fenced by the owner token. A `compare_owner_and_set` Lua primitive on `RedisCommandsMixin` rejects the SET unless the lease key still holds the caller's token; it runs only when the value store and the lease share the exact same Redis client, and separate clients fall back to a documented, non-atomic immediate ownership recheck before the SET. A paused writer whose lease was taken over mid-operation now has its SET rejected, so the fresher payload and its descriptor/TTL survive (test: `test_same_client_fence_rejects_paused_writer`).
   
   *Posted by Claude (AI) on behalf of @mikebridge.*



##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()
+        finally:
+            renewal_stopped.set()
+            renewal_thread.join()
+        return renewal_failed.is_set()
+
+    def mutate(self, key: str, operation: Callable[[], None]) -> bool:
+        """Acquire a bounded lease, mutate, and release only our ownership."""
+        lease_key: str = f"semantic-cache-lock:{key}"
+        owner_token: str = self._token_factory()
+        deadline: float = self._clock() + self._settings.wait_seconds
+        acquired: bool = False
+        while True:
+            try:
+                acquired = self._backend.acquire_owner_token(

Review Comment:
   addressed in ab42028cf9 — coordination Redis I/O is now bounded. A private coordination client is constructed with socket/connect timeouts derived from `SEMANTIC_CACHE_COORDINATION_WAIT_SECONDS` (1 ms floor) and retry/backoff disabled, leaving the shared data-cache client untouched. A hung store/refresh/release is caught as a best-effort failure (coordination_failure + store_failure counters) and the chart still returns the provider result within the bound (test: `test_coordination_timeout_keeps_provider_result`).
   
   *Posted by Claude (AI) on behalf of @mikebridge.*



##########
superset-frontend/src/explore/components/ChartPills.tsx:
##########
@@ -100,12 +100,19 @@ export const ChartPills = forwardRef(
               limit={Number(rowLimit ?? 0)}
             />
           )}
-          {!isLoading && firstQueryResponse?.is_cached && (
-            <CachedLabel
-              onClick={refreshCachedQuery}
-              cachedTimestamp={firstQueryResponse.cached_dttm}
-            />
-          )}
+          {!isLoading &&
+            (firstQueryResponse?.is_cached ||

Review Comment:
   addressed in c25fcfaed6 — provenance now aggregates across every query response: all HIT → HIT, any HIT mixed with a non-HIT → MIXED (shown as "Mixed cache", not a semantic-cache hit), otherwise MISS. The server-paginated data-HIT + row-count-MISS case is pinned in `ChartPills.test.tsx`.
   
   *Posted by Claude (AI) on behalf of @mikebridge.*



##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,99 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants; containment is bypassed for a
+`GLOBAL` view whenever Superset row-level security applies to the request, since
+that variation is invisible to the provider. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag
+`SEMANTIC_LAYER_CONTAINMENT_CACHE`, and configure two backends:
+
+- `DATA_CACHE_CONFIG` holds the cached results and their descriptors. It must be
+  a persistent cache shared by every web and worker process, such as `RedisCache`.
+  The default `NullCache` discards every value, so containment would only ever
+  miss; `RedisSentinelCache` reads from replicas that can lag the master. Both
+  disable containment at startup rather than run it ineffectively.
+- `DISTRIBUTED_COORDINATION_CONFIG` must select `RedisCache` or
+  `RedisSentinelCache`; containment requires its atomic owner-token lease
+  operations.
+
+```python
+DATA_CACHE_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_DEFAULT_TIMEOUT": 86400,
+    "CACHE_KEY_PREFIX": "superset_results",
+    "CACHE_REDIS_URL": "redis://redis:6379/1",
+}
+DISTRIBUTED_COORDINATION_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_REDIS_URL": "redis://redis:6379/2",
+}
+```
+
+Containment follows the same cache timeout the ordinary result cache resolves for
+a request (custom, then chart, then dataset), so a chart-level timeout of `-1`
+bypasses containment entirely, and honors `DATA_CACHE_MAX_VALUE_SIZE`: a result
+larger than that many bytes is served but not stored. The bounded defaults are
+`SEMANTIC_CACHE_COORDINATION_WAIT_SECONDS = 1.0` and
+`SEMANTIC_CACHE_COORDINATION_LEASE_SECONDS = 30`. A missing or unsuitable backend
+and missing or invalid coordination each disable only containment, log a fixed
+warning without configuration or query content, and leave provider execution
+available.
+
+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.
+Track `semantic_cache.containment.enabled` and the fixed-name `hit`, `miss`,

Review Comment:
   addressed in c25fcfaed6 — the rollout guide now lists all twelve emitted counters with their full `semantic_cache.containment.` prefix (enabled, hit, miss, bypass, store_skipped, store_failure, lookup_failure, transform_failure, prune_failure, coordination_failure, unsupported, invalid_configuration) and calls out the failure counters to alert on.
   
   *Posted by Claude (AI) on behalf of @mikebridge.*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5724739463

   Updated in two separate commits for review: master re-sync `75e44b557d6ec531693a045eb46cd9d6ab38b8b3`, then correctness fix `65971b967a12e8c34b3f68f6ff2c5f9c62bdbdfc`.
   
   The review found a monthly cached result could incorrectly answer a partial-month range. The fix rejects narrowing on a cached grained axis, including its raw-column variant; regressions cover partial upper/lower bounds and preserve safe raw-axis containment. Independent re-review approved the fix. Final local verification: 676 semantic-layer tests pass with 100% statement/branch coverage, and the focused changed-file hooks pass.
   
   The update also repairs the generated OpenAPI property, unused MyPy ignore and coverage gaps. Docs clarify binary/codepoint collation assumptions and that atomic fencing is a same-client optimisation; default deployments use the non-atomic immediate ownership recheck. Mapper variant ordering remains a separate [SC-121337](https://app.shortcut.com/preset/story/121337) follow-up. Remaining non-blocking follow-ups are disclosed in the PR body.
   
   `hold!` stays. This is publication for validation, not a merge request: we still need green CI on this exact head, including Redis/Sentinel `test-semantic-cache-coordination` and frontend compilation, plus a flag-on soak with a real opted-in provider exercising concurrent forced refreshes and narrowed ranges against direct-provider answers. Local frontend checking was limited by unbuilt workspace declarations (TS6305); no frontend build or live-provider/Redis soak is claimed here.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4147988858


##########
superset/charts/schemas.py:
##########
@@ -1806,6 +1807,17 @@ class ChartDataResponseResult(Schema):
         required=True,
         allow_none=None,
     )
+    semantic_cache_status: fields.String = fields.String(

Review Comment:
   Good catch—the generated `semantic_cache_status` field is restored in `5e54caab05`, and regeneration leaves the file unchanged. Local generation and focused tests pass; the new OpenAPI CI run on this head should confirm the published artifact.
   



##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()

Review Comment:
   Good catch—the nonce fence described in our earlier reply had gone missing from the branch head; `5e54caab05` restores it. A separate-client takeover probe fails before and passes after, 374 focused tests pass, and the exact tree had an independent review. Would it make sense to keep the rollout hold until live split-store/process-pause and provider-result validation is done? To be precise, this rejects mismatched pairs as misses; it isn't an atomic cross-store write guarantee.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6134301766

   Merged the latest master into this branch at f7595d8872. The mapper resolution preserves both the per-request filter metadata and semantic cache provenance; all changed test fixtures were reviewed for compatibility.
   
   Validation: 1,518 focused Python tests and 47 frontend tests passed. The incoming-file Python run had 2,379 passes and one previously documented local Europe/Dublin timezone failure. Branch-file hooks and the normal pre-push checks, including coverage gates, passed. Codex prepared and validated the merge; an independent Claude review approved the exact committed tree with that documented baseline exception.
   
   GitHub now reports MERGEABLE. CI is still running, and `hold!` remains in place.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5208017567

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3913939766


##########
docs/static/feature-flags.json:
##########
@@ -93,6 +93,12 @@
         "lifecycle": "development",
         "description": "Enable semantic layers and show semantic views alongside datasets"
       },
+      {
+        "name": "SEMANTIC_LAYER_CONTAINMENT_CACHE",

Review Comment:
   Enabling this flag from the Feature Flags page can leave containment silently ineffective unless the operator also configures persistent `DATA_CACHE_CONFIG` and Redis-backed `DISTRIBUTED_COORDINATION_CONFIG`; those prerequisites and the rollback path are only documented in the extension-author guide. Could this entry link to operator-facing cache setup guidance so an administrator can enable it safely?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184621732

   A **containment cache** can reuse a previously cached semantic-query result when that result is proven to contain everything needed to answer a new query. For example, a cached result grouped by country and city may answer a later country-only query by rolling up the cached rows, avoiding another provider query while preserving equivalent results.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184572256

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4033096860


##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,428 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from contextvars import ContextVar
+from dataclasses import dataclass, fields
+from math import ceil
+from time import time
+from typing import cast, Protocol, TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from superset.coordination.cache_backend import RedisCommandsMixin
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class SemanticCacheWriteFence:
+    """Mutation-local lease identity; never shared between concurrent writers."""
+
+    key: str
+    owner_token: str
+    check_owner: Callable[[], bool]
+    redis_backend: RedisCommandsMixin | None = None
+
+
+semantic_cache_write_fence: ContextVar[SemanticCacheWriteFence | None] = ContextVar(
+    "semantic_cache_write_fence", default=None
+)
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def has(self, key: str) -> bool: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _has(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._backend.has(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend has failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            fence: SemanticCacheWriteFence | None = semantic_cache_write_fence.get()
+            persisted: bool | None = None
+            if fence is not None:
+                fenced_set: (
+                    Callable[
+                        [SemanticCacheWriteFence, str, object, int | None], bool | None
+                    ]
+                    | None
+                ) = getattr(self._backend, "set_if_owner", None)
+                if fenced_set is not None:
+                    persisted = fenced_set(fence, key, value, timeout)
+                if persisted is None and not fence.check_owner():
+                    raise SemanticCacheCoordinationError(
+                        "Semantic cache lease ownership was lost"
+                    )
+            if persisted is None:
+                # Non-Redis or separate-client stores cannot atomically check
+                # the lease and SET. Recheck immediately before this best-effort
+                # write; a lease takeover between the two calls remains possible.
+                persisted = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    def _delete(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            self._backend.delete(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend delete failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        # A pickled dataclass restores only the attributes it was written
+        # with, so an entry from an older shape can pass ``isinstance`` and
+        # still lack a field (a class-level default masks that from
+        # ``hasattr``, hence the instance-dict check). Key rotation
+        # (``IDENTITY_FORMAT_VERSION``) is the primary defence; treating such
+        # a bucket as empty is the backstop, so it costs one miss and a
+        # re-store rather than a lookup failure on every request until the
+        # bucket expires.
+        expected: tuple[str, ...] = tuple(field.name for field in fields(CachedEntry))
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry)
+            and all(name in vars(entry) for name in expected)
+            for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+        *,
+        replace: bool = True,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor.
+
+        With ``replace`` false, a value that another request already stored
+        and registered under the same identity is left alone: the identical
+        provider result is already discoverable, and skipping saves this
+        request the lease wait and the payload write. A herd of identical
+        misses then contends for the lease once, not once per request.
+        """
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        now: float = self._clock()
+        if not replace and self._is_registered(bucket_key, value_key, meta, now):
+            return True
+        descriptor: CachedEntry = CachedEntry(
+            filters=frozenset(query.filters or set()),
+            dimensions=frozenset(query.dimensions),
+            metrics=frozenset(query.metrics),
+            limit=query.limit,
+            offset=query.offset or 0,
+            order_key=SemanticCacheIdentityFactory.order(query.order),
+            group_limit_key=SemanticCacheIdentityFactory.group_limit(query.group_limit),
+            value_key=value_key,
+            timestamp=now,
+            timeout=meta.timeout,
+        )
+
+        def register() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheStoreError)
+            )
+            retained: list[CachedEntry] = [
+                entry for entry in entries if entry.value_key != value_key
+            ]
+            retained.append(descriptor)
+            bounded: list[CachedEntry] = sorted(
+                retained,
+                key=lambda entry: entry.timestamp,
+                reverse=True,
+            )[:MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET]
+            bounded_value_keys: set[str] = {entry.value_key for entry in bounded}
+            evicted_value_keys: set[str] = {
+                entry.value_key
+                for entry in retained
+                if entry.value_key not in bounded_value_keys
+            }
+            self._set(
+                bucket_key,
+                bounded,
+                self._bucket_timeout(bounded, meta.timeout, now),
+                SemanticCacheStoreError,
+            )
+            self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+            for evicted_value_key in evicted_value_keys:
+                self._delete(evicted_value_key, SemanticCacheStoreError)
+
+        return self._mutate(bucket_key, register, SemanticCacheStoreError)
+
+    @staticmethod
+    def _serves(entry: CachedEntry, meta: ViewMeta, now: float) -> bool:
+        """Whether a stored value may answer a request with ``meta``'s timeout.
+
+        Requests resolve their own cache timeout, so a value stored by a
+        long-timeout chart can outlive what a short-timeout chart on the same
+        view is allowed to reuse. The value's age is bounded by the requesting
+        timeout (``None`` and ``0`` follow the backend's unbounded conventions),
+        and for the store dedupe the stored TTL must also cover this request,
+        or the longer-lived chart would be pinned to the shorter entry.
+        """
+        if meta.timeout is None or meta.timeout <= 0:
+            return True
+        if now - entry.timestamp > meta.timeout:
+            return False
+        return (
+            entry.timeout is None
+            or entry.timeout <= 0
+            or (entry.timeout >= meta.timeout)
+        )
+
+    def _is_registered(
+        self,
+        bucket_key: str,
+        value_key: str,
+        meta: ViewMeta,
+        now: float,
+    ) -> bool:
+        entries: list[CachedEntry] = self._entries(
+            self._get(bucket_key, SemanticCacheStoreError)
+        )
+        return any(
+            entry.value_key == value_key and self._serves(entry, meta, now)
+            for entry in entries
+        ) and self._has(value_key, SemanticCacheStoreError)
+
+    def lookup(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        capabilities: ContainmentCapabilities,
+    ) -> SemanticCacheLookupResult:
+        """Load ranked values and report missing descriptors without mutation."""
+        bucket_key: str = self._bucket_key(meta)
+        now: float = self._clock()
+        entries: list[CachedEntry] = [
+            entry
+            for entry in self._entries(self._get(bucket_key, SemanticCacheLookupError))
+            if self._serves(entry, meta, now)
+        ]
+        ranked: list[tuple[ReuseDecision, CachedEntry]] = rank_reuse_decisions(
+            query, entries, capabilities
+        )
+        candidates: list[CachedResultCandidate] = []
+        missing_value_keys: set[str] = set()
+        for decision, entry in ranked:
+            value: object | None = self._get(entry.value_key, SemanticCacheLookupError)
+            if not isinstance(value, SemanticResult):
+                missing_value_keys.add(entry.value_key)
+                continue
+            candidates.append(CachedResultCandidate(entry, value, decision))
+            break
+        return SemanticCacheLookupResult(
+            candidates=tuple(candidates),
+            missing_value_keys=frozenset(missing_value_keys),
+        )
+
+    def prune_missing(
+        self,
+        meta: ViewMeta,
+        missing_value_keys: frozenset[str],
+    ) -> None:
+        """Identity-safely remove descriptors whose values remain absent."""
+        if not missing_value_keys:
+            return
+        bucket_key: str = self._bucket_key(meta)
+        now: float = self._clock()
+
+        def prune() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheLookupError)
+            )
+            retained: list[CachedEntry] = [
+                entry
+                for entry in entries
+                if entry.value_key not in missing_value_keys
+                or self._get(entry.value_key, SemanticCacheLookupError) is not None
+            ]
+            self._set(
+                bucket_key,
+                retained,
+                self._bucket_timeout(retained, meta.timeout, now),
+                SemanticCacheLookupError,
+            )
+
+        self._mutate(bucket_key, prune, SemanticCacheLookupError)
+
+    @staticmethod
+    def _bucket_timeout(
+        entries: list[CachedEntry],
+        fallback: int | None,
+        now: float,
+    ) -> int | None:
+        """Expire a bucket no sooner than the longest-lived value it indexes.
+
+        Requests resolve their own cache timeout (custom, chart, then dataset),
+        so one view's bucket indexes values stored with different TTLs. Writing
+        the bucket with the latest request's timeout would let a short-lived
+        store expire the index out from under longer-lived values, orphaning
+        them until their own TTL. ``0`` follows the backend's never-expire
+        convention and wins outright; ``None`` (backend default) is used only
+        when no entry carries an explicit TTL, because its length is unknown
+        here.
+        """
+        timeouts: list[int | None] = [entry.timeout for entry in entries]
+        if not timeouts:
+            return fallback
+        if any(timeout == 0 for timeout in timeouts):
+            return 0
+        remaining: list[float] = [

Review Comment:
   A bucket can contain both explicit-TTL entries and an entry with `timeout=None`. This calculation then uses only the explicit entries, so the index can expire while the backend-default-TTL value remains live and unreachable. Could a bucket containing any `None` timeout avoid a shorter explicit expiry (or otherwise keep that descriptor reachable)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4043847732


##########
docs/static/feature-flags.json:
##########
@@ -93,6 +93,12 @@
         "lifecycle": "development",
         "description": "Enable semantic layers and show semantic views alongside datasets"
       },
+      {
+        "name": "SEMANTIC_LAYER_CONTAINMENT_CACHE",

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset-frontend/src/explore/components/ChartPills.tsx:
##########
@@ -100,11 +112,20 @@ export const ChartPills = forwardRef(
               limit={Number(rowLimit ?? 0)}
             />
           )}
-          {!isLoading && firstQueryResponse?.is_cached && (
-            <CachedLabel
-              onClick={refreshCachedQuery}
-              cachedTimestamp={firstQueryResponse.cached_dttm}
-            />
+          {!isLoading &&
+            semanticCacheStatus !== 'MIXED' &&
+            (firstQueryResponse?.is_cached ||
+              semanticCacheStatus === 'HIT') && (
+              <CachedLabel
+                onClick={refreshCachedQuery}
+                cachedTimestamp={firstQueryResponse?.cached_dttm}
+                cacheSource={
+                  semanticCacheStatus === 'HIT' ? 'semantic' : 'result'
+                }
+              />
+            )}
+          {!isLoading && semanticCacheStatus === 'MIXED' && (

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,112 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants; containment is bypassed for a
+`GLOBAL` view whenever Superset row-level security applies to the request, since
+that variation is invisible to the provider. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag
+`SEMANTIC_LAYER_CONTAINMENT_CACHE`, and configure two backends:
+
+- `DATA_CACHE_CONFIG` holds the cached results and their descriptors. It must be
+  a persistent cache shared by every web and worker process, such as `RedisCache`.
+  The default `NullCache` discards every value, so containment would only ever
+  miss; `RedisSentinelCache` reads from replicas that can lag the master. Both
+  disable containment at startup rather than run it ineffectively.
+- `DISTRIBUTED_COORDINATION_CONFIG` must select `RedisCache` or
+  `RedisSentinelCache`; containment requires its atomic owner-token lease
+  operations.
+
+```python
+DATA_CACHE_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_DEFAULT_TIMEOUT": 86400,
+    "CACHE_KEY_PREFIX": "superset_results",
+    "CACHE_REDIS_URL": "redis://redis:6379/1",
+}
+DISTRIBUTED_COORDINATION_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_REDIS_URL": "redis://redis:6379/2",

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/charts/data/api.py:
##########
@@ -575,6 +575,9 @@ def _process_data(query_data: Any) -> Any:
                 )
             resp = make_response(response_data, 200)
             resp.headers["Content-Type"] = "application/json; charset=utf-8"
+            resp.headers["X-Superset-Semantic-Cache"] = SemanticCacheStatus.combine(

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/semantic_layers/cache_transform.py:
##########
@@ -0,0 +1,222 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""In-memory transformations for proven-compatible semantic cache results."""
+
+from collections.abc import Callable
+
+import pandas as pd
+import pyarrow as pa
+from superset_core.semantic_layers.types import (
+    AggregationType,
+    Filter,
+    Operator,
+    SemanticQuery,
+    SemanticResult,
+)
+
+from superset.semantic_layers.cache_policy import compile_like_pattern
+from superset.semantic_layers.cache_types import (
+    ContainmentCapabilities,
+    PatternSemantics,
+    ReuseDecision,
+    ReuseMode,
+    ROLLUP_COMPATIBLE_AGGREGATIONS,
+)
+
+
+def _sql_sum(series: pd.Series) -> object:
+    return series.sum(min_count=1)
+
+
+_ROLLUP_AGGREGATIONS: dict[AggregationType, str | Callable[[pd.Series], object]] = {
+    AggregationType.SUM: _sql_sum,
+    AggregationType.COUNT: "sum",
+    AggregationType.MIN: "min",
+    AggregationType.MAX: "max",
+}
+assert frozenset(_ROLLUP_AGGREGATIONS) == ROLLUP_COMPATIBLE_AGGREGATIONS
+
+
+class SemanticCacheTransformationError(RuntimeError):
+    """Cached data cannot safely satisfy an otherwise eligible query."""
+
+
+def _comparison_mask(
+    series: pd.Series, operator: Operator, value: object
+) -> pd.Series | None:
+    if value is None:
+        return pd.Series(False, index=series.index, dtype=bool)
+    not_null: pd.Series = series.notna()
+    comparisons: dict[Operator, Callable[[object], pd.Series]] = {
+        Operator.EQUALS: series.eq,
+        Operator.NOT_EQUALS: series.ne,
+        Operator.GREATER_THAN: series.gt,
+        Operator.GREATER_THAN_OR_EQUAL: series.ge,
+        Operator.LESS_THAN: series.lt,
+        Operator.LESS_THAN_OR_EQUAL: series.le,
+    }
+    comparison: Callable[[object], pd.Series] | None = comparisons.get(operator)
+    return not_null & comparison(value) if comparison else None
+
+
+def _membership_mask(
+    series: pd.Series,
+    operator: Operator,
+    values: set[object] | frozenset[object] | tuple[object, ...],
+) -> pd.Series:
+    not_null: pd.Series = series.notna()
+    non_null_values: list[object] = [item for item in values if item is not None]
+    membership: pd.Series = not_null & series.isin(non_null_values)
+    if operator is Operator.IN:
+        return membership
+    if None in values:
+        return pd.Series(False, index=series.index, dtype=bool)
+    return not_null & ~membership
+
+
+def _pattern_mask(
+    series: pd.Series,
+    operator: Operator,
+    pattern: str,
+    semantics: PatternSemantics,
+) -> pd.Series:
+    not_null: pd.Series = series.notna()
+    matches: pd.Series = not_null & series.astype("string").str.fullmatch(
+        compile_like_pattern(pattern, semantics.escape), na=False
+    )
+    return matches if operator is Operator.LIKE else not_null & ~matches
+
+
+def mask_for(
+    series: pd.Series,
+    operator: Operator,
+    value: object,
+    *,
+    pattern_semantics: PatternSemantics | None = None,
+) -> pd.Series:
+    """Return a SQL-WHERE-compatible boolean mask for a pandas series."""
+    if operator is Operator.IS_NULL:
+        return series.isna()
+    if operator is Operator.IS_NOT_NULL:
+        return series.notna()
+    comparison: pd.Series | None = _comparison_mask(series, operator, value)
+    if comparison is not None:
+        return comparison
+    if operator in {Operator.IN, Operator.NOT_IN} and isinstance(
+        value, (set, frozenset, tuple)
+    ):
+        return _membership_mask(series, operator, value)
+    if (
+        operator in {Operator.LIKE, Operator.NOT_LIKE}
+        and isinstance(value, str)
+        and pattern_semantics is not None
+    ):
+        return _pattern_mask(series, operator, value, pattern_semantics)
+    raise ValueError(f"Unsupported cached filter operation: {operator.value}")
+
+
+def _apply_leftovers(
+    frame: pd.DataFrame,
+    leftovers: frozenset[Filter],
+    capabilities: ContainmentCapabilities,
+) -> pd.DataFrame:
+    transformed: pd.DataFrame = frame
+    for filter_ in sorted(
+        leftovers,
+        key=lambda item: (
+            item.column.id if item.column else "",
+            item.operator.value,
+        ),
+    ):
+        if filter_.column is None:
+            raise ValueError("Cached post-processing requires a filter column")
+        column_name: str = filter_.column.name
+        transformed = transformed.loc[
+            mask_for(
+                transformed[column_name],
+                filter_.operator,
+                filter_.value,
+                pattern_semantics=capabilities.pattern_semantics,
+            )
+        ]
+    return transformed
+
+
+def _rollup(frame: pd.DataFrame, query: SemanticQuery) -> pd.DataFrame:
+    dimension_names: list[str] = [dimension.name for dimension in query.dimensions]
+    aggregations: dict[str, str | Callable[[pd.Series], object]] = {}
+    for metric in query.metrics:
+        if metric.aggregation not in _ROLLUP_AGGREGATIONS:
+            raise ValueError(f"Metric {metric.id} is not safely roll-up compatible")
+        aggregations[metric.name] = _ROLLUP_AGGREGATIONS[metric.aggregation]
+    if dimension_names:
+        return frame.groupby(dimension_names, as_index=False, dropna=False).agg(

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/common/query_context_processor.py:
##########
@@ -241,6 +241,12 @@ def get_df_payload_result(
             self._resolve_forced_query(query_obj, cache_key)
             or timeout == CACHE_DISABLED_TIMEOUT
         )
+        if query_obj:
+            # Datasources that run their own caching (semantic containment)
+            # must honor the same resolved chart/custom timeout and force
+            # decision as the result cache, not the datasource-level default.
+            query_obj.force_query = force_query

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/semantic_layers/mapper.py:
##########
@@ -147,8 +191,24 @@ def get_results(query_object: QueryObject) -> QueryResult:
 
     # Step 2: Execute the main query (first in the list)
     main_query = queries[0]
-    main_result = dispatcher(main_query)
+    main_outcome: SemanticCacheOutcome = _dispatch_semantic_query(
+        query_object.datasource,
+        dispatcher,
+        main_query,
+        force=query_object.force_query,
+        # Row-count results share the query's logical identity but not its
+        # shape: a cached table result would satisfy a row-count lookup (and
+        # vice versa) and break server-side pagination. Containment reuse is
+        # only defined over tabular results, so row-count dispatches bypass
+        # the cache entirely.
+        cacheable=not query_object.is_rowcount,

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6134337267

   Removing `hold!`: the remaining condition was https://github.com/apache/superset/pull/45100, which merged as 04db66b0f6627cd94f4f1c67b3577677a3f4e757.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184586538

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | fa1d7fae7e5e8f2eb5b688e1570d2683e6c69df5 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a72530204434a000829d1c6 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-42760--superset-docs-preview.netlify.app](https://deploy-preview-42760--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQyNzYwLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.myWw6tQVLckJ4XOV6LWskVIGwrIJFDHH3MRDFF8PSCE)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DctLDoAgDADRu3QtSUVE9AYeoxaiJPIJsDHGu8tuFm9eyCWF3GADGOAoFPnqXVmMqI00orpAsXkWTHw54WNzZ6HmU-zeunynZ7f90LTIeUKJSk2KENHI1Y6s4fsB) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-42760--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3716181937


##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,266 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from time import time
+from typing import cast, Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    semantic_dimension_key,
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            persisted: bool = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry) for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor."""
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+        descriptor: CachedEntry = CachedEntry(

Review Comment:
   **Suggestion:** The result value is written before descriptor registration, and a coordination failure returns without deleting that value. With a non-expiring timeout, every failed registration leaves an undiscoverable backend object indefinitely; even with expiration, repeated failures waste cache capacity. Delete `value_key` when mutation does not complete successfully. [resource leak]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Redis coordination failures create undiscoverable values.
   - ❌ Non-expiring semantic caches retain orphaned results indefinitely.
   - ⚠️ Repeated failed stores increase backend storage usage.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6c92efded7d14ff991691ad48995ecb5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6c92efded7d14ff991691ad48995ecb5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/semantic_layers/cache_repository.py
   **Line:** 175:176
   **Comment:**
   	*Resource Leak: The result value is written before descriptor registration, and a coordination failure returns without deleting that value. With a non-expiring timeout, every failed registration leaves an undiscoverable backend object indefinitely; even with expiration, repeated failures waste cache capacity. Delete `value_key` when mutation does not complete successfully.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42760&comment_hash=0cd60ec28d749203a789f94478b1c7f1c93c9dc455f33df43d392b6fcfc1e89d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42760&comment_hash=0cd60ec28d749203a789f94478b1c7f1c93c9dc455f33df43d392b6fcfc1e89d&reaction=dislike'>👎</a>



##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,266 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from time import time
+from typing import cast, Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    semantic_dimension_key,
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            persisted: bool = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry) for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor."""
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+        descriptor: CachedEntry = CachedEntry(
+            filters=frozenset(query.filters or set()),
+            dimension_keys=frozenset(
+                semantic_dimension_key(dimension) for dimension in query.dimensions
+            ),
+            metric_ids=frozenset(metric.id for metric in query.metrics),
+            limit=query.limit,
+            offset=query.offset or 0,
+            order_key=SemanticCacheIdentityFactory.order(query.order),
+            group_limit_key=SemanticCacheIdentityFactory.group_limit(query.group_limit),
+            value_key=value_key,
+            timestamp=self._clock(),
+        )
+
+        def register() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheStoreError)
+            )
+            retained: list[CachedEntry] = [
+                entry for entry in entries if entry.value_key != value_key
+            ]
+            retained.append(descriptor)
+            bounded: list[CachedEntry] = sorted(
+                retained,
+                key=lambda entry: entry.timestamp,
+                reverse=True,
+            )[:MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET]

Review Comment:
   **Suggestion:** When the descriptor list exceeds the bound, older descriptors are discarded but their referenced result values are never deleted. Those values become permanently unreachable when `meta.timeout` is `None`, so storing many distinct queries can grow the backend without bound despite the descriptor limit. Remove the value objects corresponding to evicted descriptors or provide an explicit garbage-collection mechanism. [resource leak]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ More than 128 queries evict descriptors.
   - ❌ Evicted result objects remain unreachable in cache storage.
   - ⚠️ Non-expiring buckets can grow with distinct queries.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5d29e382834546929f250d17db1b32b0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5d29e382834546929f250d17db1b32b0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/semantic_layers/cache_repository.py
   **Line:** 198:202
   **Comment:**
   	*Resource Leak: When the descriptor list exceeds the bound, older descriptors are discarded but their referenced result values are never deleted. Those values become permanently unreachable when `meta.timeout` is `None`, so storing many distinct queries can grow the backend without bound despite the descriptor limit. Remove the value objects corresponding to evicted descriptors or provide an explicit garbage-collection mechanism.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42760&comment_hash=dab94065c2516cebf9770844c1f81addc568c698e6fa3134e7f6356fe7160f0f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42760&comment_hash=dab94065c2516cebf9770844c1f81addc568c698e6fa3134e7f6356fe7160f0f&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5906267140

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6099942787

   Merged latest master in `6115764833`. The `UPDATING.md` conflict is resolved by retaining both release notes. The cache implementation and all direct/containment cache-key components are preserved.
   
   Validation passed: 1,459 focused Python tests, 12 cache-pill Jest tests, changed-file pre-commit hooks, and the normal push coverage gate. GitHub reports this head as mergeable. The `hold!` label remains in place; this update does not change the dependency on #45100 or mark the PR ready for merge.
   
   Merge prepared by Codex, with an independent Claude review of the exact merged tree. That review found no new issues; previously tracked deferred findings remain unchanged.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6127388823

   Merged latest master in `c8e39142ea`, keeping both sides of the release-note and mapper/test conflicts. Containment dispatch and the single metadata observation are preserved. With #45100 merged, the host metadata generation now reaches both the direct result-cache key and containment identity alongside the producer result-version key. The `hold!` label remains unchanged.
   
   Validation: 1,502 focused Python tests passed; the extra query-context run had 143 passes and one known Mac-only `longdouble` fixture failure whose test and production method are unchanged from master. After a fresh `npm ci`, all frontend package type builds, 12 cache-pill Jest tests, and changed-file hooks passed.
   
   The previous two failed checks were `check-hold-label` (expected while held) and `lint-frontend` (TS7006 implicit-any errors in chart-plugin control panels). Those plugin files are outside this PR's diff, and the type errors did not reproduce in the fresh local package build. The new CI run will provide the remote result.
   
   Merge prepared by Codex and independently reviewed by Claude on the exact committed tree; no blocking review findings. No ready-state or label changes were made.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3716293506


##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,266 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from time import time
+from typing import cast, Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    semantic_dimension_key,
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            persisted: bool = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry) for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor."""
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+        descriptor: CachedEntry = CachedEntry(

Review Comment:
   Fixed in f143574cc4. If descriptor coordination does not register the value, the repository deletes the undiscoverable result key. The regression test now asserts that a failed coordination attempt leaves no cached value behind.



##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,266 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from time import time
+from typing import cast, Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    semantic_dimension_key,
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            persisted: bool = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry) for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor."""
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+        descriptor: CachedEntry = CachedEntry(
+            filters=frozenset(query.filters or set()),
+            dimension_keys=frozenset(
+                semantic_dimension_key(dimension) for dimension in query.dimensions
+            ),
+            metric_ids=frozenset(metric.id for metric in query.metrics),
+            limit=query.limit,
+            offset=query.offset or 0,
+            order_key=SemanticCacheIdentityFactory.order(query.order),
+            group_limit_key=SemanticCacheIdentityFactory.group_limit(query.group_limit),
+            value_key=value_key,
+            timestamp=self._clock(),
+        )
+
+        def register() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheStoreError)
+            )
+            retained: list[CachedEntry] = [
+                entry for entry in entries if entry.value_key != value_key
+            ]
+            retained.append(descriptor)
+            bounded: list[CachedEntry] = sorted(
+                retained,
+                key=lambda entry: entry.timestamp,
+                reverse=True,
+            )[:MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET]

Review Comment:
   Fixed in f143574cc4. After the bounded descriptor list is persisted, the repository deletes result keys for descriptors evicted from that list. The regression test stores 129 distinct queries and asserts that only the 128 referenced result values remain.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sha174n (via GitHub)" <gi...@apache.org>.
sha174n commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5368859818

   Went through the cache-key construction for cross-context correctness and it holds up: the value key derives from a per-context bucket, and for the default EXECUTION_CONTEXT scope that bucket folds in principal, role ids, the datasource RLS cache key, and the guest token, which lines up with how the ordinary result cache partitions results; nice that it fails closed when there's no request context or resolvable principal, and that provider opt-in is required. The bounded-descriptor eviction now cleans up orphaned value keys too. One doc line worth making explicit: GLOBAL scope intentionally drops the per-context material, so it's only appropriate when a provider's results are provably identical across every principal and tenant. LGTM once rebased.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4032905061


##########
superset/semantic_layers/cache_transform.py:
##########
@@ -0,0 +1,222 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""In-memory transformations for proven-compatible semantic cache results."""
+
+from collections.abc import Callable
+
+import pandas as pd
+import pyarrow as pa
+from superset_core.semantic_layers.types import (
+    AggregationType,
+    Filter,
+    Operator,
+    SemanticQuery,
+    SemanticResult,
+)
+
+from superset.semantic_layers.cache_policy import compile_like_pattern
+from superset.semantic_layers.cache_types import (
+    ContainmentCapabilities,
+    PatternSemantics,
+    ReuseDecision,
+    ReuseMode,
+    ROLLUP_COMPATIBLE_AGGREGATIONS,
+)
+
+
+def _sql_sum(series: pd.Series) -> object:
+    return series.sum(min_count=1)
+
+
+_ROLLUP_AGGREGATIONS: dict[AggregationType, str | Callable[[pd.Series], object]] = {
+    AggregationType.SUM: _sql_sum,
+    AggregationType.COUNT: "sum",
+    AggregationType.MIN: "min",
+    AggregationType.MAX: "max",
+}
+assert frozenset(_ROLLUP_AGGREGATIONS) == ROLLUP_COMPATIBLE_AGGREGATIONS
+
+
+class SemanticCacheTransformationError(RuntimeError):
+    """Cached data cannot safely satisfy an otherwise eligible query."""
+
+
+def _comparison_mask(
+    series: pd.Series, operator: Operator, value: object
+) -> pd.Series | None:
+    if value is None:
+        return pd.Series(False, index=series.index, dtype=bool)
+    not_null: pd.Series = series.notna()
+    comparisons: dict[Operator, Callable[[object], pd.Series]] = {
+        Operator.EQUALS: series.eq,
+        Operator.NOT_EQUALS: series.ne,
+        Operator.GREATER_THAN: series.gt,
+        Operator.GREATER_THAN_OR_EQUAL: series.ge,
+        Operator.LESS_THAN: series.lt,
+        Operator.LESS_THAN_OR_EQUAL: series.le,
+    }
+    comparison: Callable[[object], pd.Series] | None = comparisons.get(operator)
+    return not_null & comparison(value) if comparison else None
+
+
+def _membership_mask(
+    series: pd.Series,
+    operator: Operator,
+    values: set[object] | frozenset[object] | tuple[object, ...],
+) -> pd.Series:
+    not_null: pd.Series = series.notna()
+    non_null_values: list[object] = [item for item in values if item is not None]
+    membership: pd.Series = not_null & series.isin(non_null_values)
+    if operator is Operator.IN:
+        return membership
+    if None in values:
+        return pd.Series(False, index=series.index, dtype=bool)
+    return not_null & ~membership
+
+
+def _pattern_mask(
+    series: pd.Series,
+    operator: Operator,
+    pattern: str,
+    semantics: PatternSemantics,
+) -> pd.Series:
+    not_null: pd.Series = series.notna()
+    matches: pd.Series = not_null & series.astype("string").str.fullmatch(
+        compile_like_pattern(pattern, semantics.escape), na=False
+    )
+    return matches if operator is Operator.LIKE else not_null & ~matches
+
+
+def mask_for(
+    series: pd.Series,
+    operator: Operator,
+    value: object,
+    *,
+    pattern_semantics: PatternSemantics | None = None,
+) -> pd.Series:
+    """Return a SQL-WHERE-compatible boolean mask for a pandas series."""
+    if operator is Operator.IS_NULL:
+        return series.isna()
+    if operator is Operator.IS_NOT_NULL:
+        return series.notna()
+    comparison: pd.Series | None = _comparison_mask(series, operator, value)
+    if comparison is not None:
+        return comparison
+    if operator in {Operator.IN, Operator.NOT_IN} and isinstance(
+        value, (set, frozenset, tuple)
+    ):
+        return _membership_mask(series, operator, value)
+    if (
+        operator in {Operator.LIKE, Operator.NOT_LIKE}
+        and isinstance(value, str)
+        and pattern_semantics is not None
+    ):
+        return _pattern_mask(series, operator, value, pattern_semantics)
+    raise ValueError(f"Unsupported cached filter operation: {operator.value}")
+
+
+def _apply_leftovers(
+    frame: pd.DataFrame,
+    leftovers: frozenset[Filter],
+    capabilities: ContainmentCapabilities,
+) -> pd.DataFrame:
+    transformed: pd.DataFrame = frame
+    for filter_ in sorted(
+        leftovers,
+        key=lambda item: (
+            item.column.id if item.column else "",
+            item.operator.value,
+        ),
+    ):
+        if filter_.column is None:
+            raise ValueError("Cached post-processing requires a filter column")
+        column_name: str = filter_.column.name
+        transformed = transformed.loc[
+            mask_for(
+                transformed[column_name],
+                filter_.operator,
+                filter_.value,
+                pattern_semantics=capabilities.pattern_semantics,
+            )
+        ]
+    return transformed
+
+
+def _rollup(frame: pd.DataFrame, query: SemanticQuery) -> pd.DataFrame:
+    dimension_names: list[str] = [dimension.name for dimension in query.dimensions]
+    aggregations: dict[str, str | Callable[[pd.Series], object]] = {}
+    for metric in query.metrics:
+        if metric.aggregation not in _ROLLUP_AGGREGATIONS:
+            raise ValueError(f"Metric {metric.id} is not safely roll-up compatible")
+        aggregations[metric.name] = _ROLLUP_AGGREGATIONS[metric.aggregation]
+    if dimension_names:
+        return frame.groupby(dimension_names, as_index=False, dropna=False).agg(

Review Comment:
   Could this groupby use `observed=True`? `to_pandas()` converts Arrow dictionary dimensions to categoricals, and pandas' default adds unobserved category groups (zero/NaN); with multiple categorical dimensions, `as_index=False` raises `ValueError`. A valid cached rollup can therefore return phantom rows or degrade to a miss. Please cover categorical single- and multi-dimension rollups.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5746361513

   ## Flag-on soak: PASS at `f934d64d`
   
   This completes the third hold-lift condition. Evidence summary; the full report with the harness, matrix and raw counters is in our spec repo.
   
   **Setup.** Isolated stack built from this PR's head, `SEMANTIC_LAYERS` + `SEMANTIC_LAYER_CONTAINMENT_CACHE` on at boot, an opted-in reference provider backed by a real SQL database, and — importantly — a **separate Redis client/db for `DISTRIBUTED_COORDINATION_CONFIG`** from `DATA_CACHE_CONFIG`, so the split-store path is the one under test. Every API answer was compared against the equivalent direct SQL result.
   
   **Timed run (4 concurrent clients, 1,210 s).**
   - **4,386 responses: all HTTP 200, all matching the independent SQL answer. Zero wrong answers, zero request errors.**
   - 880 forced refreshes racing normal reads; 3,466 HIT / 920 MISS at the API layer (API MISS also covers force-bypass and ordinary result-cache responses, so it is not the containment service's `miss` counter).
   - Matrix covered exact-key repeats, narrowed time ranges contained in a cached wider range, coarser-grain and filter subsets, and forced refreshes under concurrency.
   
   **Reader-side fence.** Four deterministic same-key writer-takeover rounds: **12/12 correct**. Containment counters for the window: `hit` 3,470, `miss` 2, `bypass` 968, **`fence_reject` 31**, plus `lookup_failure` 11, `coordination_failure` 16, `store_failure` 16 — those three are the *expected* observations from deliberately induced stale-writer and outage faults, and no incorrect answer was served in any of them.
   
   **Controls.** Flag off → no semantic caching (three bypass counters, zero semantic hits or stores). A Redis restart mid-soak recovered with no wrong answers.
   
   **Scope of the claim.** This is bounded validation for this SHA against the reference provider workload, not a proof for every provider or workload. Exact-head CI, including `test-semantic-cache-coordination`, is green.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4009278270


##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()

Review Comment:
   When renewal loses ownership, this still lets `operation()` write before reporting the failure. A paused writer can resume after a forced-refresh writer has replaced the same value key, overwrite that fresh payload with its older result, and leave the newer descriptor/TTL pointing at stale data. Could the bucket/value commit be fenced by the owner token instead of checking ownership only after it completes?



##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()
+        finally:
+            renewal_stopped.set()
+            renewal_thread.join()
+        return renewal_failed.is_set()
+
+    def mutate(self, key: str, operation: Callable[[], None]) -> bool:
+        """Acquire a bounded lease, mutate, and release only our ownership."""
+        lease_key: str = f"semantic-cache-lock:{key}"
+        owner_token: str = self._token_factory()
+        deadline: float = self._clock() + self._settings.wait_seconds
+        acquired: bool = False
+        while True:
+            try:
+                acquired = self._backend.acquire_owner_token(

Review Comment:
   `SEMANTIC_CACHE_COORDINATION_WAIT_SECONDS` does not bound this Redis call (or refresh/release), and the configured backend defaults socket timeouts to `None`; if Redis accepts the connection and then stops responding, a best-effort store can hang the chart request indefinitely after the provider result is ready. Could containment require bounded Redis I/O or enforce a timeout at this boundary?



##########
superset-frontend/src/explore/components/ChartPills.tsx:
##########
@@ -100,12 +100,19 @@ export const ChartPills = forwardRef(
               limit={Number(rowLimit ?? 0)}
             />
           )}
-          {!isLoading && firstQueryResponse?.is_cached && (
-            <CachedLabel
-              onClick={refreshCachedQuery}
-              cachedTimestamp={firstQueryResponse.cached_dttm}
-            />
-          )}
+          {!isLoading &&
+            (firstQueryResponse?.is_cached ||

Review Comment:
   Server-paginated tables always make a second row-count query that bypasses containment, but this label inspects only the first response. When the data query hits and the row-count query misses, the response is `MIXED` while Explore still says “Semantic cache,” overstating provenance. Could this aggregate every query response and cover the `HIT` + `MISS` case?



##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,99 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants; containment is bypassed for a
+`GLOBAL` view whenever Superset row-level security applies to the request, since
+that variation is invisible to the provider. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag
+`SEMANTIC_LAYER_CONTAINMENT_CACHE`, and configure two backends:
+
+- `DATA_CACHE_CONFIG` holds the cached results and their descriptors. It must be
+  a persistent cache shared by every web and worker process, such as `RedisCache`.
+  The default `NullCache` discards every value, so containment would only ever
+  miss; `RedisSentinelCache` reads from replicas that can lag the master. Both
+  disable containment at startup rather than run it ineffectively.
+- `DISTRIBUTED_COORDINATION_CONFIG` must select `RedisCache` or
+  `RedisSentinelCache`; containment requires its atomic owner-token lease
+  operations.
+
+```python
+DATA_CACHE_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_DEFAULT_TIMEOUT": 86400,
+    "CACHE_KEY_PREFIX": "superset_results",
+    "CACHE_REDIS_URL": "redis://redis:6379/1",
+}
+DISTRIBUTED_COORDINATION_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_REDIS_URL": "redis://redis:6379/2",
+}
+```
+
+Containment follows the same cache timeout the ordinary result cache resolves for
+a request (custom, then chart, then dataset), so a chart-level timeout of `-1`
+bypasses containment entirely, and honors `DATA_CACHE_MAX_VALUE_SIZE`: a result
+larger than that many bytes is served but not stored. The bounded defaults are
+`SEMANTIC_CACHE_COORDINATION_WAIT_SECONDS = 1.0` and
+`SEMANTIC_CACHE_COORDINATION_LEASE_SECONDS = 30`. A missing or unsuitable backend
+and missing or invalid coordination each disable only containment, log a fixed
+warning without configuration or query content, and leave provider execution
+available.
+
+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.
+Track `semantic_cache.containment.enabled` and the fixed-name `hit`, `miss`,

Review Comment:
   These are documented as bare `hit`/`miss` names, but the code emits `semantic_cache.containment.*`; the list also omits `transform_failure`, `prune_failure`, and `invalid_configuration`. An alert copied from this rollout guide can stay green while cache operations are falling back. Could this list the exact emitted names and all failure counters operators need?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5457811015

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5376395791

   Rebased and hardened — ready for a second look. Head is now `56a0cf02ec` (three commits over the approved `4b1166afb0`... rather, the same five commits rebased onto current master plus two fix commits):
   
   **Rebase** (@rusackas's ask): onto master `09bd8c98de` — 430 commits of drift, conflicts were three additive collisions in `query_object.py`/`query_context_factory.py` (master's `extra_cache_keys` sorting + `datasource_model_instance` beside this PR's `force_query`), all resolved keep-both.
   
   **@sadpandajoe's three findings**: all confirmed real and fixed in `e5d5077568` with regression tests that fail against the previous code — details in each thread. Thank you for the careful pass; the `results=None` one was worse than reported (the AttributeError escaped the transformation boundary, so cache hits 500'd).
   
   **@rusackas's CI nit**: done in `e5d5077568` — new `semantic-layers` change-detector group; `test-semantic-cache-coordination` now runs only when `superset/semantic_layers/`, its tests, superset-core's semantic-layer types, or the workflow/detector themselves change.
   
   **Additional hardening** (`56a0cf02ec`) from a data-systems review pass over the full branch before pushing:
   - `SemanticCacheService.execute` now degrades on *any* exception at each cache stage instead of only its typed errors — cached pickles outlive the code that wrote them, and a shape-incompatible entry from an older release previously failed every request on the view until TTL expiry. Unexpected failures log + count against the stage metrics and fall through to the provider.
   - `initialize_semantic_cache` fails closed on Sentinel-backed data caches (new `UNSUPPORTED_BACKEND` reason): flask-caching's `RedisSentinelCache` reads via `slave_for` replicas while writing the master, so the lease-guarded bucket read-modify-write loses read-your-writes under replication lag. Routing repository reads through the write client (which would re-enable Sentinel deployments) is tracked as follow-up work, along with the review's lower-severity items (lease write fencing, capability-flag collation contract documentation, payload size caps, guest-token bucket churn).
   
   **Verification**: 607 unit tests green, the `semantic_layers` 100% coverage gate holds, and every fix's regression test was control-run red against the unfixed code.
   
   *Rebase and fixes authored with AI assistance (Claude); all changes reviewed, tested, and control-verified as described.*


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4032766327


##########
superset-frontend/src/explore/components/ChartPills.tsx:
##########
@@ -100,11 +112,20 @@ export const ChartPills = forwardRef(
               limit={Number(rowLimit ?? 0)}
             />
           )}
-          {!isLoading && firstQueryResponse?.is_cached && (
-            <CachedLabel
-              onClick={refreshCachedQuery}
-              cachedTimestamp={firstQueryResponse.cached_dttm}
-            />
+          {!isLoading &&
+            semanticCacheStatus !== 'MIXED' &&
+            (firstQueryResponse?.is_cached ||
+              semanticCacheStatus === 'HIT') && (
+              <CachedLabel
+                onClick={refreshCachedQuery}
+                cachedTimestamp={firstQueryResponse?.cached_dttm}
+                cacheSource={
+                  semanticCacheStatus === 'HIT' ? 'semantic' : 'result'
+                }
+              />
+            )}
+          {!isLoading && semanticCacheStatus === 'MIXED' && (

Review Comment:
   For a server-paginated table, the row-count query is intentionally a containment miss while the data query can be a hit. That makes this branch the steady state and removes Explore's only force-refresh affordance. Could the mixed indicator retain the cache pill's refresh action?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5920088404

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3868224912


##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,71 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag

Review Comment:
   Containment stores results in `DATA_CACHE_CONFIG`, whose default `NullCache` discards every value, but these instructions only require distributed coordination. An operator can enable the feature successfully yet get only misses. Could this also require a persistent shared `DATA_CACHE_CONFIG` (with an example)?



##########
superset/semantic_layers/cache_host.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Host adaptation for semantic cache identity and provider contracts."""
+
+import hashlib
+from collections.abc import Iterable, Mapping
+from datetime import datetime
+from typing import cast, Protocol
+
+from flask import g, has_request_context
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+from superset import security_manager
+from superset.connectors.sqla.models import BaseDatasource
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    PatternSemantics,
+)
+from superset.semantic_layers.cache_repository import ViewMeta
+from superset.utils import json
+
+
+class _SemanticCacheProvider(Protocol):
+    semantic_cache_responsibility: SemanticCacheResponsibility
+    semantic_cache_scope: SemanticCacheScope
+    semantic_cache_capabilities: SemanticCacheCapabilities
+
+    def get_semantic_cache_provider_identity(
+        self,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+
+def _execution_context(
+    datasource: BaseDatasource,
+) -> SemanticCacheExecutionContext | None:
+    if not has_request_context() or not getattr(g, "user", None):
+        return None
+    user: object = g.user
+    principal: object = getattr(user, "id", None) or getattr(user, "username", None)
+    if principal is None:
+        return None
+    roles_value: object = getattr(user, "roles", ())
+    roles: Iterable[object] = (
+        roles_value
+        if isinstance(roles_value, Iterable) and not isinstance(roles_value, str)
+        else ()
+    )
+    role_ids: tuple[str, ...] = tuple(
+        sorted(
+            str(getattr(role, "id", None) or getattr(role, "name", ""))
+            for role in roles
+        )
+    )
+    guest_token: object = getattr(user, "guest_token", None)
+    rls_cache_key: list[str] = security_manager.get_rls_cache_key(datasource)
+    identity_payload: str = json.dumps(
+        {
+            "guest_token": guest_token,
+            "principal": str(principal),
+            "rls": rls_cache_key,
+            "roles": role_ids,
+        },
+        default=str,
+        separators=(",", ":"),
+        sort_keys=True,
+    )
+    host_identity: str = hashlib.sha256(identity_payload.encode()).hexdigest()
+    return SemanticCacheExecutionContext(str(principal), role_ids, host_identity)
+
+
+def build_cache_configuration(
+    datasource: BaseDatasource,
+) -> tuple[ViewMeta, ContainmentCapabilities] | None:
+    """Build safe host metadata when the provider explicitly opts in."""
+    layer: _SemanticCacheProvider = cast(
+        _SemanticCacheProvider,
+        datasource.semantic_layer.implementation,
+    )
+    if (
+        getattr(layer, "semantic_cache_responsibility", None)
+        is not SemanticCacheResponsibility.SUPERSET
+    ):
+        return None
+    provider_material: object = layer.get_semantic_cache_provider_identity()
+    if not isinstance(provider_material, SemanticCacheIdentityMaterial):
+        return None
+    scope: object = getattr(layer, "semantic_cache_scope", None)
+    scope_material: Mapping[str, object]
+    if scope is SemanticCacheScope.GLOBAL:
+        scope_material = {"scope": "global"}
+    elif scope is SemanticCacheScope.EXECUTION_CONTEXT:
+        context: SemanticCacheExecutionContext | None = _execution_context(datasource)
+        if context is None:
+            return None
+        context_material: object = layer.get_semantic_cache_context_identity(context)
+        if not isinstance(context_material, SemanticCacheIdentityMaterial):
+            return None
+        scope_material = {
+            "host_identity": context.host_identity,
+            "provider_identity": context_material.values,
+        }
+    else:
+        return None
+    provider_capabilities: object = getattr(layer, "semantic_cache_capabilities", None)
+    if not isinstance(provider_capabilities, SemanticCacheCapabilities):
+        return None
+    pattern_semantics: PatternSemantics | None = (
+        PatternSemantics.sql_like(escape=provider_capabilities.pattern_escape)
+        if provider_capabilities.pattern_escape is not None
+        else None
+    )
+    capabilities: ContainmentCapabilities = ContainmentCapabilities(
+        comparisons=provider_capabilities.comparisons,
+        membership=provider_capabilities.membership,
+        nulls=provider_capabilities.nulls,
+        pattern_semantics=pattern_semantics,
+    )
+    changed_on: object = getattr(datasource, "changed_on", None)
+    definition_material: dict[str, object] = {
+        "changed_on": changed_on.isoformat()
+        if isinstance(changed_on, datetime)
+        else str(changed_on),
+    }
+    meta: ViewMeta = ViewMeta(
+        view_identity=SemanticViewIdentity(str(datasource.uuid)),
+        definition_identity=SemanticCacheIdentityFactory.definition(
+            definition_material
+        ),
+        provider_identity=SemanticCacheIdentityFactory.provider(
+            provider_material.values
+        ),
+        scope_identity=SemanticCacheIdentityFactory.scope(scope_material),
+        timeout=datasource.cache_timeout,

Review Comment:
   The new bypass only reads `datasource.cache_timeout`. A chart-level or custom `-1` timeout still bypasses the normal result cache while containment stores and reuses the response, so a chart explicitly configured not to cache can serve stale rows. Could containment use the resolved query-context timeout and force flag too?



##########
superset/semantic_layers/mapper.py:
##########
@@ -221,6 +284,7 @@ def get_results(query_object: QueryObject) -> QueryResult:
         semantic_result,
         query_object,
         duration,
+        semantic_cache_hit=main_outcome.cache_hit,

Review Comment:
   This reports only the main query's outcome. For a time-comparison chart where the main query misses but an offset hits (or the reverse), the header and pill report a full miss or hit despite mixed provenance. Could this aggregate the offset outcomes or represent a mixed result?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5749266630

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3876479934


##########
superset/semantic_layers/mapper.py:
##########
@@ -221,6 +284,7 @@ def get_results(query_object: QueryObject) -> QueryResult:
         semantic_result,
         query_object,
         duration,
+        semantic_cache_hit=main_outcome.cache_hit,

Review Comment:
   Confirmed and fixed in `f0e9e32685`. The per-query boolean could not represent it, so `semantic_cache_hit` is now `semantic_cache_status: HIT | MISS | MIXED` (`SemanticCacheStatus` in `superset/constants.py`), aggregated over the main **and every offset** dispatch in `get_results`. The `X-Superset-Semantic-Cache` header combines the per-query statuses with the same vocabulary: `HIT` only when every query was `HIT`, `MIXED` if any was `HIT` or `MIXED`.
   
   The pill renders only on `HIT` — a `MIXED` payload included a provider round-trip, so "loaded from semantic cache" would overstate it. Parametrized `mapper_test` covers all four hit/miss combinations; the header test covers `MIXED` and mixed lists.
   



##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,71 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag

Review Comment:
   Confirmed and fixed in `f0e9e32685`, in both directions: the docs now require a persistent shared `DATA_CACHE_CONFIG` with a Redis example next to the coordination one, and `initialize_semantic_cache` fails closed on a `NullCache` data cache (`UNSUPPORTED_BACKEND`, the same path as Sentinel) with a startup warning that names `DATA_CACHE_CONFIG`. An operator who enables the flag on the default config now sees the misconfiguration at boot instead of a 0% hit rate.
   



##########
superset/semantic_layers/cache_host.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Host adaptation for semantic cache identity and provider contracts."""
+
+import hashlib
+from collections.abc import Iterable, Mapping
+from datetime import datetime
+from typing import cast, Protocol
+
+from flask import g, has_request_context
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+from superset import security_manager
+from superset.connectors.sqla.models import BaseDatasource
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    PatternSemantics,
+)
+from superset.semantic_layers.cache_repository import ViewMeta
+from superset.utils import json
+
+
+class _SemanticCacheProvider(Protocol):
+    semantic_cache_responsibility: SemanticCacheResponsibility
+    semantic_cache_scope: SemanticCacheScope
+    semantic_cache_capabilities: SemanticCacheCapabilities
+
+    def get_semantic_cache_provider_identity(
+        self,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+
+def _execution_context(
+    datasource: BaseDatasource,
+) -> SemanticCacheExecutionContext | None:
+    if not has_request_context() or not getattr(g, "user", None):
+        return None
+    user: object = g.user
+    principal: object = getattr(user, "id", None) or getattr(user, "username", None)
+    if principal is None:
+        return None
+    roles_value: object = getattr(user, "roles", ())
+    roles: Iterable[object] = (
+        roles_value
+        if isinstance(roles_value, Iterable) and not isinstance(roles_value, str)
+        else ()
+    )
+    role_ids: tuple[str, ...] = tuple(
+        sorted(
+            str(getattr(role, "id", None) or getattr(role, "name", ""))
+            for role in roles
+        )
+    )
+    guest_token: object = getattr(user, "guest_token", None)
+    rls_cache_key: list[str] = security_manager.get_rls_cache_key(datasource)
+    identity_payload: str = json.dumps(
+        {
+            "guest_token": guest_token,
+            "principal": str(principal),
+            "rls": rls_cache_key,
+            "roles": role_ids,
+        },
+        default=str,
+        separators=(",", ":"),
+        sort_keys=True,
+    )
+    host_identity: str = hashlib.sha256(identity_payload.encode()).hexdigest()
+    return SemanticCacheExecutionContext(str(principal), role_ids, host_identity)
+
+
+def build_cache_configuration(
+    datasource: BaseDatasource,
+) -> tuple[ViewMeta, ContainmentCapabilities] | None:
+    """Build safe host metadata when the provider explicitly opts in."""
+    layer: _SemanticCacheProvider = cast(
+        _SemanticCacheProvider,
+        datasource.semantic_layer.implementation,
+    )
+    if (
+        getattr(layer, "semantic_cache_responsibility", None)
+        is not SemanticCacheResponsibility.SUPERSET
+    ):
+        return None
+    provider_material: object = layer.get_semantic_cache_provider_identity()
+    if not isinstance(provider_material, SemanticCacheIdentityMaterial):
+        return None
+    scope: object = getattr(layer, "semantic_cache_scope", None)
+    scope_material: Mapping[str, object]
+    if scope is SemanticCacheScope.GLOBAL:
+        scope_material = {"scope": "global"}
+    elif scope is SemanticCacheScope.EXECUTION_CONTEXT:
+        context: SemanticCacheExecutionContext | None = _execution_context(datasource)
+        if context is None:
+            return None
+        context_material: object = layer.get_semantic_cache_context_identity(context)
+        if not isinstance(context_material, SemanticCacheIdentityMaterial):
+            return None
+        scope_material = {
+            "host_identity": context.host_identity,
+            "provider_identity": context_material.values,
+        }
+    else:
+        return None
+    provider_capabilities: object = getattr(layer, "semantic_cache_capabilities", None)
+    if not isinstance(provider_capabilities, SemanticCacheCapabilities):
+        return None
+    pattern_semantics: PatternSemantics | None = (
+        PatternSemantics.sql_like(escape=provider_capabilities.pattern_escape)
+        if provider_capabilities.pattern_escape is not None
+        else None
+    )
+    capabilities: ContainmentCapabilities = ContainmentCapabilities(
+        comparisons=provider_capabilities.comparisons,
+        membership=provider_capabilities.membership,
+        nulls=provider_capabilities.nulls,
+        pattern_semantics=pattern_semantics,
+    )
+    changed_on: object = getattr(datasource, "changed_on", None)
+    definition_material: dict[str, object] = {
+        "changed_on": changed_on.isoformat()
+        if isinstance(changed_on, datetime)
+        else str(changed_on),
+    }
+    meta: ViewMeta = ViewMeta(
+        view_identity=SemanticViewIdentity(str(datasource.uuid)),
+        definition_identity=SemanticCacheIdentityFactory.definition(
+            definition_material
+        ),
+        provider_identity=SemanticCacheIdentityFactory.provider(
+            provider_material.values
+        ),
+        scope_identity=SemanticCacheIdentityFactory.scope(scope_material),
+        timeout=datasource.cache_timeout,

Review Comment:
   Confirmed and fixed in `f0e9e32685` — and it was slightly worse than described: the factory only put the *request* `force` on the `QueryObject`, so the processor's resolved `force_query` (which folds in `timeout == -1`) and the resolved timeout never reached containment at all. `get_df_payload_result` now writes both onto the `QueryObject`, and `build_cache_configuration(..., cache_timeout=)` uses the resolved value both for the `-1` bypass (nothing read, nothing stored) and as the TTL of stored values, so a chart's own timeout bounds reuse. Covered in `cache_host_test`, `cache_integration_test` (store untouched by `-1` requests between cacheable ones), and `test_query_context_processor_timing`.
   
   One follow-on from a data-systems pass over that change, fixed in `7eb97a33a3`: with per-request TTLs, one view's descriptor bucket indexes values with different lifetimes, and the bucket was written with the *latest* request's timeout — a 60 s chart storing after a 3600 s chart would expire the index out from under the longer-lived value (orphaned until its own TTL, extra misses; never wrong data, since value keys are content-addressed). Descriptors now carry their TTL and the bucket expires no sooner than its longest-lived value. `IDENTITY_FORMAT_VERSION` is bumped to v3 because `CachedEntry` is pickled.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184683182

   This replacement keeps the containment-reuse idea from #40221, but changes its safety and architecture substantially:
   
   - **Explicit opt-in:** the original PR automatically wrapped semantic queries once `SEMANTIC_LAYERS` was enabled. This PR adds a separate default-off `SEMANTIC_LAYER_CONTAINMENT_CACHE` rollout flag, and requires each provider to explicitly delegate cache responsibility to Superset.
   - **Provider contract:** providers declare whether reuse is global or execution-context scoped, supply secret-free result-affecting identity material, and opt into only the comparison, membership, NULL, and pattern semantics they can guarantee.
   - **Security-aware identity:** cache identity includes the semantic definition and provider material; context-scoped identity also incorporates a hash of the principal, roles, guest-token claims, and RLS cache key.
   - **Smaller architecture:** the original cache implementation was a large multipurpose class/module. This version separates application orchestration, host adaptation, identity, containment policy, result transformation, repository storage, shared types, and distributed coordination.
   - **Distributed mutation safety:** descriptor updates use bounded Redis owner-token leases and atomic compare-and-delete release, with direct Redis and Sentinel coverage. This replaces the original non-atomic descriptor-index updates.
   - **Failure boundaries:** expected lookup, storage, and coordination failures leave provider queries available. Invalid or unsupported deployment configuration disables containment rather than semantic queries.
   - **Forced refresh:** `force_query` bypasses containment reads without changing ordinary result identity, and a successful forced provider result is stored under the canonical identity.
   - **Result provenance:** semantic containment hits are propagated separately from ordinary query-cache hits so the UI can explain which cache supplied the result.
   - **Rollout and observability:** requested/effective state, fixed-name metrics, unsupported-backend warnings, canary guidance, restart convergence, and rollback instructions are included.
   - **Verification:** the replacement adds deterministic concurrency and negative-control tests, a pinned real Redis/Sentinel CI path, and 100% statement/branch coverage for the semantic-layer package.
   
   The implementation also incorporates the still-valid fixes from #41824, #41825, #41826, and #41856 while avoiding unrelated files from the original branch.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184588252

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/42760?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 65.68%. Comparing base ([`3dde95d`](https://app.codecov.io/gh/apache/superset/commit/3dde95d80969bd0b67c97fb628723c21403c8062?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`fa1d7fa`](https://app.codecov.io/gh/apache/superset/commit/fa1d7fae7e5e8f2eb5b688e1570d2683e6c69df5?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 4 commits behind head on master.
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #42760      +/-   ##
   ==========================================
   + Coverage   65.59%   65.68%   +0.09%     
   ==========================================
     Files        2819     2824       +5     
     Lines      160372   160986     +614     
     Branches    36617    36615       -2     
   ==========================================
   + Hits       105188   105743     +555     
   - Misses      53120    53179      +59     
     Partials     2064     2064              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/42760/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [superset-extensions-cli](https://app.codecov.io/gh/apache/superset/pull/42760/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `90.57% <ø> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/42760?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3822170920


##########
superset/semantic_layers/cache_identity.py:
##########
@@ -0,0 +1,316 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Immutable identity values for semantic containment caching."""
+
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Mapping as MappingABC
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from typing import Mapping
+
+from superset_core.semantic_layers.types import (
+    AdhocExpression,
+    Dimension,
+    Filter,
+    GroupLimit,
+    Metric,
+    OrderTuple,
+    SemanticQuery,
+)
+
+from superset.utils import json
+
+IDENTITY_FORMAT_VERSION: str = "v2"
+_SENSITIVE_KEY_PARTS: tuple[str, ...] = (
+    "credential",
+    "password",
+    "secret",
+    "token",
+)
+
+
+class SensitiveIdentityMaterialError(ValueError):
+    """Raised when raw secret-like material is offered for cache identity."""
+
+
+def _find_sensitive_paths(value: object, prefix: str = "") -> list[str]:
+    sensitive_paths: list[str] = []
+    if isinstance(value, MappingABC):
+        for key, nested_value in value.items():
+            key_text: str = str(key)
+            path: str = f"{prefix}.{key_text}" if prefix else key_text
+            if any(part in key_text.casefold() for part in _SENSITIVE_KEY_PARTS):
+                sensitive_paths.append(path)
+            sensitive_paths.extend(_find_sensitive_paths(nested_value, path))
+    elif isinstance(value, (list, tuple)):
+        for index, nested_value in enumerate(value):
+            path = f"{prefix}[{index}]"
+            sensitive_paths.extend(_find_sensitive_paths(nested_value, path))
+    return sensitive_paths
+
+
+@dataclass(frozen=True)
+class SemanticViewIdentity:
+    """Stable identity of a semantic view."""
+
+    value: str
+
+
+@dataclass(frozen=True)
+class SemanticDefinitionIdentity:
+    """Versioned digest of result-affecting semantic-view definition fields."""
+
+    digest: str
+
+
+@dataclass(frozen=True)
+class SemanticCacheProviderIdentity:
+    """Versioned digest of result-affecting provider configuration."""
+
+    digest: str
+
+
+@dataclass(frozen=True)
+class SemanticCacheScopeIdentity:
+    """Digest separating global or execution-context cache scopes."""
+
+    digest: str
+
+
+class SemanticCacheIdentityFactory:
+    """Create deterministic, versioned identities from secret-safe material."""
+
+    @classmethod
+    def definition(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticDefinitionIdentity:
+        """Create a semantic-definition identity."""
+        return SemanticDefinitionIdentity(cls._digest(material))
+
+    @classmethod
+    def provider(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticCacheProviderIdentity:
+        """Create a provider-configuration identity."""
+        return SemanticCacheProviderIdentity(cls._digest(material))
+
+    @classmethod
+    def scope(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticCacheScopeIdentity:
+        """Create an execution-scope identity."""
+        return SemanticCacheScopeIdentity(cls._digest(material))
+
+    @classmethod
+    def query(cls, query: SemanticQuery) -> str:
+        """Create a logical identity from every result-affecting query field."""
+        digest: str = cls._digest(_canonical_query(query))
+        return f"semantic-cache:query:{digest}"
+
+    @classmethod
+    def bucket(
+        cls,
+        view: SemanticViewIdentity,
+        definition: SemanticDefinitionIdentity,
+        provider: SemanticCacheProviderIdentity,
+        scope: SemanticCacheScopeIdentity,
+    ) -> str:
+        """Create a descriptor-bucket identity from all host boundaries."""
+        digest: str = cls._digest(
+            {
+                "view": view.value,
+                "definition": definition.digest,
+                "provider": provider.digest,
+                "scope": scope.digest,
+            }
+        )
+        return f"semantic-cache:bucket:{digest}"
+
+    @classmethod
+    def value(cls, bucket: str, query: SemanticQuery) -> str:
+        """Create a result-value identity within a host boundary bucket."""
+        digest: str = cls._digest({"bucket": bucket, "query": cls.query(query)})
+        return f"semantic-cache:value:{digest}"
+
+    @staticmethod
+    def order(order: list[OrderTuple] | None) -> str:
+        """Serialize ordering for descriptor compatibility checks."""
+        if not order:
+            return ""
+        return _canonical_json(
+            [
+                {
+                    "element": _canonical_orderable(element),
+                    "direction": direction.value,
+                }
+                for element, direction in order
+            ]
+        )
+
+    @staticmethod
+    def group_limit(group_limit: GroupLimit | None) -> str:
+        """Serialize group-limit behavior for descriptor compatibility checks."""
+        if group_limit is None:
+            return ""
+        return _canonical_json(_canonical_group_limit(group_limit))
+
+    @staticmethod
+    def _digest(material: Mapping[str, object]) -> str:
+        sensitive_paths: list[str] = _find_sensitive_paths(material)
+        if sensitive_paths:
+            joined_keys: str = ", ".join(sorted(sensitive_paths))
+            raise SensitiveIdentityMaterialError(
+                f"Secret-like identity fields are not allowed: {joined_keys}"
+            )
+
+        canonical: str = json.dumps(
+            material,
+            ensure_ascii=False,
+            separators=(",", ":"),
+            sort_keys=True,
+        )
+        payload: bytes = f"{IDENTITY_FORMAT_VERSION}:{canonical}".encode()
+        return f"{IDENTITY_FORMAT_VERSION}:{hashlib.sha256(payload).hexdigest()}"
+
+
+def _canonical_query(query: SemanticQuery) -> Mapping[str, object]:

Review Comment:
   The cache key only encodes `SemanticQuery`, while this caller dispatches the same query to either `get_table` or `get_row_count`. When a server-paginated table issues otherwise identical data and row-count requests, the row-count lookup can reuse table rows and return no `rowcount`, breaking pagination. Can the dispatched result kind be part of the cache identity?



##########
superset/semantic_layers/cache_host.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Host adaptation for semantic cache identity and provider contracts."""
+
+import hashlib
+from collections.abc import Iterable, Mapping
+from datetime import datetime
+from typing import cast, Protocol
+
+from flask import g, has_request_context
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+from superset import security_manager
+from superset.connectors.sqla.models import BaseDatasource
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    PatternSemantics,
+)
+from superset.semantic_layers.cache_repository import ViewMeta
+from superset.utils import json
+
+
+class _SemanticCacheProvider(Protocol):
+    semantic_cache_responsibility: SemanticCacheResponsibility
+    semantic_cache_scope: SemanticCacheScope
+    semantic_cache_capabilities: SemanticCacheCapabilities
+
+    def get_semantic_cache_provider_identity(
+        self,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+
+def _execution_context(
+    datasource: BaseDatasource,
+) -> SemanticCacheExecutionContext | None:
+    if not has_request_context() or not getattr(g, "user", None):
+        return None
+    user: object = g.user
+    principal: object = getattr(user, "id", None) or getattr(user, "username", None)
+    if principal is None:
+        return None
+    roles_value: object = getattr(user, "roles", ())
+    roles: Iterable[object] = (
+        roles_value
+        if isinstance(roles_value, Iterable) and not isinstance(roles_value, str)
+        else ()
+    )
+    role_ids: tuple[str, ...] = tuple(
+        sorted(
+            str(getattr(role, "id", None) or getattr(role, "name", ""))
+            for role in roles
+        )
+    )
+    guest_token: object = getattr(user, "guest_token", None)
+    rls_cache_key: list[str] = security_manager.get_rls_cache_key(datasource)
+    identity_payload: str = json.dumps(
+        {
+            "guest_token": guest_token,
+            "principal": str(principal),
+            "rls": rls_cache_key,
+            "roles": role_ids,
+        },
+        default=str,
+        separators=(",", ":"),
+        sort_keys=True,
+    )
+    host_identity: str = hashlib.sha256(identity_payload.encode()).hexdigest()
+    return SemanticCacheExecutionContext(str(principal), role_ids, host_identity)
+
+
+def build_cache_configuration(
+    datasource: BaseDatasource,
+) -> tuple[ViewMeta, ContainmentCapabilities] | None:
+    """Build safe host metadata when the provider explicitly opts in."""
+    layer: _SemanticCacheProvider = cast(
+        _SemanticCacheProvider,
+        datasource.semantic_layer.implementation,
+    )
+    if (
+        getattr(layer, "semantic_cache_responsibility", None)
+        is not SemanticCacheResponsibility.SUPERSET
+    ):
+        return None
+    provider_material: object = layer.get_semantic_cache_provider_identity()
+    if not isinstance(provider_material, SemanticCacheIdentityMaterial):
+        return None
+    scope: object = getattr(layer, "semantic_cache_scope", None)
+    scope_material: Mapping[str, object]
+    if scope is SemanticCacheScope.GLOBAL:
+        scope_material = {"scope": "global"}
+    elif scope is SemanticCacheScope.EXECUTION_CONTEXT:
+        context: SemanticCacheExecutionContext | None = _execution_context(datasource)
+        if context is None:
+            return None
+        context_material: object = layer.get_semantic_cache_context_identity(context)
+        if not isinstance(context_material, SemanticCacheIdentityMaterial):
+            return None
+        scope_material = {
+            "host_identity": context.host_identity,
+            "provider_identity": context_material.values,
+        }
+    else:
+        return None
+    provider_capabilities: object = getattr(layer, "semantic_cache_capabilities", None)
+    if not isinstance(provider_capabilities, SemanticCacheCapabilities):
+        return None
+    pattern_semantics: PatternSemantics | None = (
+        PatternSemantics.sql_like(escape=provider_capabilities.pattern_escape)
+        if provider_capabilities.pattern_escape is not None
+        else None
+    )
+    capabilities: ContainmentCapabilities = ContainmentCapabilities(
+        comparisons=provider_capabilities.comparisons,
+        membership=provider_capabilities.membership,
+        nulls=provider_capabilities.nulls,
+        pattern_semantics=pattern_semantics,
+    )
+    changed_on: object = getattr(datasource, "changed_on", None)
+    definition_material: dict[str, object] = {
+        "changed_on": changed_on.isoformat()
+        if isinstance(changed_on, datetime)
+        else str(changed_on),
+    }
+    meta: ViewMeta = ViewMeta(
+        view_identity=SemanticViewIdentity(str(datasource.uuid)),
+        definition_identity=SemanticCacheIdentityFactory.definition(
+            definition_material
+        ),
+        provider_identity=SemanticCacheIdentityFactory.provider(
+            provider_material.values
+        ),
+        scope_identity=SemanticCacheIdentityFactory.scope(scope_material),
+        timeout=datasource.cache_timeout,

Review Comment:
   A datasource timeout of `-1` means caching is disabled, but this passes `-1` to the containment backend instead. RedisCache treats that as no expiry, so a query from a datasource configured never to cache can be reused indefinitely. Should this bypass containment (and use the resolved query timeout) when caching is disabled?



##########
superset/semantic_layers/cache.py:
##########
@@ -0,0 +1,310 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Application-level state for semantic containment caching."""
+
+from __future__ import annotations
+
+import enum
+import logging
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_coordination import (
+    OwnerTokenCoordinationBackend,
+    SemanticCacheCoordinationSettings,
+    SemanticCacheCoordinator,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    eligible_reuse_mode as eligible_reuse_mode,
+    rank_eligible_entries as rank_eligible_entries,
+)
+from superset.semantic_layers.cache_repository import (
+    SemanticCacheBackend,
+    SemanticCacheBackendError,
+    SemanticCacheLookupError,
+    SemanticCacheLookupResult,
+    SemanticCacheRepository,
+    SemanticCacheStoreError,
+    ViewMeta,
+)
+from superset.semantic_layers.cache_transform import (
+    SemanticCacheTransformationError,
+    transform_result,
+)
+
+
+class SemanticCacheDisabledReason(str, enum.Enum):
+    """Stable operational reasons why containment is ineffective."""
+
+    PARENT_FLAG_OFF = "parent_flag_off"
+    FLAG_OFF = "flag_off"
+    UNSUPPORTED_COORDINATION = "unsupported_coordination"
+    INVALID_COORDINATION_CONFIGURATION = "invalid_coordination_configuration"
+
+
+@dataclass(frozen=True)
+class SemanticCacheState:
+    """Requested and effective containment state owned by the cache service."""
+
+    requested: bool
+    effective: bool
+    disabled_reason: SemanticCacheDisabledReason | None
+
+    def __post_init__(self) -> None:
+        if self.effective and not self.requested:
+            raise ValueError("Effective semantic caching must be requested")
+        if self.effective and self.disabled_reason is not None:
+            raise ValueError("Effective semantic caching cannot have a disabled reason")
+        if not self.effective and self.disabled_reason is None:
+            raise ValueError("Ineffective semantic caching requires a disabled reason")
+
+    @classmethod
+    def enabled(cls) -> SemanticCacheState:
+        """Return the single valid effective state."""
+        return cls(requested=True, effective=True, disabled_reason=None)
+
+    @classmethod
+    def disabled(
+        cls,
+        reason: SemanticCacheDisabledReason,
+        *,
+        requested: bool = False,
+    ) -> SemanticCacheState:
+        """Return an explicitly ineffective state."""
+        return cls(
+            requested=requested,
+            effective=False,
+            disabled_reason=reason,
+        )
+
+
+@dataclass(frozen=True)
+class SemanticCacheOutcome:
+    """Host-side result plus whether containment supplied it."""
+
+    result: SemanticResult
+    cache_hit: bool
+
+
+class SemanticCacheMetrics(Protocol):
+    """Fixed-name metrics used by containment cache operations."""
+
+    def incr(self, key: str) -> None: ...  # pragma: no cover
+
+    def gauge(self, key: str, value: float) -> None: ...  # pragma: no cover
+
+
+SEMANTIC_CACHE_METRIC_PREFIX: str = "semantic_cache.containment"
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+class SafeSemanticCacheBackend:
+    """Translate pluggable cache-client failures into the repository boundary."""
+
+    def __init__(self, backend: SemanticCacheBackend) -> None:
+        self._backend: SemanticCacheBackend = backend
+
+    def get(self, key: str) -> object | None:
+        try:
+            return self._backend.get(key)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache get failed") from ex
+
+    def set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None = None,
+    ) -> bool:
+        try:
+            return self._backend.set(key, value, timeout=timeout)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache set failed") from ex
+
+    def delete(self, key: str) -> bool:
+        try:
+            return self._backend.delete(key)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache delete failed") from ex
+
+
+class SemanticCacheService:
+    """Orchestrate optional cache lookup, provider execution, and storage.
+
+    This service is intentionally limited to application flow. Cache identity,
+    containment proofs, result transformation, persistence, distributed mutation,
+    and Superset host adaptation live in ``cache_identity``, ``cache_policy``,
+    ``cache_transform``, ``cache_repository``, ``cache_coordination``, and
+    ``cache_host`` respectively. Keeping those decisions behind narrow boundaries
+    prevents the orchestration service from becoming a multipurpose cache class.
+    """
+
+    def __init__(
+        self,
+        state: SemanticCacheState,
+        repository: SemanticCacheRepository | None = None,
+        metrics: SemanticCacheMetrics | None = None,
+    ) -> None:
+        if state.effective and repository is None:
+            raise ValueError("Effective semantic caching requires a repository")
+        self.state: SemanticCacheState = state
+        self._repository: SemanticCacheRepository | None = repository
+        self._metrics: SemanticCacheMetrics | None = metrics
+
+    def _increment(self, suffix: str) -> None:
+        metrics: SemanticCacheMetrics | None = self._metrics
+        if metrics is None:
+            return
+        try:
+            metrics.incr(f"{SEMANTIC_CACHE_METRIC_PREFIX}.{suffix}")
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache metric emission failed", exc_info=True)
+
+    @classmethod
+    def default_ineffective(cls) -> SemanticCacheService:
+        """Build the safe process default used before capability initialization."""
+        return cls(SemanticCacheState.disabled(SemanticCacheDisabledReason.FLAG_OFF))
+
+    def execute(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        provider: Callable[[SemanticQuery], SemanticResult],
+        *,
+        capabilities: ContainmentCapabilities,
+        force: bool = False,
+    ) -> SemanticCacheOutcome:
+        """Serve a proven hit or execute and best-effort store provider output."""
+        repository: SemanticCacheRepository | None = self._repository
+        if not self.state.effective or repository is None:
+            self._increment("bypass")
+            return SemanticCacheOutcome(provider(query), cache_hit=False)
+        if not force:
+            try:
+                lookup_result: SemanticCacheLookupResult = repository.lookup(
+                    meta, query, capabilities
+                )
+            except SemanticCacheLookupError:
+                self._increment("lookup_failure")
+                return SemanticCacheOutcome(provider(query), cache_hit=False)
+            for candidate in lookup_result.candidates:
+                try:
+                    transformed: SemanticResult = transform_result(
+                        candidate.result,
+                        query,
+                        candidate.decision,
+                        capabilities,
+                    )
+                except SemanticCacheTransformationError:
+                    self._increment("transform_failure")
+                    continue
+                self._increment("hit")
+                return SemanticCacheOutcome(transformed, cache_hit=True)
+            try:
+                repository.prune_missing(
+                    meta,
+                    lookup_result.missing_value_keys,
+                )
+            except SemanticCacheLookupError:
+                self._increment("prune_failure")
+            self._increment("miss")
+        else:
+            self._increment("bypass")
+        result: SemanticResult = provider(query)
+        try:
+            repository.store(meta, query, result)

Review Comment:
   This stores the provider result before `mapper.py` normalizes `SemanticResult(results=None)` to an empty Arrow table. The first empty result succeeds, but the next cache hit calls `result.results.select(...)` and raises on `None`. Could the result be normalized before it is stored, or skipped when it has no table?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5377352859

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5672580249

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6067908164

   Update in `3b9d669dbd` (master merged): the containment fail-safe now bypasses the cache and runs the provider whenever the host metadata token is missing or invalid, so it can't reuse a legacy entry without a token. The precision fix is preserved. This stays on hold until #45100 merges, since #45100 supplies the per-layer metadata version that containment keys on. The combination was tested in review, and the semantic suite passes after the master merge.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6083350396

   Pushed f90b19ee76, which brings in master and fixes one cache-identity gap.
   
   - **Master merge:** master's completeness check now runs inside the containment cache's provider dispatch, which is the miss path. An incomplete or rejected provider result raises before anything is stored.
   - **Containment identity:** it now includes the same producer result-version discriminator that master added to the direct result cache key (`("semantic-result-version", layer type, version)`). Results stored under an older producer guarantee can no longer be reused through a containment hit. Layers without a version keep their existing identity.
   - **Tests:** the discriminator partitions the containment definition identity, and a version change forces a miss and then a hit. A provider rejection or completeness error on a miss is raised, not cached, and the next successful query is stored normally.
   
   Still on hold until the metadata-cache invalidation work lands; containment composes with its generation token. One docs-only conflict with master remains in `docs/developer_docs/extensions/contribution-types.md`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #42760:
URL: https://github.com/apache/superset/pull/42760


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5275955655

   Just needing a rebase here @mikebridge and we're good to merge.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5726160478

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4051039715


##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()

Review Comment:
   Addressed with a reader-side publication fence in https://github.com/apache/superset/commit/37cdc79ea78a20a6ff8e03b83ec6bae24ff8df6c (also merges master).
   
   Each store generates a fresh write nonce shared by its descriptor and cached result envelope. Exact and containment lookups require a matching nonempty nonce and a valid result. In the interleaving you described, B's descriptor cannot validate A's late payload: the reader rejects that pair and falls back to another valid candidate or provider execution. Dedupe also requires a valid pair, so the mismatch cannot pin an unusable entry. Pruning re-reads the pair under the mutation coordinator and does not delete payloads. The existing same-client Lua path remains.
   
   The regression pauses A inside the plain data-cache SET after its successful ownership check, expires A's lease, lets B publish and observe its newer value, then allows A's stale SET. Both exact and containment cases demonstrate rejection and maintenance. The final-tree semantic suite passed 839 tests with 100% statement/branch coverage; MyPy passed, and source-resolved TypeScript checking covered all eight changed TS/TSX files with zero diagnostics. The standard isolated-clone frontend hook still reports missing built declarations (TS6305); the source check is the verified frontend gate.
   
   The documented limits remain: this is paired-record validation, not an atomic cross-store write or a general linearizability guarantee. A pruning process paused beyond its lease can still overwrite a repaired bucket and lose reachability; delayed eviction can likewise cause misses. Repeated stalls may cause repeated provider fallbacks, rather than a bounded single miss. Identity v4 isolates the envelope format, but old workers retain the old race until upgraded/drained. Real Redis/Sentinel full-process-pause and provider-result validation remain rollout gates. Keeping this PR draft with hold! in place.



##########
.github/workflows/superset-python-integrationtest.yml:
##########
@@ -38,6 +39,55 @@
         with:
           token: ${{ secrets.GITHUB_TOKEN }}
 
+  test-semantic-cache-coordination:
+    needs: changes
+    if: needs.changes.outputs.semantic-layers == 'true'
+    runs-on: ubuntu-26.04
+    timeout-minutes: 15
+    env:
+      PYTHONPATH: ${{ github.workspace }}
+      SEMANTIC_CACHE_REDIS_PORT: 16379
+      SEMANTIC_CACHE_SENTINEL_PORT: 26379
+    services:
+      redis:
+        image: redis:7.4.10-alpine3.21
+        ports:
+          - 16379:6379
+        options: >-
+          --health-cmd="redis-cli ping"
+          --health-interval=2s
+          --health-timeout=2s
+          --health-retries=20
+    steps:
+      - name: Checkout
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+        with:
+          persist-credentials: false
+          submodules: recursive
+      - name: Setup Python
+        uses: ./.github/actions/setup-backend/

Review Comment:
   Fixed in https://github.com/apache/superset/commit/37cdc79ea78a20a6ff8e03b83ec6bae24ff8df6c: the setup-backend action now uses GitHub's dedicated self-repository syntax, `$/.github/actions/setup-backend/`. The final-tree zizmor hook passed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4043848547


##########
superset/coordination/cache_backend.py:
##########
@@ -280,12 +346,14 @@ def __init__(  # pylint: disable=too-many-arguments
         ssl_ca_certs: str | None = None,
         socket_timeout: float | None = None,
         socket_connect_timeout: float | None = None,
+        force_master_ip: str | None = None,
         **kwargs: Any,
     ) -> None:
         # Sentinel dont directly support SSL
         # Initialize Sentinel without SSL parameters
         self._sentinel = Sentinel(
             sentinels,
+            force_master_ip=force_master_ip,

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/semantic_layers/cache_repository.py:
##########
@@ -0,0 +1,428 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Storage records for semantic containment caching."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from contextvars import ContextVar
+from dataclasses import dataclass, fields
+from math import ceil
+from time import time
+from typing import cast, Protocol, TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from superset.coordination.cache_backend import RedisCommandsMixin
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticCacheProviderIdentity,
+    SemanticCacheScopeIdentity,
+    SemanticDefinitionIdentity,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import rank_reuse_decisions
+from superset.semantic_layers.cache_types import (
+    CachedEntry as CachedEntry,
+    CachedResultCandidate as CachedResultCandidate,
+    ContainmentCapabilities,
+    ReuseDecision,
+    SemanticCacheLookupResult as SemanticCacheLookupResult,
+)
+
+MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET: int = 128
+
+
+class SemanticCacheRepositoryError(RuntimeError):
+    """Base error for expected cache-adapter failures."""
+
+
+class SemanticCacheLookupError(SemanticCacheRepositoryError):
+    """Raised when an expected backend lookup operation fails."""
+
+
+class SemanticCacheStoreError(SemanticCacheRepositoryError):
+    """Raised when an expected backend store operation fails."""
+
+
+class SemanticCacheBackendError(RuntimeError):
+    """Expected operational failure raised by an expiring backend adapter."""
+
+
+class SemanticCacheCoordinationError(RuntimeError):
+    """Expected operational failure raised by a mutation coordinator."""
+
+
+@dataclass(frozen=True)
+class SemanticCacheWriteFence:
+    """Mutation-local lease identity; never shared between concurrent writers."""
+
+    key: str
+    owner_token: str
+    check_owner: Callable[[], bool]
+    redis_backend: RedisCommandsMixin | None = None
+
+
+semantic_cache_write_fence: ContextVar[SemanticCacheWriteFence | None] = ContextVar(
+    "semantic_cache_write_fence", default=None
+)
+
+
+@dataclass(frozen=True)
+class ViewMeta:
+    """Identity and expiry inputs for one semantic-view cache bucket."""
+
+    view_identity: SemanticViewIdentity
+    definition_identity: SemanticDefinitionIdentity
+    provider_identity: SemanticCacheProviderIdentity
+    scope_identity: SemanticCacheScopeIdentity
+    timeout: int | None
+
+
+class SemanticCacheBackend(Protocol):
+    """Expiring value/descriptor operations required by the repository."""
+
+    def get(self, key: str) -> object | None: ...  # pragma: no cover
+
+    def has(self, key: str) -> bool: ...  # pragma: no cover
+
+    def set(
+        self, key: str, value: object, timeout: int | None = None
+    ) -> bool: ...  # pragma: no cover
+
+    def delete(self, key: str) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheMutationCoordinator(Protocol):
+    """Boundary for ownership-safe descriptor mutation."""
+
+    def mutate(
+        self, key: str, operation: Callable[[], None]
+    ) -> bool: ...  # pragma: no cover
+
+
+class SemanticCacheRepository:
+    """Store expiring results and bounded descriptors behind injected ports."""
+
+    def __init__(
+        self,
+        backend: SemanticCacheBackend,
+        coordinator: SemanticCacheMutationCoordinator,
+        *,
+        clock: Callable[[], float] = time,
+    ) -> None:
+        self._backend: SemanticCacheBackend = backend
+        self._coordinator: SemanticCacheMutationCoordinator = coordinator
+        self._clock: Callable[[], float] = clock
+
+    def _get(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> object | None:
+        try:
+            return self._backend.get(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend get failed") from ex
+
+    def _has(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._backend.has(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend has failed") from ex
+
+    def _set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            fence: SemanticCacheWriteFence | None = semantic_cache_write_fence.get()
+            persisted: bool | None = None
+            if fence is not None:
+                fenced_set: (
+                    Callable[
+                        [SemanticCacheWriteFence, str, object, int | None], bool | None
+                    ]
+                    | None
+                ) = getattr(self._backend, "set_if_owner", None)
+                if fenced_set is not None:
+                    persisted = fenced_set(fence, key, value, timeout)
+                if persisted is None and not fence.check_owner():
+                    raise SemanticCacheCoordinationError(
+                        "Semantic cache lease ownership was lost"
+                    )
+            if persisted is None:
+                # Non-Redis or separate-client stores cannot atomically check
+                # the lease and SET. Recheck immediately before this best-effort
+                # write; a lease takeover between the two calls remains possible.
+                persisted = self._backend.set(key, value, timeout=timeout)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend set failed") from ex
+        if not persisted:
+            raise error_type("Semantic cache backend rejected set")
+
+    def _mutate(
+        self,
+        key: str,
+        operation: Callable[[], None],
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> bool:
+        try:
+            return self._coordinator.mutate(key, operation)
+        except SemanticCacheCoordinationError as ex:
+            raise error_type("Semantic cache descriptor mutation failed") from ex
+
+    def _delete(
+        self,
+        key: str,
+        error_type: type[SemanticCacheRepositoryError],
+    ) -> None:
+        try:
+            self._backend.delete(key)
+        except SemanticCacheBackendError as ex:
+            raise error_type("Semantic cache backend delete failed") from ex
+
+    @staticmethod
+    def _bucket_key(meta: ViewMeta) -> str:
+        return SemanticCacheIdentityFactory.bucket(
+            meta.view_identity,
+            meta.definition_identity,
+            meta.provider_identity,
+            meta.scope_identity,
+        )
+
+    @staticmethod
+    def _entries(value: object | None) -> list[CachedEntry]:
+        # A pickled dataclass restores only the attributes it was written
+        # with, so an entry from an older shape can pass ``isinstance`` and
+        # still lack a field (a class-level default masks that from
+        # ``hasattr``, hence the instance-dict check). Key rotation
+        # (``IDENTITY_FORMAT_VERSION``) is the primary defence; treating such
+        # a bucket as empty is the backstop, so it costs one miss and a
+        # re-store rather than a lookup failure on every request until the
+        # bucket expires.
+        expected: tuple[str, ...] = tuple(field.name for field in fields(CachedEntry))
+        if not isinstance(value, list) or not all(
+            isinstance(entry, CachedEntry)
+            and all(name in vars(entry) for name in expected)
+            for entry in value
+        ):
+            return []
+        return cast(list[CachedEntry], value)
+
+    def store(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        result: SemanticResult,
+        *,
+        replace: bool = True,
+    ) -> bool:
+        """Store a TTL-bounded value and register its bounded descriptor.
+
+        With ``replace`` false, a value that another request already stored
+        and registered under the same identity is left alone: the identical
+        provider result is already discoverable, and skipping saves this
+        request the lease wait and the payload write. A herd of identical
+        misses then contends for the lease once, not once per request.
+        """
+        bucket_key: str = self._bucket_key(meta)
+        value_key: str = SemanticCacheIdentityFactory.value(bucket_key, query)
+        now: float = self._clock()
+        if not replace and self._is_registered(bucket_key, value_key, meta, now):
+            return True
+        descriptor: CachedEntry = CachedEntry(
+            filters=frozenset(query.filters or set()),
+            dimensions=frozenset(query.dimensions),
+            metrics=frozenset(query.metrics),
+            limit=query.limit,
+            offset=query.offset or 0,
+            order_key=SemanticCacheIdentityFactory.order(query.order),
+            group_limit_key=SemanticCacheIdentityFactory.group_limit(query.group_limit),
+            value_key=value_key,
+            timestamp=now,
+            timeout=meta.timeout,
+        )
+
+        def register() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheStoreError)
+            )
+            retained: list[CachedEntry] = [
+                entry for entry in entries if entry.value_key != value_key
+            ]
+            retained.append(descriptor)
+            bounded: list[CachedEntry] = sorted(
+                retained,
+                key=lambda entry: entry.timestamp,
+                reverse=True,
+            )[:MAX_SEMANTIC_CACHE_DESCRIPTORS_PER_BUCKET]
+            bounded_value_keys: set[str] = {entry.value_key for entry in bounded}
+            evicted_value_keys: set[str] = {
+                entry.value_key
+                for entry in retained
+                if entry.value_key not in bounded_value_keys
+            }
+            self._set(
+                bucket_key,
+                bounded,
+                self._bucket_timeout(bounded, meta.timeout, now),
+                SemanticCacheStoreError,
+            )
+            self._set(value_key, result, meta.timeout, SemanticCacheStoreError)
+            for evicted_value_key in evicted_value_keys:
+                self._delete(evicted_value_key, SemanticCacheStoreError)
+
+        return self._mutate(bucket_key, register, SemanticCacheStoreError)
+
+    @staticmethod
+    def _serves(entry: CachedEntry, meta: ViewMeta, now: float) -> bool:
+        """Whether a stored value may answer a request with ``meta``'s timeout.
+
+        Requests resolve their own cache timeout, so a value stored by a
+        long-timeout chart can outlive what a short-timeout chart on the same
+        view is allowed to reuse. The value's age is bounded by the requesting
+        timeout (``None`` and ``0`` follow the backend's unbounded conventions),
+        and for the store dedupe the stored TTL must also cover this request,
+        or the longer-lived chart would be pinned to the shorter entry.
+        """
+        if meta.timeout is None or meta.timeout <= 0:
+            return True
+        if now - entry.timestamp > meta.timeout:
+            return False
+        return (
+            entry.timeout is None
+            or entry.timeout <= 0
+            or (entry.timeout >= meta.timeout)
+        )
+
+    def _is_registered(
+        self,
+        bucket_key: str,
+        value_key: str,
+        meta: ViewMeta,
+        now: float,
+    ) -> bool:
+        entries: list[CachedEntry] = self._entries(
+            self._get(bucket_key, SemanticCacheStoreError)
+        )
+        return any(
+            entry.value_key == value_key and self._serves(entry, meta, now)
+            for entry in entries
+        ) and self._has(value_key, SemanticCacheStoreError)
+
+    def lookup(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        capabilities: ContainmentCapabilities,
+    ) -> SemanticCacheLookupResult:
+        """Load ranked values and report missing descriptors without mutation."""
+        bucket_key: str = self._bucket_key(meta)
+        now: float = self._clock()
+        entries: list[CachedEntry] = [
+            entry
+            for entry in self._entries(self._get(bucket_key, SemanticCacheLookupError))
+            if self._serves(entry, meta, now)
+        ]
+        ranked: list[tuple[ReuseDecision, CachedEntry]] = rank_reuse_decisions(
+            query, entries, capabilities
+        )
+        candidates: list[CachedResultCandidate] = []
+        missing_value_keys: set[str] = set()
+        for decision, entry in ranked:
+            value: object | None = self._get(entry.value_key, SemanticCacheLookupError)
+            if not isinstance(value, SemanticResult):
+                missing_value_keys.add(entry.value_key)
+                continue
+            candidates.append(CachedResultCandidate(entry, value, decision))
+            break
+        return SemanticCacheLookupResult(
+            candidates=tuple(candidates),
+            missing_value_keys=frozenset(missing_value_keys),
+        )
+
+    def prune_missing(
+        self,
+        meta: ViewMeta,
+        missing_value_keys: frozenset[str],
+    ) -> None:
+        """Identity-safely remove descriptors whose values remain absent."""
+        if not missing_value_keys:
+            return
+        bucket_key: str = self._bucket_key(meta)
+        now: float = self._clock()
+
+        def prune() -> None:
+            entries: list[CachedEntry] = self._entries(
+                self._get(bucket_key, SemanticCacheLookupError)
+            )
+            retained: list[CachedEntry] = [
+                entry
+                for entry in entries
+                if entry.value_key not in missing_value_keys
+                or self._get(entry.value_key, SemanticCacheLookupError) is not None
+            ]
+            self._set(
+                bucket_key,
+                retained,
+                self._bucket_timeout(retained, meta.timeout, now),
+                SemanticCacheLookupError,
+            )
+
+        self._mutate(bucket_key, prune, SemanticCacheLookupError)
+
+    @staticmethod
+    def _bucket_timeout(
+        entries: list[CachedEntry],
+        fallback: int | None,
+        now: float,
+    ) -> int | None:
+        """Expire a bucket no sooner than the longest-lived value it indexes.
+
+        Requests resolve their own cache timeout (custom, chart, then dataset),
+        so one view's bucket indexes values stored with different TTLs. Writing
+        the bucket with the latest request's timeout would let a short-lived
+        store expire the index out from under longer-lived values, orphaning
+        them until their own TTL. ``0`` follows the backend's never-expire
+        convention and wins outright; ``None`` (backend default) is used only
+        when no entry carries an explicit TTL, because its length is unknown
+        here.
+        """
+        timeouts: list[int | None] = [entry.timeout for entry in entries]
+        if not timeouts:
+            return fallback
+        if any(timeout == 0 for timeout in timeouts):
+            return 0
+        remaining: list[float] = [

Review Comment:
   addressed in b5b6ed484382aa7a2b0615403d7dfc28f608244b



##########
superset/charts/schemas.py:
##########
@@ -1806,6 +1807,17 @@ class ChartDataResponseResult(Schema):
         required=True,
         allow_none=None,
     )
+    semantic_cache_status: fields.String = fields.String(

Review Comment:
   addressed in 75e44b557d6ec531693a045eb46cd9d6ab38b8b3 — regenerated the OpenAPI response property.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4009550420


##########
.github/workflows/superset-python-integrationtest.yml:
##########
@@ -38,6 +39,55 @@
         with:
           token: ${{ secrets.GITHUB_TOKEN }}
 
+  test-semantic-cache-coordination:
+    needs: changes
+    if: needs.changes.outputs.semantic-layers == 'true'
+    runs-on: ubuntu-26.04
+    timeout-minutes: 15
+    env:
+      PYTHONPATH: ${{ github.workspace }}
+      SEMANTIC_CACHE_REDIS_PORT: 16379
+      SEMANTIC_CACHE_SENTINEL_PORT: 26379
+    services:
+      redis:
+        image: redis:7.4.10-alpine3.21
+        ports:
+          - 16379:6379
+        options: >-
+          --health-cmd="redis-cli ping"
+          --health-interval=2s
+          --health-timeout=2s
+          --health-retries=20
+    steps:
+      - name: Checkout
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+        with:
+          persist-credentials: false
+          submodules: recursive
+      - name: Setup Python
+        uses: ./.github/actions/setup-backend/

Review Comment:
   ## zizmor / 
   
   use GitHub's dedicated self-repository syntax: use '$/...' instead of './...'
   
   [Show more details](https://github.com/apache/superset/security/code-scanning/3881)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5442035972

   Slapped a hold label on at @mikebridge 's request... just a timing thing, not a blocker-based thing. He can rescind this at any time he wants to merge for proper stacking/timing.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5376420316

   For reviewers and early adopters — the data-systems review pass that produced the hardening commit also catalogued the limitations we're consciously shipping with, so they're documented here rather than discovered in production. None serve wrong data except the second, which is an opt-in contract hazard; all are queued as follow-up work.
   
   **Known limitations accepted for this PR**
   
   - **Sentinel deployments are disabled, not fixed** (`initialize_semantic_cache`): the `UNSUPPORTED_BACKEND` gate is deliberate — flask-caching's `RedisSentinelCache` reads via `slave_for` replicas while writing the master, so the lease-guarded bucket read-modify-write loses read-your-writes under replication lag (a fresh descriptor can be invisible to the next lease holder, which then persists the stale bucket over it; the prune path's existence recheck has the same exposure). Follow-up: route repository reads through the write client, then drop the gate.
   - **Capability flags assume binary collation** (`cache_transform.py`, `SemanticCacheCapabilities`): leftover filters re-apply in pandas with byte-equality, case-sensitive semantics. A provider on a case-insensitive collation (MySQL `utf8mb4_ci`, SQL Server defaults) that sets `comparisons=True` or `pattern_escape` would serve different rows from cache than from the warehouse. Until the flag docs make this contract explicit, providers on case-insensitive collations should not opt in.
   - **Lease writes are unfenced** (`cache_coordination.py`): a holder paused past `lease_seconds` can overwrite its successor's bucket on resume; ownership loss is detected after the mutation. Bounded to lost descriptors and orphaned values until TTL — content-addressed value keys mean no interleaving can bind a descriptor to the wrong query's result — so this is an accepted efficiency anomaly, not a correctness one. Compare-and-set bucket writes would close it.
   - **No payload size cap**: full pyarrow results are pickled into the data cache; very large results should probably skip containment rather than flood the backend. Related: embedded guest tokens are folded whole into the scope identity, so every token (fresh `exp`/`iat`) mints a new bucket — near-zero reuse for embedded traffic.
   - **`cache_timeout=0` means never-expire** in cachelib, and identity rotation via `changed_on` strands the previous bucket with TTL as the only GC — operators using 0 should know those orphans are permanent.
   - **Smaller items**: fixed 50ms lease-acquisition spin without jitter (first-load herd on a hot view); descriptor LRU ordered by per-worker wall clocks (skew can misorder eviction); a release failure in the mutation's `finally` can mask the original exception in logs; async/Celery contexts bypass EXECUTION_CONTEXT containment by design (no request context — consistent misses, never wrong data); the `semantic_cache_hit` flag reflects the main query only, not time-offset sub-queries.
   
   The same pass explicitly verified the core safety properties: content-addressed value keys make the descriptor↔value binding race-proof and prevent cross-user/RLS reuse, provider execution never runs under the lease, release/refresh use compare-Lua (an expired owner cannot release its successor — integration-tested), and corrupted buckets self-heal.
   
   *Review and write-up produced with AI assistance (Claude); findings verified against the code and installed library behavior as described.*


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4033088933


##########
superset/coordination/cache_backend.py:
##########
@@ -280,12 +346,14 @@ def __init__(  # pylint: disable=too-many-arguments
         ssl_ca_certs: str | None = None,
         socket_timeout: float | None = None,
         socket_connect_timeout: float | None = None,
+        force_master_ip: str | None = None,
         **kwargs: Any,
     ) -> None:
         # Sentinel dont directly support SSL
         # Initialize Sentinel without SSL parameters
         self._sentinel = Sentinel(
             sentinels,
+            force_master_ip=force_master_ip,

Review Comment:
   This passes `force_master_ip` even when it is `None`, but our supported `redis>=5.0.0` range includes redis-py 5.0, whose `Sentinel` constructor forwards that unknown kwarg into connection setup. Sentinel-backed coordination then fails on its first cache operation instead of retaining the prior behavior. Could this omit the kwarg when unset (or raise the minimum redis-py version)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4032894776


##########
superset/semantic_layers/cache_coordination.py:
##########
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ownership-safe coordination for semantic-cache descriptor mutations."""
+
+import logging
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from random import random
+from threading import Event, Thread
+from time import monotonic, sleep
+from typing import Protocol, runtime_checkable
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+
+from superset.semantic_layers.cache_repository import SemanticCacheCoordinationError
+
+SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC: str = (
+    "semantic_cache.containment.coordination_failure"
+)
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+@runtime_checkable
+class OwnerTokenCoordinationBackend(Protocol):
+    """Atomic lease operations required from a coordination backend."""
+
+    def acquire_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+    def release_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+    ) -> bool: ...  # pragma: no cover
+
+    def refresh_owner_token(
+        self,
+        key: str,
+        owner_token: str,
+        lease_seconds: int,
+    ) -> bool: ...  # pragma: no cover
+
+
+@dataclass(frozen=True)
+class SemanticCacheCoordinationSettings:
+    """Validated bounded timing settings for descriptor leases."""
+
+    wait_seconds: float
+    lease_seconds: int
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.wait_seconds, bool)
+            or not isinstance(self.wait_seconds, (int, float))
+            or not math.isfinite(self.wait_seconds)
+            or self.wait_seconds < 0
+        ):
+            raise ValueError(
+                "Coordination wait seconds must be finite and non-negative"
+            )
+        if (
+            isinstance(self.lease_seconds, bool)
+            or not isinstance(self.lease_seconds, int)
+            or self.lease_seconds <= 0
+        ):
+            raise ValueError("Coordination lease seconds must be positive")
+
+
+class SemanticCacheCoordinator:
+    """Run descriptor mutations while holding an owner-token lease."""
+
+    def __init__(
+        self,
+        backend: OwnerTokenCoordinationBackend,
+        settings: SemanticCacheCoordinationSettings,
+        *,
+        clock: Callable[[], float] = monotonic,
+        sleeper: Callable[[float], None] = sleep,
+        token_factory: Callable[[], str] = lambda: uuid4().hex,
+        failure_metric: Callable[[str], None] | None = None,
+        jitter: Callable[[], float] = random,
+    ) -> None:
+        self._backend: OwnerTokenCoordinationBackend = backend
+        self._settings: SemanticCacheCoordinationSettings = settings
+        self._clock: Callable[[], float] = clock
+        self._sleeper: Callable[[float], None] = sleeper
+        self._token_factory: Callable[[], str] = token_factory
+        self._failure_metric: Callable[[str], None] = failure_metric or (lambda _: None)
+        self._jitter: Callable[[], float] = jitter
+
+    def _failure(self, message: str, cause: RedisError | None = None) -> None:
+        self._record_failure()
+        error: SemanticCacheCoordinationError = SemanticCacheCoordinationError(message)
+        if cause is None:
+            raise error
+        raise error from cause
+
+    def _record_failure(self) -> None:
+        try:
+            self._failure_metric(SEMANTIC_CACHE_COORDINATION_FAILURE_METRIC)
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache coordination metric failed", exc_info=True)
+
+    def _run_with_renewal(
+        self,
+        lease_key: str,
+        owner_token: str,
+        operation: Callable[[], None],
+    ) -> bool:
+        renewal_stopped: Event = Event()
+        renewal_failed: Event = Event()
+
+        def renew_lease() -> None:
+            interval: float = self._settings.lease_seconds / 3
+            while not renewal_stopped.wait(interval):
+                try:
+                    refreshed: bool = self._backend.refresh_owner_token(
+                        lease_key,
+                        owner_token,
+                        self._settings.lease_seconds,
+                    )
+                except RedisError:
+                    renewal_failed.set()
+                    return
+                if not refreshed:
+                    renewal_failed.set()
+                    return
+
+        renewal_thread: Thread = Thread(
+            target=renew_lease,
+            name="semantic-cache-lease-renewal",
+            daemon=True,
+        )
+        renewal_thread.start()
+        try:
+            operation()

Review Comment:
   Thanks for the clarification. The separate-client path still has the original stale-write race: `set_if_owner` returns `None`, then `cache_repository._set` refreshes the owner token and performs a plain data-cache `SET`. A forced refresh can take the coordination lease and write a newer value between those two calls, after which the paused writer still overwrites that value. Can the separate-store configuration fence the value write too, rather than documenting a race in the normal data-cache/coordination split?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5184966370

   ### Manual local testing
   
   The clearest manual test uses two different semantic queries where the first
   result safely contains the second. This distinguishes containment reuse from
   Superset's ordinary exact-query cache.
   
   No built-in production semantic provider opts into this cache yet, so this test
   requires a local provider or extension implementing the new cache contract.
   
   #### 1. Start Redis
   
   ```bash
   docker run --rm --name superset-semantic-redis \
     -p 6379:6379 redis:7-alpine
   ```
   
   #### 2. Configure Superset
   
   Add the following to `superset_config.py`:
   
   ```python
   FEATURE_FLAGS = {
       "SEMANTIC_LAYERS": True,
       "SEMANTIC_LAYER_CONTAINMENT_CACHE": True,
   }
   
   DATA_CACHE_CONFIG = {
       "CACHE_TYPE": "RedisCache",
       "CACHE_REDIS_HOST": "127.0.0.1",
       "CACHE_REDIS_PORT": 6379,
       "CACHE_REDIS_DB": 1,
       "CACHE_DEFAULT_TIMEOUT": 300,
   }
   
   DISTRIBUTED_COORDINATION_CONFIG = {
       "CACHE_TYPE": "RedisCache",
       "CACHE_REDIS_HOST": "127.0.0.1",
       "CACHE_REDIS_PORT": 6379,
       "CACHE_REDIS_DB": 2,
       "CACHE_REDIS_PASSWORD": "",
   }
   ```
   
   When Superset runs in Docker, use the Redis service/container hostname instead
   of `127.0.0.1`. Restart every web and worker process after changing configuration.
   
   #### 3. Opt in the semantic provider
   
   The provider needs the equivalent of:
   
   ```python
   from superset_core.semantic_layers.layer import (
       SemanticCacheCapabilities,
       SemanticCacheIdentityMaterial,
       SemanticCacheResponsibility,
       SemanticCacheScope,
   )
   
   semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
   semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
   semantic_cache_capabilities = SemanticCacheCapabilities(
       comparisons=True,
       membership=True,
       nulls=True,
       pattern_escape="\\",
   )
   
   def get_semantic_cache_provider_identity(self):
       return SemanticCacheIdentityMaterial(
           {"provider_version": "local-test-v1", "catalog": self.config.catalog}
       )
   
   def get_semantic_cache_context_identity(self, context):
       return SemanticCacheIdentityMaterial({"tenant": "local-test"})
   ```
   
   #### 4. Exercise containment
   
   1. Create a chart from an opted-in semantic view, grouped by `country` and
      `city`, using an additive metric such as `SUM(revenue)`.
   2. Run it and confirm that the semantic provider receives the request.
   3. Remove `city`, leaving the chart grouped only by `country`.
   4. Run it again.
   
   The second query differs from the first, but the first result contains enough
   detail to answer it. Superset should roll up the cached rows without another
   provider request.
   
   #### 5. Verify the result
   
   Inspect the chart-data response in browser developer tools. It should contain:
   
   ```json
   {
     "semantic_cache_hit": true
   }
   ```
   
   The cache pill tooltip should say **Loaded from semantic cache**. Provider logs
   or a temporary request counter should show that only the first query reached the
   provider. Confirm that the country totals exactly match a forced provider query.
   
   #### 6. Negative controls
   
   - Click the cache pill to force-refresh: the provider should run and
     `semantic_cache_hit` should be false.
   - Request a metric absent from the cached result: the provider should run.
   - Disable `SEMANTIC_LAYER_CONTAINMENT_CACHE` and restart: both requests should
     reach the provider.
   - Remove `DISTRIBUTED_COORDINATION_CONFIG` and restart: containment should be
     disabled without breaking semantic queries.
   - With `EXECUTION_CONTEXT`, repeat as another user: that user's first request
     should miss rather than reuse the other user's result.
   
   The same behavior has a quick non-UI smoke test:
   
   ```bash
   source ~/venv/superset/bin/activate
   pytest -q tests/unit_tests/semantic_layers/cache_integration_test.py
   ```
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5417589311

   Has fresh conflicts, but getting closer!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r3834348313


##########
superset/semantic_layers/cache_host.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Host adaptation for semantic cache identity and provider contracts."""
+
+import hashlib
+from collections.abc import Iterable, Mapping
+from datetime import datetime
+from typing import cast, Protocol
+
+from flask import g, has_request_context
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+from superset import security_manager
+from superset.connectors.sqla.models import BaseDatasource
+from superset.semantic_layers.cache_identity import (
+    SemanticCacheIdentityFactory,
+    SemanticViewIdentity,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    PatternSemantics,
+)
+from superset.semantic_layers.cache_repository import ViewMeta
+from superset.utils import json
+
+
+class _SemanticCacheProvider(Protocol):
+    semantic_cache_responsibility: SemanticCacheResponsibility
+    semantic_cache_scope: SemanticCacheScope
+    semantic_cache_capabilities: SemanticCacheCapabilities
+
+    def get_semantic_cache_provider_identity(
+        self,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial | None: ...  # pragma: no cover
+
+
+def _execution_context(
+    datasource: BaseDatasource,
+) -> SemanticCacheExecutionContext | None:
+    if not has_request_context() or not getattr(g, "user", None):
+        return None
+    user: object = g.user
+    principal: object = getattr(user, "id", None) or getattr(user, "username", None)
+    if principal is None:
+        return None
+    roles_value: object = getattr(user, "roles", ())
+    roles: Iterable[object] = (
+        roles_value
+        if isinstance(roles_value, Iterable) and not isinstance(roles_value, str)
+        else ()
+    )
+    role_ids: tuple[str, ...] = tuple(
+        sorted(
+            str(getattr(role, "id", None) or getattr(role, "name", ""))
+            for role in roles
+        )
+    )
+    guest_token: object = getattr(user, "guest_token", None)
+    rls_cache_key: list[str] = security_manager.get_rls_cache_key(datasource)
+    identity_payload: str = json.dumps(
+        {
+            "guest_token": guest_token,
+            "principal": str(principal),
+            "rls": rls_cache_key,
+            "roles": role_ids,
+        },
+        default=str,
+        separators=(",", ":"),
+        sort_keys=True,
+    )
+    host_identity: str = hashlib.sha256(identity_payload.encode()).hexdigest()
+    return SemanticCacheExecutionContext(str(principal), role_ids, host_identity)
+
+
+def build_cache_configuration(
+    datasource: BaseDatasource,
+) -> tuple[ViewMeta, ContainmentCapabilities] | None:
+    """Build safe host metadata when the provider explicitly opts in."""
+    layer: _SemanticCacheProvider = cast(
+        _SemanticCacheProvider,
+        datasource.semantic_layer.implementation,
+    )
+    if (
+        getattr(layer, "semantic_cache_responsibility", None)
+        is not SemanticCacheResponsibility.SUPERSET
+    ):
+        return None
+    provider_material: object = layer.get_semantic_cache_provider_identity()
+    if not isinstance(provider_material, SemanticCacheIdentityMaterial):
+        return None
+    scope: object = getattr(layer, "semantic_cache_scope", None)
+    scope_material: Mapping[str, object]
+    if scope is SemanticCacheScope.GLOBAL:
+        scope_material = {"scope": "global"}
+    elif scope is SemanticCacheScope.EXECUTION_CONTEXT:
+        context: SemanticCacheExecutionContext | None = _execution_context(datasource)
+        if context is None:
+            return None
+        context_material: object = layer.get_semantic_cache_context_identity(context)
+        if not isinstance(context_material, SemanticCacheIdentityMaterial):
+            return None
+        scope_material = {
+            "host_identity": context.host_identity,
+            "provider_identity": context_material.values,
+        }
+    else:
+        return None
+    provider_capabilities: object = getattr(layer, "semantic_cache_capabilities", None)
+    if not isinstance(provider_capabilities, SemanticCacheCapabilities):
+        return None
+    pattern_semantics: PatternSemantics | None = (
+        PatternSemantics.sql_like(escape=provider_capabilities.pattern_escape)
+        if provider_capabilities.pattern_escape is not None
+        else None
+    )
+    capabilities: ContainmentCapabilities = ContainmentCapabilities(
+        comparisons=provider_capabilities.comparisons,
+        membership=provider_capabilities.membership,
+        nulls=provider_capabilities.nulls,
+        pattern_semantics=pattern_semantics,
+    )
+    changed_on: object = getattr(datasource, "changed_on", None)
+    definition_material: dict[str, object] = {
+        "changed_on": changed_on.isoformat()
+        if isinstance(changed_on, datetime)
+        else str(changed_on),
+    }
+    meta: ViewMeta = ViewMeta(
+        view_identity=SemanticViewIdentity(str(datasource.uuid)),
+        definition_identity=SemanticCacheIdentityFactory.definition(
+            definition_material
+        ),
+        provider_identity=SemanticCacheIdentityFactory.provider(
+            provider_material.values
+        ),
+        scope_identity=SemanticCacheIdentityFactory.scope(scope_material),
+        timeout=datasource.cache_timeout,

Review Comment:
   Confirmed and fixed in `e5d5077568`. `build_cache_configuration` now bypasses containment entirely when `cache_timeout == CACHE_DISABLED_TIMEOUT`, mirroring the guard in `set_and_log_cache` — the raw `-1` previously reached the backend, where Redis reads a negative TTL as *no expiry*, inverting "never cache" into "cache forever". Regression test `test_cache_configuration_bypasses_disabled_caching` fails against the previous code.
   
   *Fix authored with AI assistance; verified as described.*



##########
superset/semantic_layers/cache_identity.py:
##########
@@ -0,0 +1,316 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Immutable identity values for semantic containment caching."""
+
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Mapping as MappingABC
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from typing import Mapping
+
+from superset_core.semantic_layers.types import (
+    AdhocExpression,
+    Dimension,
+    Filter,
+    GroupLimit,
+    Metric,
+    OrderTuple,
+    SemanticQuery,
+)
+
+from superset.utils import json
+
+IDENTITY_FORMAT_VERSION: str = "v2"
+_SENSITIVE_KEY_PARTS: tuple[str, ...] = (
+    "credential",
+    "password",
+    "secret",
+    "token",
+)
+
+
+class SensitiveIdentityMaterialError(ValueError):
+    """Raised when raw secret-like material is offered for cache identity."""
+
+
+def _find_sensitive_paths(value: object, prefix: str = "") -> list[str]:
+    sensitive_paths: list[str] = []
+    if isinstance(value, MappingABC):
+        for key, nested_value in value.items():
+            key_text: str = str(key)
+            path: str = f"{prefix}.{key_text}" if prefix else key_text
+            if any(part in key_text.casefold() for part in _SENSITIVE_KEY_PARTS):
+                sensitive_paths.append(path)
+            sensitive_paths.extend(_find_sensitive_paths(nested_value, path))
+    elif isinstance(value, (list, tuple)):
+        for index, nested_value in enumerate(value):
+            path = f"{prefix}[{index}]"
+            sensitive_paths.extend(_find_sensitive_paths(nested_value, path))
+    return sensitive_paths
+
+
+@dataclass(frozen=True)
+class SemanticViewIdentity:
+    """Stable identity of a semantic view."""
+
+    value: str
+
+
+@dataclass(frozen=True)
+class SemanticDefinitionIdentity:
+    """Versioned digest of result-affecting semantic-view definition fields."""
+
+    digest: str
+
+
+@dataclass(frozen=True)
+class SemanticCacheProviderIdentity:
+    """Versioned digest of result-affecting provider configuration."""
+
+    digest: str
+
+
+@dataclass(frozen=True)
+class SemanticCacheScopeIdentity:
+    """Digest separating global or execution-context cache scopes."""
+
+    digest: str
+
+
+class SemanticCacheIdentityFactory:
+    """Create deterministic, versioned identities from secret-safe material."""
+
+    @classmethod
+    def definition(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticDefinitionIdentity:
+        """Create a semantic-definition identity."""
+        return SemanticDefinitionIdentity(cls._digest(material))
+
+    @classmethod
+    def provider(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticCacheProviderIdentity:
+        """Create a provider-configuration identity."""
+        return SemanticCacheProviderIdentity(cls._digest(material))
+
+    @classmethod
+    def scope(
+        cls,
+        material: Mapping[str, object],
+    ) -> SemanticCacheScopeIdentity:
+        """Create an execution-scope identity."""
+        return SemanticCacheScopeIdentity(cls._digest(material))
+
+    @classmethod
+    def query(cls, query: SemanticQuery) -> str:
+        """Create a logical identity from every result-affecting query field."""
+        digest: str = cls._digest(_canonical_query(query))
+        return f"semantic-cache:query:{digest}"
+
+    @classmethod
+    def bucket(
+        cls,
+        view: SemanticViewIdentity,
+        definition: SemanticDefinitionIdentity,
+        provider: SemanticCacheProviderIdentity,
+        scope: SemanticCacheScopeIdentity,
+    ) -> str:
+        """Create a descriptor-bucket identity from all host boundaries."""
+        digest: str = cls._digest(
+            {
+                "view": view.value,
+                "definition": definition.digest,
+                "provider": provider.digest,
+                "scope": scope.digest,
+            }
+        )
+        return f"semantic-cache:bucket:{digest}"
+
+    @classmethod
+    def value(cls, bucket: str, query: SemanticQuery) -> str:
+        """Create a result-value identity within a host boundary bucket."""
+        digest: str = cls._digest({"bucket": bucket, "query": cls.query(query)})
+        return f"semantic-cache:value:{digest}"
+
+    @staticmethod
+    def order(order: list[OrderTuple] | None) -> str:
+        """Serialize ordering for descriptor compatibility checks."""
+        if not order:
+            return ""
+        return _canonical_json(
+            [
+                {
+                    "element": _canonical_orderable(element),
+                    "direction": direction.value,
+                }
+                for element, direction in order
+            ]
+        )
+
+    @staticmethod
+    def group_limit(group_limit: GroupLimit | None) -> str:
+        """Serialize group-limit behavior for descriptor compatibility checks."""
+        if group_limit is None:
+            return ""
+        return _canonical_json(_canonical_group_limit(group_limit))
+
+    @staticmethod
+    def _digest(material: Mapping[str, object]) -> str:
+        sensitive_paths: list[str] = _find_sensitive_paths(material)
+        if sensitive_paths:
+            joined_keys: str = ", ".join(sorted(sensitive_paths))
+            raise SensitiveIdentityMaterialError(
+                f"Secret-like identity fields are not allowed: {joined_keys}"
+            )
+
+        canonical: str = json.dumps(
+            material,
+            ensure_ascii=False,
+            separators=(",", ":"),
+            sort_keys=True,
+        )
+        payload: bytes = f"{IDENTITY_FORMAT_VERSION}:{canonical}".encode()
+        return f"{IDENTITY_FORMAT_VERSION}:{hashlib.sha256(payload).hexdigest()}"
+
+
+def _canonical_query(query: SemanticQuery) -> Mapping[str, object]:

Review Comment:
   Confirmed and fixed in `e5d5077568`, via bypass rather than key-widening: row-count dispatches now skip the cache in **both** directions (`cacheable=not query_object.is_rowcount` on the main and offset paths). Reasoning: containment reuse is only defined over tabular results — even with the result kind folded into the identity, a row-count entry could never survive `transform_result`'s column projection, so kind-scoped entries would only ever be dead weight in the descriptor bucket. Bypassing keeps the identity model simple and fixes both failure directions (row-count reusing table rows, and a stored scalar poisoning later table lookups). Regression test `test_rowcount_dispatch_bypasses_cache_both_directions` also pins that the tabular entry seeded by a prior table query stays undisturbed.
   
   *Fix authored with AI assistance; verified as described.*



##########
superset/semantic_layers/cache.py:
##########
@@ -0,0 +1,310 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Application-level state for semantic containment caching."""
+
+from __future__ import annotations
+
+import enum
+import logging
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Protocol
+
+from superset_core.semantic_layers.types import SemanticQuery, SemanticResult
+
+from superset.semantic_layers.cache_coordination import (
+    OwnerTokenCoordinationBackend,
+    SemanticCacheCoordinationSettings,
+    SemanticCacheCoordinator,
+)
+from superset.semantic_layers.cache_policy import (
+    ContainmentCapabilities,
+    eligible_reuse_mode as eligible_reuse_mode,
+    rank_eligible_entries as rank_eligible_entries,
+)
+from superset.semantic_layers.cache_repository import (
+    SemanticCacheBackend,
+    SemanticCacheBackendError,
+    SemanticCacheLookupError,
+    SemanticCacheLookupResult,
+    SemanticCacheRepository,
+    SemanticCacheStoreError,
+    ViewMeta,
+)
+from superset.semantic_layers.cache_transform import (
+    SemanticCacheTransformationError,
+    transform_result,
+)
+
+
+class SemanticCacheDisabledReason(str, enum.Enum):
+    """Stable operational reasons why containment is ineffective."""
+
+    PARENT_FLAG_OFF = "parent_flag_off"
+    FLAG_OFF = "flag_off"
+    UNSUPPORTED_COORDINATION = "unsupported_coordination"
+    INVALID_COORDINATION_CONFIGURATION = "invalid_coordination_configuration"
+
+
+@dataclass(frozen=True)
+class SemanticCacheState:
+    """Requested and effective containment state owned by the cache service."""
+
+    requested: bool
+    effective: bool
+    disabled_reason: SemanticCacheDisabledReason | None
+
+    def __post_init__(self) -> None:
+        if self.effective and not self.requested:
+            raise ValueError("Effective semantic caching must be requested")
+        if self.effective and self.disabled_reason is not None:
+            raise ValueError("Effective semantic caching cannot have a disabled reason")
+        if not self.effective and self.disabled_reason is None:
+            raise ValueError("Ineffective semantic caching requires a disabled reason")
+
+    @classmethod
+    def enabled(cls) -> SemanticCacheState:
+        """Return the single valid effective state."""
+        return cls(requested=True, effective=True, disabled_reason=None)
+
+    @classmethod
+    def disabled(
+        cls,
+        reason: SemanticCacheDisabledReason,
+        *,
+        requested: bool = False,
+    ) -> SemanticCacheState:
+        """Return an explicitly ineffective state."""
+        return cls(
+            requested=requested,
+            effective=False,
+            disabled_reason=reason,
+        )
+
+
+@dataclass(frozen=True)
+class SemanticCacheOutcome:
+    """Host-side result plus whether containment supplied it."""
+
+    result: SemanticResult
+    cache_hit: bool
+
+
+class SemanticCacheMetrics(Protocol):
+    """Fixed-name metrics used by containment cache operations."""
+
+    def incr(self, key: str) -> None: ...  # pragma: no cover
+
+    def gauge(self, key: str, value: float) -> None: ...  # pragma: no cover
+
+
+SEMANTIC_CACHE_METRIC_PREFIX: str = "semantic_cache.containment"
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+class SafeSemanticCacheBackend:
+    """Translate pluggable cache-client failures into the repository boundary."""
+
+    def __init__(self, backend: SemanticCacheBackend) -> None:
+        self._backend: SemanticCacheBackend = backend
+
+    def get(self, key: str) -> object | None:
+        try:
+            return self._backend.get(key)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache get failed") from ex
+
+    def set(
+        self,
+        key: str,
+        value: object,
+        timeout: int | None = None,
+    ) -> bool:
+        try:
+            return self._backend.set(key, value, timeout=timeout)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache set failed") from ex
+
+    def delete(self, key: str) -> bool:
+        try:
+            return self._backend.delete(key)
+        except Exception as ex:  # pylint: disable=broad-exception-caught
+            raise SemanticCacheBackendError("Semantic cache delete failed") from ex
+
+
+class SemanticCacheService:
+    """Orchestrate optional cache lookup, provider execution, and storage.
+
+    This service is intentionally limited to application flow. Cache identity,
+    containment proofs, result transformation, persistence, distributed mutation,
+    and Superset host adaptation live in ``cache_identity``, ``cache_policy``,
+    ``cache_transform``, ``cache_repository``, ``cache_coordination``, and
+    ``cache_host`` respectively. Keeping those decisions behind narrow boundaries
+    prevents the orchestration service from becoming a multipurpose cache class.
+    """
+
+    def __init__(
+        self,
+        state: SemanticCacheState,
+        repository: SemanticCacheRepository | None = None,
+        metrics: SemanticCacheMetrics | None = None,
+    ) -> None:
+        if state.effective and repository is None:
+            raise ValueError("Effective semantic caching requires a repository")
+        self.state: SemanticCacheState = state
+        self._repository: SemanticCacheRepository | None = repository
+        self._metrics: SemanticCacheMetrics | None = metrics
+
+    def _increment(self, suffix: str) -> None:
+        metrics: SemanticCacheMetrics | None = self._metrics
+        if metrics is None:
+            return
+        try:
+            metrics.incr(f"{SEMANTIC_CACHE_METRIC_PREFIX}.{suffix}")
+        except Exception:  # pylint: disable=broad-exception-caught
+            logger.debug("Semantic cache metric emission failed", exc_info=True)
+
+    @classmethod
+    def default_ineffective(cls) -> SemanticCacheService:
+        """Build the safe process default used before capability initialization."""
+        return cls(SemanticCacheState.disabled(SemanticCacheDisabledReason.FLAG_OFF))
+
+    def execute(
+        self,
+        meta: ViewMeta,
+        query: SemanticQuery,
+        provider: Callable[[SemanticQuery], SemanticResult],
+        *,
+        capabilities: ContainmentCapabilities,
+        force: bool = False,
+    ) -> SemanticCacheOutcome:
+        """Serve a proven hit or execute and best-effort store provider output."""
+        repository: SemanticCacheRepository | None = self._repository
+        if not self.state.effective or repository is None:
+            self._increment("bypass")
+            return SemanticCacheOutcome(provider(query), cache_hit=False)
+        if not force:
+            try:
+                lookup_result: SemanticCacheLookupResult = repository.lookup(
+                    meta, query, capabilities
+                )
+            except SemanticCacheLookupError:
+                self._increment("lookup_failure")
+                return SemanticCacheOutcome(provider(query), cache_hit=False)
+            for candidate in lookup_result.candidates:
+                try:
+                    transformed: SemanticResult = transform_result(
+                        candidate.result,
+                        query,
+                        candidate.decision,
+                        capabilities,
+                    )
+                except SemanticCacheTransformationError:
+                    self._increment("transform_failure")
+                    continue
+                self._increment("hit")
+                return SemanticCacheOutcome(transformed, cache_hit=True)
+            try:
+                repository.prune_missing(
+                    meta,
+                    lookup_result.missing_value_keys,
+                )
+            except SemanticCacheLookupError:
+                self._increment("prune_failure")
+            self._increment("miss")
+        else:
+            self._increment("bypass")
+        result: SemanticResult = provider(query)
+        try:
+            repository.store(meta, query, result)

Review Comment:
   Confirmed and fixed in `e5d5077568` — and your instinct here was better than reported: the crash escapes the transformation-error boundary entirely (`AttributeError` was not in the caught tuple), so the second request against an empty result 500'd rather than missing. Two changes: normalization now happens **before** the store (the dispatcher is wrapped, so both the cached copy and the direct path see a coerced empty Arrow table), and `transform_result` treats `AttributeError` as an incompatible-entry miss so any entry stored by a pre-fix build degrades gracefully. Two regression tests: `test_none_results_are_normalized_before_store` and `test_poisoned_none_entry_degrades_to_miss` — the latter's control run reproduces the exact `AttributeError` at `cache_transform.py:203` against the previous code.
   
   *Fix authored with AI assistance; verified as described.*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5480724471

   Hold rescinded — the stacking/timing concern it covered is resolved (#42839 merged, the legacy stack #41824/#41825/#41826/#41856/#42117 is closed, and #40221 closes with this comment's sibling). Every real check is green at `34fa8f6f57`; the only red in the rollup was the hold-label check itself. @rusackas this just needs the merge click — both approvals (yours + sha174n's) stand, and the three post-approval commits are the hardening items described in the comments above.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4032844751


##########
docs/developer_docs/extensions/contribution-types.md:
##########
@@ -291,3 +291,112 @@ class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
 - **Host context**: Original ID used as-is
 
 The decorator registers the class in the semantic layers registry, making it available in the UI for users to create connections. The `configuration_class` should be a Pydantic model that defines the fields needed to connect (credentials, project, database, etc.). Superset uses the model's JSON schema to render the configuration form dynamically.
+
+#### Semantic result containment caching
+
+Superset containment caching is experimental and off by default. A provider must
+explicitly opt in; the safe defaults leave caching with the provider and scope
+results to an execution context:
+
+```python
+from superset_core.semantic_layers.layer import (
+    SemanticCacheCapabilities,
+    SemanticCacheExecutionContext,
+    SemanticCacheIdentityMaterial,
+    SemanticCacheResponsibility,
+    SemanticCacheScope,
+)
+
+class MySemanticLayer(SemanticLayer[MyConfig, MySemanticView]):
+    semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
+    semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
+    semantic_cache_capabilities = SemanticCacheCapabilities(
+        comparisons=True,
+        membership=True,
+        nulls=True,
+        pattern_escape="\\",
+    )
+
+    def get_semantic_cache_provider_identity(self) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial(
+            {"provider_version": "v1", "catalog": self.config.catalog}
+        )
+
+    def get_semantic_cache_context_identity(
+        self,
+        context: SemanticCacheExecutionContext,
+    ) -> SemanticCacheIdentityMaterial:
+        return SemanticCacheIdentityMaterial({"tenant": self.tenant_id(context)})
+```
+
+Identity material must be secret-free and include every provider setting that can
+change results. For execution-context scope, Superset also hashes the principal,
+roles, guest-token claims, and row-level-security cache key. Returning `None` from
+either identity method bypasses containment. Use `GLOBAL` only when results are
+provably identical across principals and tenants; containment is bypassed for a
+`GLOBAL` view whenever Superset row-level security applies to the request, since
+that variation is invisible to the provider. Declare only filter capabilities
+whose provider semantics exactly match Superset's post-processing semantics.
+
+Operators enable both `SEMANTIC_LAYERS` and the development feature flag
+`SEMANTIC_LAYER_CONTAINMENT_CACHE`, and configure two backends:
+
+- `DATA_CACHE_CONFIG` holds the cached results and their descriptors. It must be
+  a persistent cache shared by every web and worker process, such as `RedisCache`.
+  The default `NullCache` discards every value, so containment would only ever
+  miss; `RedisSentinelCache` reads from replicas that can lag the master. Both
+  disable containment at startup rather than run it ineffectively.
+- `DISTRIBUTED_COORDINATION_CONFIG` must select `RedisCache` or
+  `RedisSentinelCache`; containment requires its atomic owner-token lease
+  operations.
+
+```python
+DATA_CACHE_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_DEFAULT_TIMEOUT": 86400,
+    "CACHE_KEY_PREFIX": "superset_results",
+    "CACHE_REDIS_URL": "redis://redis:6379/1",
+}
+DISTRIBUTED_COORDINATION_CONFIG = {
+    "CACHE_TYPE": "RedisCache",
+    "CACHE_REDIS_URL": "redis://redis:6379/2",

Review Comment:
   This configuration uses `CACHE_REDIS_URL`, but the coordination backend reads only `CACHE_REDIS_HOST`, `CACHE_REDIS_PORT`, and `CACHE_REDIS_DB`. An operator copying it therefore connects to the default local Redis instead of database 2, which disables cross-process coordination. Could this example use the supported host/port/DB settings (or teach the backend to parse the URL)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42760:
URL: https://github.com/apache/superset/pull/42760#discussion_r4033085735


##########
superset/common/query_context_processor.py:
##########
@@ -241,6 +241,12 @@ def get_df_payload_result(
             self._resolve_forced_query(query_obj, cache_key)
             or timeout == CACHE_DISABLED_TIMEOUT
         )
+        if query_obj:
+            # Datasources that run their own caching (semantic containment)
+            # must honor the same resolved chart/custom timeout and force
+            # decision as the result cache, not the datasource-level default.
+            query_obj.force_query = force_query

Review Comment:
   Contribution totals bypass `get_df_payload_result` and dispatch directly from `ensure_totals_available`, so this resolved force/timeout state is never applied to their query. A contribution chart with `cache_timeout=-1` can therefore use a cached totals denominator while its main query bypasses caching. Could the same resolved values be applied before the totals dispatch?



##########
superset/charts/schemas.py:
##########
@@ -1806,6 +1807,17 @@ class ChartDataResponseResult(Schema):
         required=True,
         allow_none=None,
     )
+    semantic_cache_status: fields.String = fields.String(

Review Comment:
   This unconditional response field is absent from `docs/static/resources/openapi.json`. The required OpenAPI drift workflow regenerates that file and will detect the change, leaving generated clients without the new response property. Could the generated spec be refreshed with this schema change?



##########
superset/semantic_layers/mapper.py:
##########
@@ -147,8 +191,24 @@ def get_results(query_object: QueryObject) -> QueryResult:
 
     # Step 2: Execute the main query (first in the list)
     main_query = queries[0]
-    main_result = dispatcher(main_query)
+    main_outcome: SemanticCacheOutcome = _dispatch_semantic_query(
+        query_object.datasource,
+        dispatcher,
+        main_query,
+        force=query_object.force_query,
+        # Row-count results share the query's logical identity but not its
+        # shape: a cached table result would satisfy a row-count lookup (and
+        # vice versa) and break server-side pagination. Containment reuse is
+        # only defined over tabular results, so row-count dispatches bypass
+        # the cache entirely.
+        cacheable=not query_object.is_rowcount,

Review Comment:
   Only row-count queries bypass storage here; server-paginated data pages with a nonzero `row_offset` are still stored. `select_reuse` rejects every descriptor whose query or entry offset is nonzero, so those pages can never be reused and repeated pages evict usable zero-offset descriptors from the 128-entry bucket. Could offset pages bypass containment as well?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5446160779

   Rebased onto master `0597f36bb6` (@rusackas — two additive collisions: `docs/static/feature-flags.json`, regenerated from `config.py`; and `QueryResult.__init__`, where master added `sql_shifted_temporal_labels` next to our field) and addressed @sadpandajoe's three findings — replies inline. Head is `7eb97a33a3`.
   
   One API-shape change to flag for anyone tracking the response: the per-query field is renamed `semantic_cache_hit: bool` → `semantic_cache_status: "HIT" | "MISS" | "MIXED"` so a time-comparison chart can report mixed provenance. The header vocabulary is unchanged.
   
   @rusackas — the CI nit was already handled before this round: `scripts/change_detector.py` has a `semantic-layers` pattern set and `test-semantic-cache-coordination` gates on it, so it runs only when `superset/semantic_layers/`, `superset-core/.../semantic_layers/`, their tests, or the workflow itself change.
   
   Verification: the affected unit suites pass locally (semantic_layers, query cache manager, query context processor, chart-data API, initialization — 754 tests, 17 new); frontend type check, ChartPills jest, oxlint, ruff, mypy, and pylint are clean.
   
   *Fixes and write-up produced with AI assistance (Claude); verified locally as described.*
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-6135164133

   Merged master again after #45061 and #44028. The release-note conflict retains both entries; the runtime semantic-layer gates, dashboard layout changes, cache provenance and initialization changes coexist in the merged tree. OpenAPI regeneration matches the checked-in specification.
   
   Validation: 1,543 focused Python tests and 18 frontend tests passed. Tests in the incoming changed Python files had 778 passes and two documented local Europe/Dublin timezone failures. Branch-file hooks passed. Codex prepared and validated the merge; an independent Claude review covered the cache/runtime-gate interactions, changed fixtures and full branch Python annotations.
   
   Pushed af6c876aa1; GitHub reports MERGEABLE. Normal pre-push checks, including coverage gates, passed. CI is running; labels and readiness were left unchanged.
   
   The independent review identified one non-blocking follow-up: containment still evaluates its parent `SEMANTIC_LAYERS` flag at process startup. If it is off at startup and enabled later through a runtime hook, semantic queries run but containment stays off. This fails safe by querying the provider; activation behavior should be aligned or explicitly documented before readiness. Claude approved the exact merge tree for push with this follow-up recorded.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5457700099

   One more commit, `34fa8f6f57`, closing three items from a fresh multi-lens pass over the post-approval delta:
   
   - **Freshness bound.** Lookup (and the store dedupe) now honor the *requesting* chart's resolved timeout. Per-request timeouts (`f0e9e32685`) had let a value stored by a 3600 s chart answer a 60 s chart on the same view for the value's whole life — the old last-writer bucket TTL was bounding that by accident and `7eb97a33a3` removed the accident. A short-lived registration also no longer pins a longer-lived chart to its entry.
   - **Secret-like identity material → bypass, not failure.** `SensitiveIdentityMaterialError` was raised from `build_cache_configuration`, ahead of the cache service's exception boundary, so a provider returning e.g. `{"tenant_token_version": 1}` would have failed every chart on that view once the flag is on. It now costs a containment bypass with a warning naming the view (not the material); covered at the host and mapper level.
   - **CI scoping.** `scripts/change_detector.py`'s `semantic-layers` pattern now includes `superset/async_events/cache_backend.py` and `superset/utils/cache_manager.py` — the owner-token lease code the real Redis/Sentinel job exists to test — so a Lua-script edit can't skip it (@rusackas, follow-on to your CI-scope nit).
   
   No behaviour change for correctly configured deployments beyond the freshness bound. Semantic-layers coverage still 100%.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(semantic-layers): add safe containment result cache [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #42760:
URL: https://github.com/apache/superset/pull/42760#issuecomment-5446251127

   One more commit on top, `b015734d50`, from the same data-systems pass — four hardening items, none of which changed behaviour for correct configurations: containment now honors `DATA_CACHE_MAX_VALUE_SIZE` (oversized results are served, not stored; `store_skipped` metric), a herd of identical misses stores once instead of once per request and the lease spin is jittered, `GLOBAL` scope bypasses containment whenever a Superset RLS key applies (semantic views don't support RLS yet; this closes the gap before they do), and a descriptor pickled by an older `CachedEntry` shape now costs one miss rather than a lookup failure until it expires, with a test pinning the shape to `IDENTITY_FORMAT_VERSION`. Docs updated for the cap, the metric, and the RLS rule.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org