bito-code-review[bot] commented on code in PR #44835:
URL: https://github.com/apache/superset/pull/44835#discussion_r4191972327


##########
superset/semantic_layers/metadata.py:
##########
@@ -0,0 +1,470 @@
+# 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.
+
+"""Scoped publication and invalidation of provider-owned metadata."""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import math
+import time
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from decimal import InvalidOperation
+from typing import Literal, Protocol, TYPE_CHECKING
+from uuid import uuid4
+
+from redis.exceptions import RedisError
+from superset_core.semantic_layers.metadata import (
+    CatalogLoader,
+    CatalogSnapshot,
+    MetadataRefreshError,
+    MetadataRefreshResult,
+    remaining_budget,
+)
+
+from superset.semantic_layers.cache_inspection import CacheEntryInfo, 
describe_entry
+from superset.utils import json
+
+CATALOG_TTL_SECONDS: int = 300
+MAX_SNAPSHOT_TTL_SECONDS: int = 2**31 - 1
+REFRESH_LEASE_SECONDS: int = 60
+FETCH_DEADLINE_SECONDS: int = 30
+MAX_CATALOG_BYTES: int = 10 * 1024 * 1024
+SNAPSHOT_FORMAT_VERSION: int = 2
+READER_POLL_SECONDS: float = 0.05
+
+
+if TYPE_CHECKING:
+
+    class PublicationBackend(Protocol):
+        """The shared coordinator operations used by semantic metadata."""
+
+        def with_deadline(self, deadline: float) -> PublicationBackend: ...
+        def get(self, name: str) -> bytes | None: ...
+        def set(
+            self,
+            name: str,
+            value: str,
+            ex: int | None = None,
+            px: int | None = None,
+            nx: bool = False,
+            xx: bool = False,
+        ) -> bool | None: ...
+        def delete(self, *names: str) -> int: ...
+        def compare_and_delete(self, name: str, expected: str) -> int: ...
+        def compare_and_publish(
+            self,
+            lease_key: str,
+            expected: str,
+            snapshot_key: str,
+            value: str,
+            ttl_ms: int,
+            lease_ttl_ms: int,
+            snapshot_ttl_ms: int,
+        ) -> bool: ...
+        def get_with_ttl(self, name: str) -> tuple[bytes | None, int]: ...
+        def get_or_create(self, name: str, value: str, ttl: int) -> bytes: ...
+
+
+def metadata_scope(
+    secret: str, namespace: str, connection_uuid: str, configuration: str
+) -> str:
+    """Derive a private identity from trusted deployment, tenant and 
connection data."""
+    if not secret or not namespace or not connection_uuid:
+        raise MetadataRefreshError("configuration")
+    try:
+        canonical: str = json.dumps(
+            [namespace, connection_uuid, json.loads(configuration)],
+            sort_keys=True,
+            separators=(",", ":"),
+            allow_nan=False,
+        )
+    except (TypeError, ValueError):
+        raise MetadataRefreshError("configuration") from None
+    return hmac.new(secret.encode(), canonical.encode(), 
hashlib.sha256).hexdigest()
+
+
+@dataclass(frozen=True)
+class StoredCatalog:
+    """Internal envelope; publication bookkeeping is never a provider 
revision."""
+
+    snapshot: CatalogSnapshot
+    digest: str = field(repr=False)
+    attempt: str = field(repr=False)
+    created_at: str
+
+
+class ScopedMetadataStore:
+    """One shared observation with a request-wide budget and no local 
fallback."""
+
+    def __init__(
+        self,
+        backend: PublicationBackend,
+        scope: str,
+        *,
+        deadline: float,
+        snapshot_ttl_seconds: int = CATALOG_TTL_SECONDS,
+        before_publish: Callable[[], None] | None = None,
+        clock: Callable[[], float] = time.monotonic,
+        wait: Callable[[float], None] = time.sleep,
+    ) -> None:
+        if not math.isfinite(deadline) or not scope or "{" in scope or "}" in 
scope:
+            raise MetadataRefreshError("configuration")
+        if (
+            isinstance(snapshot_ttl_seconds, bool)
+            or not isinstance(snapshot_ttl_seconds, int)
+            or not 1 <= snapshot_ttl_seconds <= MAX_SNAPSHOT_TTL_SECONDS
+        ):
+            raise MetadataRefreshError("configuration")
+        self._snapshot_ttl_seconds: int = snapshot_ttl_seconds
+        self._backend: PublicationBackend = backend
+        self._scope: str = scope
+        self._deadline: float = deadline
+        self._lease_key: str = f"semantic-metadata:{{{scope}}}:lease"
+        self._snapshot_key: str = f"semantic-metadata:{{{scope}}}:snapshot"
+        self._generation_key: str = 
f"semantic-metadata:{{{scope}}}:compatibility"
+        self._before_publish: Callable[[], None] | None = before_publish
+        self._clock: Callable[[], float] = clock
+        self._wait: Callable[[float], None] = wait
+        self._observations: dict[str, str] = {}
+
+    def _remaining(self) -> float:
+        return remaining_budget(self._deadline, now=self._clock())
+
+    def _decode(self, raw: bytes | None) -> StoredCatalog | None:
+        if raw is None or len(raw) > MAX_CATALOG_BYTES:
+            return None
+        try:
+            envelope: object = json.loads(raw)
+            if (
+                not isinstance(envelope, dict)
+                or envelope.get("version") != SNAPSHOT_FORMAT_VERSION
+            ):
+                return None
+            if any(
+                not isinstance(envelope.get(key), str)
+                for key in (
+                    "payload",
+                    "cache_token",
+                    "observed_at",
+                    "digest",
+                    "attempt",
+                    "created_at",
+                )
+            ):
+                return None
+            if any(
+                not envelope[key]
+                for key in (
+                    "cache_token",
+                    "observed_at",
+                    "digest",
+                    "attempt",
+                    "created_at",
+                )
+            ) or not envelope["cache_token"].startswith(f"{self._scope}:"):
+                return None
+            payload: str = envelope["payload"]
+            json.loads(payload, use_decimal=True)
+            if hashlib.sha256(payload.encode()).hexdigest() != 
envelope["digest"]:
+                return None
+            return StoredCatalog(
+                CatalogSnapshot(
+                    payload, envelope["cache_token"], envelope["observed_at"]
+                ),
+                envelope["digest"],
+                envelope["attempt"],
+                envelope["created_at"],
+            )
+        except (ValueError, UnicodeError, RecursionError, InvalidOperation):
+            return None
+
+    def _load(self) -> StoredCatalog | None:
+        self._remaining()
+        stored: StoredCatalog | None = self._decode(
+            self._backend.get(self._snapshot_key)
+        )
+        self._remaining()
+        return stored
+
+    def _remember(self, snapshot: CatalogSnapshot) -> CatalogSnapshot:
+        self._observations[snapshot.cache_token] = snapshot.observed_at
+        return snapshot
+
+    def observed_at(self, token: str) -> str | None:
+        """Read the timestamp captured with a provider's token, without 
backend I/O."""
+        return (
+            self._observations.get(token)
+            if token.startswith(f"{self._scope}:")
+            else None
+        )
+
+    def peek(self) -> CatalogSnapshot | None:
+        """Read the current observation without acquiring, filling or renewing 
it."""
+        try:
+            stored: StoredCatalog | None = self._load()
+        except RedisError:
+            raise MetadataRefreshError("unavailable") from None
+        return stored.snapshot if stored is not None else None
+
+    def _for_deadline(self, deadline: float) -> ScopedMetadataStore:
+        """Narrow one call without mutating the operation or another call's 
budget."""
+        remaining_budget(deadline, now=self._clock())
+        if deadline > self._deadline:
+            raise MetadataRefreshError("deadline")
+        scoped: ScopedMetadataStore = ScopedMetadataStore(
+            self._backend.with_deadline(deadline),
+            self._scope,
+            deadline=deadline,
+            snapshot_ttl_seconds=self._snapshot_ttl_seconds,
+            before_publish=self._before_publish,
+            clock=self._clock,
+            wait=self._wait,
+        )
+        scoped._observations = self._observations
+        return scoped
+
+    def read(self, fetch: CatalogLoader, *, deadline: float) -> 
CatalogSnapshot:
+        """Honor the explicit caller budget, including cache hits and 
transport."""
+        return self._for_deadline(deadline)._read(fetch)
+
+    def refresh(
+        self, fetch: CatalogLoader, *, deadline: float
+    ) -> MetadataRefreshResult:
+        """Publish within the caller budget, which cannot extend the host 
operation."""
+        return self._for_deadline(deadline)._refresh(fetch)
+
+    def _read(self, fetch: CatalogLoader) -> CatalogSnapshot:
+        """Wait for an owner or acquire once using the same remaining request 
budget."""
+        try:
+            while True:
+                current: StoredCatalog | None = self._load()
+                if current is not None:
+                    return self._remember(current.snapshot)
+                attempt: str = uuid4().hex
+                lease_ttl_ms: int = max(
+                    1, math.ceil(min(REFRESH_LEASE_SECONDS, self._remaining()) 
* 1000)
+                )

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Duplicated lease TTL derivation</b></div>
   <div id="fix">
   
   The lease-TTL derivation `max(1, math.ceil(min(REFRESH_LEASE_SECONDS, 
self._remaining()) * 1000))` now appears identically in `_read` (262-264) and 
`_refresh` (288-290). Both values feed `compare_and_publish` lease-age fencing 
(`lease_ttl_ms - lease_remaining` in `_COMPARE_AND_PUBLISH_LUA`); editing one 
site without the other silently corrupts the freshness computation. Extract a 
shared `_lease_ttl_ms()` helper.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c70cfc</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/common/query_context_processor.py:
##########
@@ -447,7 +480,49 @@ def query_cache_key(self, query_obj: QueryObject, 
**kwargs: Any) -> str | None:
             if query_obj
             else None
         )
-        return cache_key
+        return cache_key, cacheable
+
+    def _capture_annotation_metadata(self, query_obj: QueryObject) -> None:
+        """Capture authorized annotation views on a miss before a slow parent 
query."""
+        if not query_obj.annotation_layers:
+            return
+        from superset.semantic_layers.metadata_binding import (
+            metadata_refresh_enabled,
+            participates,
+        )
+        from superset.semantic_layers.models import SemanticView
+
+        if not metadata_refresh_enabled():
+            return
+        layer: dict[str, Any]
+        for layer in query_obj.annotation_layers:
+            if (
+                layer.get("sourceType")
+                not in ANNOTATION_SOURCE_TYPES_WITH_CHART_REFERENCE
+            ):
+                continue
+            value: int | str | None = layer.get("value")
+            chart: Slice | None = (
+                ChartDAO.find_by_id(value) if value is not None else None
+            )
+            source: Datasource | None = chart.resolved_datasource if chart 
else None
+            if not isinstance(source, SemanticView) or not participates(
+                source.semantic_layer
+            ):
+                continue
+            assert chart is not None
+            try:
+                context: QueryContext | None = chart.get_query_context()
+                if context is None:
+                    # The annotation executor reports its missing-context 
error.
+                    continue
+                context.raise_for_access()
+                if isinstance(context.datasource, SemanticView):
+                    # Reuse the annotation command's canonical query authority.
+                    # Later execution retains this view without renewing its 
budget.
+                    _captured: str | None = 
context.datasource.metadata_cache_token
+            except SupersetException as ex:
+                raise QueryObjectValidationError(error_msg_from_exception(ex)) 
from ex

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>MetadataRefreshError escapes handler</b></div>
   <div id="fix">
   
   `participates()` (metadata_binding.py:159) and 
`SemanticView.metadata_cache_token` (models.py:734) raise 
`MetadataRefreshError`, which derives from plain `Exception`, not 
`SupersetException` — so neither this `except` nor the caller's `except 
QueryObjectValidationError` (line 326) catches it; a misconfigured view turns 
the render into an unhandled 500. `annotation_cache_token` already handles this 
error (metadata_cache.py:63); mirror that here.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c70cfc</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



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