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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to