You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by vi...@apache.org on 2026/08/21 22:53:23 UTC
(superset) branch gaq-to-gtf updated: refactor(coordination): centralize distributed coordination in a single service (#43316)
This is an automated email from the ASF dual-hosted git repository.
villebro pushed a commit to branch gaq-to-gtf
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/gaq-to-gtf by this push:
new 78536bb0187 refactor(coordination): centralize distributed coordination in a single service (#43316)
78536bb0187 is described below
commit 78536bb01877fff639b801d801e1448b92e8bf1b
Author: Ville Brofeldt <33...@users.noreply.github.com>
AuthorDate: Fri Aug 21 15:53:17 2026 -0700
refactor(coordination): centralize distributed coordination in a single service (#43316)
---
UPDATING.md | 1 +
docs/admin_docs/configuration/cache.mdx | 7 +-
superset/async_events/async_query_manager.py | 137 ++++--
superset/commands/distributed_lock/acquire.py | 16 +-
superset/commands/distributed_lock/base.py | 17 +-
superset/commands/distributed_lock/release.py | 17 +-
superset/config.py | 49 +-
superset/coordination/__init__.py | 39 ++
superset/coordination/base.py | 380 +++++++++++++++
superset/coordination/exceptions.py | 31 ++
superset/coordination/types.py | 72 +++
superset/coordination/utils.py | 40 ++
superset/tasks/context.py | 4 +-
superset/tasks/manager.py | 517 ++-------------------
tests/integration_tests/async_events/api_tests.py | 14 +-
.../integration_tests/tasks/async_queries_tests.py | 42 +-
.../integration_tests/tasks/test_sync_join_wait.py | 6 +-
.../async_events/async_query_manager_tests.py | 105 +++--
tests/unit_tests/coordination/__init__.py | 16 +
tests/unit_tests/coordination/test_service.py | 240 ++++++++++
.../distributed_lock/distributed_lock_tests.py | 95 ++--
tests/unit_tests/tasks/test_handlers.py | 8 +-
tests/unit_tests/tasks/test_manager.py | 479 ++++++-------------
tests/unit_tests/tasks/test_timeout.py | 64 +--
24 files changed, 1322 insertions(+), 1074 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index a4adec96cf3..3b7bc65ade4 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -61,6 +61,7 @@ the old counter to use the outcome-specific replacements.
- [42393](https://github.com/apache/superset/pull/42393): Exported dataset YAML now carries a `uuid` for each metric and column so that custom folder assignments (which reference metrics/columns by UUID) survive an import into another workspace. This affects any export bundle that contains datasets, not just a dataset export: chart, dashboard, database and full-asset exports all embed the same dataset YAML, so a dashboard exported from this release also fails to import into an older one [...]
- [42300](https://github.com/apache/superset/pull/42300): Timeseries charts (line/area/bar) with a Y-axis bound in effect — either an explicit `yAxisBounds` or one derived from `truncateYAxis` — now clamp out-of-range data points to that bound instead of letting ECharts drop the point (and the line segments around it) entirely. Any existing chart with a configured Y-axis bound and data outside it will look different after upgrading: a gap becomes a point pinned to the boundary. The clamp [...]
- [42087](https://github.com/apache/superset/pull/42087): Stored calculated-column and metric expressions are validated when a query is built, under the same sub-query policy already applied to adhoc expressions. Previously only the dataset update path checked them on save, so expressions written by v1 import, by dataset duplication, or before that check existed were never validated. Since `ALLOW_ADHOC_SUBQUERY` defaults to `False` (see [19242](https://github.com/apache/superset/pull/192 [...]
+- The `GLOBAL_ASYNC_QUERIES_CACHE_BACKEND` config key is **deprecated** in favor of the shared coordination backend `DISTRIBUTED_COORDINATION_CONFIG`, which powers a single Redis connection for distributed locks, pub/sub, and the async-events streams (the GAQ firehose). All parameters previously accepted by `GLOBAL_ASYNC_QUERIES_CACHE_BACKEND` are supported identically under `DISTRIBUTED_COORDINATION_CONFIG` (they use the same `RedisCache`/`RedisSentinelCache` backend). During the deprec [...]
### Selenium support removed — Playwright is now required for screenshots
diff --git a/docs/admin_docs/configuration/cache.mdx b/docs/admin_docs/configuration/cache.mdx
index efb2587646e..022a93becba 100644
--- a/docs/admin_docs/configuration/cache.mdx
+++ b/docs/admin_docs/configuration/cache.mdx
@@ -345,9 +345,10 @@ DISTRIBUTED_COORDINATION_CONFIG = {
}
```
-By default, connections opened for `DISTRIBUTED_COORDINATION_CONFIG` (as well as
-`GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`, which uses the same `RedisCache`/`RedisSentinelCache`
-backend) have no socket timeout. This can be overridden with `CACHE_REDIS_SOCKET_TIMEOUT` and
+By default, connections opened for `DISTRIBUTED_COORDINATION_CONFIG` (as well as the
+deprecated `GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`, which uses the same
+`RedisCache`/`RedisSentinelCache` backend) have no socket timeout. This can be
+overridden with `CACHE_REDIS_SOCKET_TIMEOUT` and
`CACHE_REDIS_SOCKET_CONNECT_TIMEOUT`, both in seconds:
```python
diff --git a/superset/async_events/async_query_manager.py b/superset/async_events/async_query_manager.py
index 2642e2b4b05..bdf94c4fb45 100644
--- a/superset/async_events/async_query_manager.py
+++ b/superset/async_events/async_query_manager.py
@@ -25,12 +25,12 @@ from typing import Any, Literal, Optional, TYPE_CHECKING
import jwt
from flask import Flask, Request, request, Response, session
-from flask_caching.backends.base import BaseCache
from superset.async_events.cache_backend import (
RedisCacheBackend,
RedisSentinelCacheBackend,
)
+from superset.coordination.base import CoordinationService
from superset.utils import json
from superset.utils.core import get_user_id
@@ -87,6 +87,12 @@ def increment_id(entry_id: str) -> str:
def get_cache_backend(
config: dict[str, Any],
) -> RedisCacheBackend | RedisSentinelCacheBackend:
+ """Build a coordination backend from the deprecated GAQ cache config.
+
+ DEPRECATED: retained only so Global Async Queries can run on its own dedicated
+ ``GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`` during the deprecation window. Removed in
+ Superset 8.0, when GAQ moves onto ``DISTRIBUTED_COORDINATION_CONFIG``.
+ """
cache_config = config.get("GLOBAL_ASYNC_QUERIES_CACHE_BACKEND", {})
cache_type = cache_config.get("CACHE_TYPE")
@@ -96,7 +102,6 @@ def get_cache_backend(
if cache_type == "RedisSentinelCache":
return RedisSentinelCacheBackend.from_config(cache_config)
- # TODO: Expand cache backend options.
raise UnsupportedCacheBackendError("Unsupported cache backend configuration")
@@ -110,13 +115,18 @@ class AsyncQueryManager:
# Redis key prefix (within the GAQ stream namespace) for the per-job record
# that authorizes cancellation and flags a job as cancelled for the worker.
_JOB_REGISTRY_PREFIX = "job-cancel:"
+ # Emit the dedicated-backend deprecation notice at most once per process.
+ _legacy_backend_warning_emitted: bool = False
def __init__(self) -> None:
super().__init__()
- self._cache: Optional[BaseCache] = None
self._stream_prefix: str = ""
self._stream_limit: Optional[int]
self._stream_limit_firehose: Optional[int]
+ # Global Async Queries owns its coordination backend separately from the
+ # shared coordinator (see init_app); resolved there and passed explicitly
+ # to CoordinationService's primitives.
+ self._gaq_backend: RedisCacheBackend | RedisSentinelCacheBackend | None = None
self._jwt_cookie_name: str = ""
self._jwt_cookie_secure: bool = False
self._jwt_cookie_domain: Optional[str]
@@ -137,8 +147,42 @@ class AsyncQueryManager:
"""
)
- self._cache = get_cache_backend(app.config)
- logger.debug("Using GAQ Cache backend as %s", type(self._cache).__name__)
+ if not (
+ app.config.get("DISTRIBUTED_COORDINATION_CONFIG")
+ or app.config.get("GLOBAL_ASYNC_QUERIES_CACHE_BACKEND", {}).get(
+ "CACHE_TYPE"
+ )
+ ):
+ raise UnsupportedCacheBackendError(
+ "Global async queries require a coordination backend; configure "
+ "DISTRIBUTED_COORDINATION_CONFIG (GLOBAL_ASYNC_QUERIES_CACHE_BACKEND "
+ "is deprecated)."
+ )
+
+ # Global Async Queries share the coordinator's backend whenever
+ # DISTRIBUTED_COORDINATION_CONFIG is configured, so an 8.0-leaning deployment
+ # keeps a single coordination config rather than maintaining a separate one.
+ # Only when no coordinator is configured does GAQ fall back to its dedicated
+ # (deprecated) GLOBAL_ASYNC_QUERIES_CACHE_BACKEND, emitting a one-time
+ # deprecation warning. That dedicated backend is removed in Superset 8.0, when
+ # DISTRIBUTED_COORDINATION_CONFIG becomes the only option. Either way GAQ passes
+ # its resolved backend explicitly to CoordinationService's primitives, keeping
+ # its stream/pub-sub traffic scoped to the connection it resolved here.
+ if (coordinator := CoordinationService.get_backend()) is not None:
+ self._gaq_backend = coordinator
+ else:
+ if not AsyncQueryManager._legacy_backend_warning_emitted:
+ logger.warning(
+ "Global Async Queries is running on the deprecated "
+ "GLOBAL_ASYNC_QUERIES_CACHE_BACKEND because "
+ "DISTRIBUTED_COORDINATION_CONFIG is not configured. Configure "
+ "DISTRIBUTED_COORDINATION_CONFIG to consolidate coordination "
+ "(distributed locks, task framework, pub/sub, and the GAQ event "
+ "streams) onto a single connection; the dedicated backend is "
+ "removed in Superset 8.0."
+ )
+ AsyncQueryManager._legacy_backend_warning_emitted = True
+ self._gaq_backend = get_cache_backend(app.config)
if len(app.config["GLOBAL_ASYNC_QUERIES_JWT_SECRET"]) < 32:
raise AsyncQueryTokenException(
@@ -298,12 +342,17 @@ class AsyncQueryManager:
owner without trusting the client-supplied id. Expires with the JWT so
it never outlives the job it guards.
"""
- if not self._cache:
+ # The cancel registry is an optimization: skip it when GAQ has no
+ # coordination backend configured. When a backend is configured, a write
+ # failure is not swallowed here — it surfaces to the caller and fails job
+ # submission, matching the behavior of the surrounding stream writes.
+ if self._gaq_backend is None:
return
- self._cache.set(
+ CoordinationService.set_value(
self._job_registry_key(job_id),
json.dumps({"channel_id": channel_id, "user_id": user_id}),
- ex=self._jwt_expiration_seconds or None,
+ ttl=self._jwt_expiration_seconds or None,
+ backend=self._gaq_backend,
)
def submit_chart_data_job(
@@ -337,33 +386,32 @@ class AsyncQueryManager:
def read_events(
self, channel: str, last_id: Optional[str]
) -> list[Optional[dict[str, Any]]]:
- if not self._cache:
+ if self._gaq_backend is None:
raise CacheBackendNotInitialized("Cache backend not initialized")
stream_name = f"{self._stream_prefix}{channel}"
start_id = increment_id(last_id) if last_id else "-"
- results = self._cache.xrange(stream_name, start_id, "+", self.MAX_EVENT_COUNT)
- # Decode bytes to strings, decode_responses is not supported at RedisCache and RedisSentinelCache # noqa: E501
- if isinstance(self._cache, (RedisSentinelCacheBackend, RedisCacheBackend)):
- decoded_results = [
- (
- event_id.decode("utf-8"),
- {
- key.decode("utf-8"): value.decode("utf-8")
- for key, value in event_data.items()
- },
- )
- for event_id, event_data in results
- ]
- return (
- [] if not decoded_results else list(map(parse_event, decoded_results))
+ results = CoordinationService.stream_range(
+ stream_name, start_id, "+", self.MAX_EVENT_COUNT, backend=self._gaq_backend
+ )
+ # Decode bytes to strings: the coordination Redis backends do not enable
+ # decode_responses, so stream_range returns raw bytes.
+ decoded_results = [
+ (
+ event_id.decode("utf-8"),
+ {
+ key.decode("utf-8"): value.decode("utf-8")
+ for key, value in event_data.items()
+ },
)
- return [] if not results else list(map(parse_event, results))
+ for event_id, event_data in results
+ ]
+ return [] if not decoded_results else list(map(parse_event, decoded_results))
def update_job(
self, job_metadata: dict[str, Any], status: str, **kwargs: Any
) -> None:
- if not self._cache:
+ if self._gaq_backend is None:
raise CacheBackendNotInitialized("Cache backend not initialized")
if "channel_id" not in job_metadata:
@@ -388,10 +436,24 @@ class AsyncQueryManager:
# SIGUSR1 it is about to receive as a cancellation.
if status in (self.STATUS_DONE, self.STATUS_ERROR):
if job_id := job_metadata.get("job_id"):
- self._cache.delete(self._job_registry_key(job_id))
+ CoordinationService.delete_value(
+ self._job_registry_key(job_id), backend=self._gaq_backend
+ )
- self._cache.xadd(scoped_stream_name, event_data, "*", self._stream_limit)
- self._cache.xadd(full_stream_name, event_data, "*", self._stream_limit_firehose)
+ CoordinationService.stream_add(
+ scoped_stream_name,
+ event_data,
+ "*",
+ self._stream_limit,
+ backend=self._gaq_backend,
+ )
+ CoordinationService.stream_add(
+ full_stream_name,
+ event_data,
+ "*",
+ self._stream_limit_firehose,
+ backend=self._gaq_backend,
+ )
def is_job_cancelled(self, job_id: str) -> bool:
"""
@@ -401,10 +463,12 @@ class AsyncQueryManager:
swallowed and treated as "not cancelled" — a Redis blip must never mask
the original error (e.g. a genuine timeout) with a connection error.
"""
- if not self._cache:
+ if self._gaq_backend is None:
return False
try:
- raw = self._cache.get(self._job_registry_key(job_id))
+ raw = CoordinationService.get_value(
+ self._job_registry_key(job_id), backend=self._gaq_backend
+ )
if raw is None:
return False
return bool(json.loads(raw).get("cancelled"))
@@ -428,11 +492,11 @@ class AsyncQueryManager:
:raises AsyncQueryJobException: the job is unknown or already terminal
:raises AsyncQueryTokenException: the caller does not own the job
"""
- if not self._cache:
+ if self._gaq_backend is None:
raise CacheBackendNotInitialized("Cache backend not initialized")
key = self._job_registry_key(job_id)
- raw = self._cache.get(key)
+ raw = CoordinationService.get_value(key, backend=self._gaq_backend)
if raw is None:
raise AsyncQueryJobException("Job not found or already completed")
@@ -445,11 +509,12 @@ class AsyncQueryManager:
# key still exists (``xx``): if the job finished and cleared its record
# between the read above and here, don't recreate a stale record or
# revoke a task that is already gone — report it as not found instead.
- flagged = self._cache.set(
+ flagged = CoordinationService.set_value(
key,
json.dumps({**record, "cancelled": True}),
- ex=self._jwt_expiration_seconds or None,
- xx=True,
+ ttl=self._jwt_expiration_seconds or None,
+ if_present=True,
+ backend=self._gaq_backend,
)
if not flagged:
raise AsyncQueryJobException("Job not found or already completed")
diff --git a/superset/commands/distributed_lock/acquire.py b/superset/commands/distributed_lock/acquire.py
index 6cd9a878099..901dca4b7c4 100644
--- a/superset/commands/distributed_lock/acquire.py
+++ b/superset/commands/distributed_lock/acquire.py
@@ -27,8 +27,8 @@ from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from superset.commands.distributed_lock.base import (
BaseDistributedLockCommand,
get_default_lock_ttl,
- get_redis_client,
)
+from superset.coordination.base import CoordinationService
from superset.daos.key_value import KeyValueDAO
from superset.exceptions import (
AcquireDistributedLockFailedException,
@@ -80,21 +80,21 @@ class AcquireDistributedLock(BaseDistributedLockCommand):
self.ttl_seconds = ttl_seconds or get_default_lock_ttl()
def run(self) -> None:
- if (redis_client := get_redis_client()) is not None:
- self._acquire_redis(redis_client)
+ if CoordinationService.is_backend_defined():
+ self._acquire_redis()
else:
self._acquire_kv()
- def _acquire_redis(self, redis_client: Any) -> None:
- """Acquire lock using Redis SET NX EX (atomic)."""
+ def _acquire_redis(self) -> None:
+ """Acquire lock using the coordination backend's SET NX EX (atomic)."""
try:
# SET NX EX: Set if not exists, with expiration
# Returns True if lock acquired, None if already exists
- acquired = redis_client.set(
+ acquired = CoordinationService.set_value(
self.redis_lock_key,
"1",
- nx=True,
- ex=self.ttl_seconds,
+ ttl=self.ttl_seconds,
+ if_absent=True,
)
if not acquired:
diff --git a/superset/commands/distributed_lock/base.py b/superset/commands/distributed_lock/base.py
index 55da69f7ebd..a081df14dbb 100644
--- a/superset/commands/distributed_lock/base.py
+++ b/superset/commands/distributed_lock/base.py
@@ -19,18 +19,14 @@ from __future__ import annotations
import logging
import uuid
-from typing import Any, TYPE_CHECKING
+from typing import Any
from flask import current_app
from superset.commands.base import BaseCommand
from superset.distributed_lock.utils import get_key
-from superset.extensions import cache_manager
from superset.key_value.types import JsonKeyValueCodec, KeyValueResource
-if TYPE_CHECKING:
- import redis
-
logger = logging.getLogger(__name__)
@@ -39,17 +35,6 @@ def get_default_lock_ttl() -> int:
return int(current_app.config.get("DISTRIBUTED_LOCK_DEFAULT_TTL", 30))
-def get_redis_client() -> "redis.Redis[Any] | None":
- """
- Get Redis client from distributed coordination if available.
-
- Returns None if DISTRIBUTED_COORDINATION_CONFIG is not configured,
- allowing fallback to database-backed locking.
- """
- backend = cache_manager.distributed_coordination
- return backend._cache if backend else None
-
-
class BaseDistributedLockCommand(BaseCommand):
"""Base command for distributed lock operations."""
diff --git a/superset/commands/distributed_lock/release.py b/superset/commands/distributed_lock/release.py
index 14f9deb4df5..42fdfe0e4c1 100644
--- a/superset/commands/distributed_lock/release.py
+++ b/superset/commands/distributed_lock/release.py
@@ -19,15 +19,12 @@ from __future__ import annotations
import logging
from functools import partial
-from typing import Any
import redis
from sqlalchemy.exc import SQLAlchemyError
-from superset.commands.distributed_lock.base import (
- BaseDistributedLockCommand,
- get_redis_client,
-)
+from superset.commands.distributed_lock.base import BaseDistributedLockCommand
+from superset.coordination.base import CoordinationService
from superset.daos.key_value import KeyValueDAO
from superset.exceptions import ReleaseDistributedLockFailedException
from superset.key_value.exceptions import KeyValueDeleteFailedError
@@ -45,15 +42,15 @@ class ReleaseDistributedLock(BaseDistributedLockCommand):
"""
def run(self) -> None:
- if (redis_client := get_redis_client()) is not None:
- self._release_redis(redis_client)
+ if CoordinationService.is_backend_defined():
+ self._release_redis()
else:
self._release_kv()
- def _release_redis(self, redis_client: Any) -> None:
- """Release lock using Redis DELETE."""
+ def _release_redis(self) -> None:
+ """Release lock using the coordination backend's DELETE."""
try:
- redis_client.delete(self.redis_lock_key)
+ CoordinationService.delete_value(self.redis_lock_key)
logger.debug("Released Redis lock: %s", self.redis_lock_key)
except redis.RedisError as ex:
# Log warning but don't raise - TTL will handle cleanup
diff --git a/superset/config.py b/superset/config.py
index 0e8ee06b8eb..eea684e1793 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -2941,6 +2941,19 @@ GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL = "ws://127.0.0.1:8080/"
# Global async queries cache backend configuration options:
# - Set 'CACHE_TYPE' to 'RedisCache' for RedisCacheBackend.
# - Set 'CACHE_TYPE' to 'RedisSentinelCache' for RedisSentinelCacheBackend.
+#
+# DEPRECATED: this dedicated backend is retained only so Global Async Queries can
+# keep running on their own coordination connection when DISTRIBUTED_COORDINATION_CONFIG
+# is not configured. When configured it is used by GAQ *only* (its event streams and
+# cancel registry); it never powers distributed locks or the Global Task Framework,
+# which use DISTRIBUTED_COORDINATION_CONFIG exclusively. GAQ uses
+# DISTRIBUTED_COORDINATION_CONFIG whenever it is set and only falls back to this
+# dedicated backend when it is not, so a consolidated deployment need not maintain a
+# second config. This dual-backend arrangement is deprecated and removed in Superset
+# 8.0, when GAQ moves onto DISTRIBUTED_COORDINATION_CONFIG like the rest of Superset's
+# coordination. All parameters here are supported identically under
+# DISTRIBUTED_COORDINATION_CONFIG (both use the same
+# RedisCache/RedisSentinelCache backend).
GLOBAL_ASYNC_QUERIES_CACHE_BACKEND = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "localhost",
@@ -3223,24 +3236,46 @@ TASK_PROGRESS_UPDATE_THROTTLE_INTERVAL = 2 # seconds
# These features require Redis primitives unavailable in generic cache backends:
# - Pub/Sub: Real-time message broadcasting between workers
# - SET NX EX: Atomic lock acquisition with automatic expiration
-# - Streams: Persistent ordered event logs (future)
+# - Streams: Persistent ordered event logs (e.g. the Global Async Queries firehose)
#
# When configured, enables:
# - Real-time abort/completion notifications for GTF tasks (vs database polling)
# - Redis-based distributed locking (vs KeyValueDAO-backed DistributedLock)
-#
-# Future: This backend will power a higher-level coordination service exposing
-# standardized interfaces for distributed locks, pub/sub, and streams — consolidating
-# all advanced Redis primitives under a single connection. Global Async Queries
-# (GLOBAL_ASYNC_QUERIES_CACHE_BACKEND) will also be migrated to this configuration.
+# - Global Async Queries event streams (the async-events / firehose transport)
+#
+# This backend powers the higher-level coordination service
+# (``superset.coordination.base.CoordinationService``) exposing standardized interfaces
+# for distributed locks, pub/sub, and streams under a single connection. It is the
+# single source of truth for the coordinator's consumers (distributed locks, the
+# Global Task Framework, and future stream/pub-sub users). Global Async Queries use
+# this connection whenever it is set, falling back to their dedicated
+# ``GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`` only when it is unset; that dual-backend
+# arrangement is deprecated and, in Superset 8.0, GAQ moves onto this connection and
+# the dedicated backend is removed.
+#
+# All parameters previously supported by GLOBAL_ASYNC_QUERIES_CACHE_BACKEND are
+# supported here (both go through the same RedisCacheBackend/RedisSentinelCacheBackend
+# `from_config`): CACHE_REDIS_HOST, CACHE_REDIS_PORT, CACHE_REDIS_USER,
+# CACHE_REDIS_PASSWORD, CACHE_REDIS_DB, CACHE_KEY_PREFIX, CACHE_DEFAULT_TIMEOUT,
+# CACHE_REDIS_SSL, CACHE_REDIS_SSL_CERTFILE, CACHE_REDIS_SSL_KEYFILE,
+# CACHE_REDIS_SSL_CERT_REQS, CACHE_REDIS_SSL_CA_CERTS, CACHE_REDIS_SOCKET_TIMEOUT,
+# CACHE_REDIS_SOCKET_CONNECT_TIMEOUT, and for Sentinel CACHE_REDIS_SENTINELS,
+# CACHE_REDIS_SENTINEL_MASTER, CACHE_REDIS_SENTINEL_PASSWORD.
#
# Example with standard Redis:
# DISTRIBUTED_COORDINATION_CONFIG: CacheConfig = {
# "CACHE_TYPE": "RedisCache",
# "CACHE_REDIS_HOST": "localhost",
# "CACHE_REDIS_PORT": 6379,
-# "CACHE_REDIS_DB": 0,
+# "CACHE_REDIS_USER": "",
# "CACHE_REDIS_PASSWORD": "",
+# "CACHE_REDIS_DB": 0,
+# "CACHE_DEFAULT_TIMEOUT": 300,
+# "CACHE_REDIS_SSL": False, # True or False
+# "CACHE_REDIS_SSL_CERTFILE": None,
+# "CACHE_REDIS_SSL_KEYFILE": None,
+# "CACHE_REDIS_SSL_CERT_REQS": "required",
+# "CACHE_REDIS_SSL_CA_CERTS": None,
# }
#
# Example with Redis Sentinel:
diff --git a/superset/coordination/__init__.py b/superset/coordination/__init__.py
new file mode 100644
index 00000000000..9fb3958661a
--- /dev/null
+++ b/superset/coordination/__init__.py
@@ -0,0 +1,39 @@
+# 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.
+"""Centralized coordination service.
+
+Provides one connection (``DISTRIBUTED_COORDINATION_CONFIG``) and one interface for
+the Valkey/Redis coordination primitives Superset relies on: **pub/sub**, **key/value**,
+and event **streams**, plus a higher-level **await/notify** layer (``wait_for_signal`` /
+``listen_for_signal``) built on top of them. Distributed **locking** is served by
+:class:`~superset.distributed_lock.DistributedLock`, which draws on this service's
+backend when one is configured and falls back to a database-backed lock otherwise.
+
+Historically these were wired up independently: the Global Task Framework used
+``DISTRIBUTED_COORDINATION_CONFIG`` (pub/sub and locking) while Global Async Queries
+used a separate ``GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`` for its streams, and each caller
+hand-rolled its own pub/sub-vs-poll wait loops. Consolidating them here keeps the
+architecture modular, gives other components (e.g. the extensions framework) a single
+reusable coordination surface, and reduces the number of moving parts. The legacy
+``GLOBAL_ASYNC_QUERIES_CACHE_BACKEND`` is still honored as a fallback (with a
+deprecation warning) so existing deployments keep working during the transition.
+
+Import concrete classes directly from their modules:
+:class:`~superset.coordination.base.CoordinationService`,
+:class:`~superset.coordination.types.SignalListener`, and
+:class:`~superset.coordination.exceptions.CoordinationBackendUnavailableError`.
+"""
diff --git a/superset/coordination/base.py b/superset/coordination/base.py
new file mode 100644
index 00000000000..996a1f494e2
--- /dev/null
+++ b/superset/coordination/base.py
@@ -0,0 +1,380 @@
+# 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.
+"""Coordination service implementation.
+
+See :mod:`superset.coordination` for the package overview.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from typing import Any, Callable, TYPE_CHECKING, TypeVar
+
+from superset.coordination.exceptions import CoordinationBackendUnavailableError
+from superset.coordination.types import SignalListener
+from superset.coordination.utils import close_pubsub
+
+if TYPE_CHECKING:
+ from superset.coordination.types import CoordinationBackend
+
+logger = logging.getLogger(__name__)
+
+T = TypeVar("T")
+
+# Poll cadence for the pub/sub wait loop: how long each ``get_message`` blocks
+# before the loop re-checks the predicate, the timeout, and the stop flag. Keeps
+# stop latency and missed-message recovery bounded to ~1s.
+_PUBSUB_TICK_SECONDS = 1.0
+
+
+class CoordinationService:
+ """Single entry point for the Valkey/Redis coordination primitives.
+
+ Two layers of API:
+
+ - **Raw primitives** — ``publish``, ``get`` / ``set`` / ``delete``,
+ ``stream_add`` / ``stream_range``. These are backend-only and have no fallback:
+ they raise :class:`CoordinationBackendUnavailableError` when no backend is
+ available, rather than silently doing nothing. Each accepts an optional
+ ``backend`` so a caller with its own connection (Global Async Queries, during
+ the deprecation window) can run against it instead of the shared coordinator.
+ - **Higher-level await/notify** — ``wait_for_signal`` (blocking) and
+ ``listen_for_signal`` (background). These combine a pub/sub channel with a
+ caller-supplied predicate:
+ when a backend is defined they wake promptly on a published message and
+ re-check the predicate each tick; without a backend they poll the predicate.
+ This keeps the pub/sub-vs-poll boilerplate in one place; callers just supply a
+ channel and a check.
+
+ All methods are class-level: the service is app-global. Calls resolve the shared
+ coordination backend from ``DISTRIBUTED_COORDINATION_CONFIG`` on each call, except
+ the raw primitives, which accept an optional ``backend`` so a caller with its own
+ connection (Global Async Queries, during the deprecation window) can run against it.
+
+ Distributed locking is *not* exposed here: it has its own user-facing interface
+ (:class:`~superset.distributed_lock.DistributedLock`) that uses this service's
+ backend when one is defined and falls back to a database-backed lock otherwise.
+ """
+
+ @classmethod
+ def get_backend(cls) -> "CoordinationBackend | None":
+ """Resolve the coordination backend from ``DISTRIBUTED_COORDINATION_CONFIG``.
+
+ Returns the shared coordination connection (via the cache manager), or
+ ``None`` when ``DISTRIBUTED_COORDINATION_CONFIG`` is not configured. This is
+ the single source of truth for the coordinator's consumers (distributed
+ locks, the Global Task Framework, and future stream/pub-sub users); it does
+ *not* consult the deprecated ``GLOBAL_ASYNC_QUERIES_CACHE_BACKEND``. Global
+ Async Queries resolve their own backend (this coordinator when configured,
+ else the deprecated dedicated backend — see
+ :class:`~superset.async_events.async_query_manager.AsyncQueryManager`) and pass
+ it explicitly to the primitives below via ``backend``.
+ """
+ from superset.extensions import cache_manager
+
+ return cache_manager.distributed_coordination
+
+ @classmethod
+ def is_backend_defined(cls) -> bool:
+ """Whether a coordination backend is defined.
+
+ Some operations require the Valkey/Redis backend
+ (``DISTRIBUTED_COORDINATION_CONFIG``) to be configured; those that do note it
+ on their own docstring. Best-effort callers should branch on this before
+ invoking a backend-dependent operation instead of catching
+ :class:`CoordinationBackendUnavailableError`.
+ """
+ return cls.get_backend() is not None
+
+ @classmethod
+ def _require_backend(
+ cls, backend: "CoordinationBackend | None" = None
+ ) -> "CoordinationBackend":
+ """Return a usable backend or raise if none is available.
+
+ Used by the backend-only primitives (pub/sub publish, key/value, streams)
+ so a missing backend fails loudly instead of silently no-op'ing. When
+ ``backend`` is supplied (e.g. Global Async Queries passing its own separate
+ backend) it is used directly; otherwise the shared coordinator backend is
+ resolved via :meth:`get_backend`.
+ """
+ backend = backend or cls.get_backend()
+ if backend is None:
+ raise CoordinationBackendUnavailableError(
+ "No coordination backend configured; set "
+ "DISTRIBUTED_COORDINATION_CONFIG to enable key/value and stream "
+ "operations."
+ )
+ return backend
+
+ # -- Pub/Sub -------------------------------------------------------------
+
+ @classmethod
+ def publish(
+ cls,
+ channel: str,
+ message: str,
+ backend: "CoordinationBackend | None" = None,
+ ) -> int:
+ """Publish a message to a channel; returns the subscriber count.
+
+ Only publishing is offered here — subscribing needs the native connection
+ (a long-lived subscription with its own receive loop), so consumers that
+ subscribe should obtain it via :meth:`get_backend`.
+
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).publish(channel, message)
+
+ # -- Key/Value -----------------------------------------------------------
+
+ @classmethod
+ def get_value(cls, key: str, backend: "CoordinationBackend | None" = None) -> Any:
+ """Return the raw (bytes) value at ``key``, or ``None`` if absent.
+
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).get(key)
+
+ @classmethod
+ def set_value(
+ cls,
+ key: str,
+ value: Any,
+ ttl: int | None = None,
+ if_absent: bool = False,
+ if_present: bool = False,
+ backend: "CoordinationBackend | None" = None,
+ ) -> bool | None:
+ """Store ``value`` at ``key``.
+
+ :param ttl: optional expiry, in seconds.
+ :param if_absent: only set if the key does not already exist.
+ :param if_present: only set if the key already exists.
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :returns: ``True`` on success, or ``None`` when an ``if_absent`` /
+ ``if_present`` condition prevented the write.
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).set(
+ key, value, ex=ttl, nx=if_absent, xx=if_present
+ )
+
+ @classmethod
+ def delete_value(
+ cls, *keys: str, backend: "CoordinationBackend | None" = None
+ ) -> int:
+ """Delete one or more keys; returns the number deleted.
+
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).delete(*keys)
+
+ # -- Streams -------------------------------------------------------------
+
+ @classmethod
+ def stream_add(
+ cls,
+ stream: str,
+ data: dict[str, Any],
+ event_id: str = "*",
+ max_len: int | None = None,
+ backend: "CoordinationBackend | None" = None,
+ ) -> str:
+ """Append an event to a stream; returns the generated event id.
+
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).xadd(stream, data, event_id, max_len)
+
+ @classmethod
+ def stream_range(
+ cls,
+ stream: str,
+ start: str = "-",
+ end: str = "+",
+ count: int | None = None,
+ backend: "CoordinationBackend | None" = None,
+ ) -> list[Any]:
+ """Read a range of events from a stream.
+
+ :param backend: optional explicit backend (see :meth:`_require_backend`).
+ :raises CoordinationBackendUnavailableError: if no backend is available.
+ """
+ return cls._require_backend(backend).xrange(stream, start, end, count)
+
+ # -- Await / notify ------------------------------------------------------
+
+ @classmethod
+ def wait_for_signal(
+ cls,
+ channel: str,
+ check: Callable[[], T | None],
+ *,
+ timeout: float | None = None,
+ poll_interval: float = 1.0,
+ ) -> T:
+ """Block until ``check()`` returns a non-``None`` value; return that value.
+
+ ``check`` is the source of truth (typically a metastore read). When a
+ coordination backend is defined, this subscribes to ``channel`` and re-runs
+ ``check`` promptly whenever a message is published; otherwise it polls
+ ``check`` every ``poll_interval`` seconds. ``check`` is also re-evaluated on
+ every tick even in pub/sub mode, so a signal published before the subscription
+ (or a dropped message) is still caught.
+
+ :param channel: pub/sub channel that peers publish to when the awaited state
+ is reached (used only as a low-latency wake-up; correctness relies on
+ ``check``).
+ :param check: returns a truthy result once the wait is satisfied, else
+ ``None``.
+ :param timeout: max seconds to wait; ``None`` waits indefinitely.
+ :param poll_interval: poll cadence when no backend is defined.
+ :raises TimeoutError: if ``timeout`` elapses before ``check`` is satisfied.
+ """
+ deadline = None if timeout is None else time.monotonic() + timeout
+ # Check first, before touching the backend: if the awaited state is already
+ # reached (e.g. the task is already terminal), return straight from the
+ # source of truth so the fast path never requires the backend to be reachable.
+ if (result := check()) is not None:
+ return result
+ backend = cls.get_backend()
+ pubsub = backend.pubsub() if backend is not None else None
+ try:
+ if pubsub is not None:
+ pubsub.subscribe(channel)
+ while True:
+ # Re-check every tick even in pub/sub mode, so a signal published
+ # before the subscription (or a dropped message) is still caught.
+ if (result := check()) is not None:
+ return result
+ remaining = (
+ None if deadline is None else max(0.0, deadline - time.monotonic())
+ )
+ if remaining is not None and remaining <= 0:
+ raise TimeoutError(f"Timed out waiting on channel {channel}")
+ cls._wait_tick(pubsub, poll_interval, remaining)
+ finally:
+ if pubsub is not None:
+ close_pubsub(pubsub)
+
+ @staticmethod
+ def _wait_tick(pubsub: Any, poll_interval: float, remaining: float | None) -> None:
+ """Block for one wait tick: a pub/sub message (nudge) or a poll sleep."""
+ if pubsub is not None:
+ wait = (
+ _PUBSUB_TICK_SECONDS
+ if remaining is None
+ else min(_PUBSUB_TICK_SECONDS, remaining)
+ )
+ pubsub.get_message(ignore_subscribe_messages=True, timeout=wait)
+ else:
+ time.sleep(
+ poll_interval if remaining is None else min(poll_interval, remaining)
+ )
+
+ @classmethod
+ def listen_for_signal(
+ cls,
+ channel: str,
+ check: Callable[[], bool],
+ on_signal: Callable[[], None],
+ *,
+ poll_interval: float,
+ name: str | None = None,
+ ) -> SignalListener:
+ """Run a background daemon that invokes ``on_signal`` once ``check`` is true.
+
+ Same wake-vs-poll model as :meth:`wait_for_signal`: a published message on
+ ``channel`` wakes the loop when a backend is defined, otherwise it polls
+ ``check`` every ``poll_interval`` seconds. The thread stops after firing
+ ``on_signal`` once, or when :meth:`SignalListener.stop` is called.
+
+ :param channel: pub/sub channel peers publish to when the condition is met.
+ :param check: returns ``True`` once ``on_signal`` should fire.
+ :param on_signal: invoked (once) when ``check`` becomes true.
+ :param poll_interval: poll cadence when no backend is defined.
+ :param name: optional thread name suffix for logging.
+ """
+ stop_event = threading.Event()
+ backend = cls.get_backend()
+ pubsub = backend.pubsub() if backend is not None else None
+ if pubsub is not None:
+ # Subscribe in the caller's thread so a connection failure surfaces here
+ # (fail-fast) rather than dying silently in the daemon thread.
+ try:
+ pubsub.subscribe(channel)
+ except Exception:
+ close_pubsub(pubsub)
+ raise
+ thread = threading.Thread(
+ target=cls._run_listen_loop,
+ args=(channel, check, on_signal, stop_event, poll_interval, pubsub),
+ daemon=True,
+ name=f"coord-listen-{name or channel}",
+ )
+ thread.start()
+ return SignalListener(thread, stop_event, pubsub)
+
+ @classmethod
+ def _run_listen_loop(
+ cls,
+ channel: str,
+ check: Callable[[], bool],
+ on_signal: Callable[[], None],
+ stop_event: threading.Event,
+ poll_interval: float,
+ pubsub: Any,
+ ) -> None:
+ """Body of the background listener thread (see :meth:`listen_for_signal`)."""
+ try:
+ while not stop_event.is_set():
+ try:
+ if check():
+ on_signal()
+ return
+ if pubsub is not None:
+ # Blocks up to a tick; the message is just a wake-up nudge.
+ pubsub.get_message(
+ ignore_subscribe_messages=True,
+ timeout=_PUBSUB_TICK_SECONDS,
+ )
+ else:
+ stop_event.wait(timeout=poll_interval)
+ except (ValueError, OSError) as ex:
+ # Connection torn down (e.g. stop() closing the subscription, or
+ # shutdown). Expected when stopping; otherwise surface it and bail.
+ if not stop_event.is_set():
+ logger.error(
+ "Signal listener on %s failed: %s",
+ channel,
+ ex,
+ exc_info=True,
+ )
+ return
+ except Exception: # pylint: disable=broad-except
+ if not stop_event.is_set():
+ logger.exception("Signal listener on %s crashed", channel)
+ finally:
+ if pubsub is not None:
+ close_pubsub(pubsub)
diff --git a/superset/coordination/exceptions.py b/superset/coordination/exceptions.py
new file mode 100644
index 00000000000..17f9214c545
--- /dev/null
+++ b/superset/coordination/exceptions.py
@@ -0,0 +1,31 @@
+# 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.
+"""Exceptions raised by the coordination service."""
+
+from __future__ import annotations
+
+
+class CoordinationBackendUnavailableError(Exception):
+ """Raised when a Valkey/Redis-only primitive is used without a backend.
+
+ Pub/sub, streams, and key/value operations have no in-service fallback, so
+ calling them without a configured coordination backend is a programming or
+ configuration error rather than a silently-ignored no-op. Callers that have
+ their own fallback (e.g. database polling) should gate on
+ :meth:`superset.coordination.base.CoordinationService.is_backend_defined` instead of
+ catching this.
+ """
diff --git a/superset/coordination/types.py b/superset/coordination/types.py
new file mode 100644
index 00000000000..fa73f586dfe
--- /dev/null
+++ b/superset/coordination/types.py
@@ -0,0 +1,72 @@
+# 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.
+"""Types for the coordination service."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from typing import Any, TYPE_CHECKING
+
+from superset.coordination.utils import close_pubsub
+
+if TYPE_CHECKING:
+ from superset.async_events.cache_backend import (
+ RedisCacheBackend,
+ RedisSentinelCacheBackend,
+ )
+
+ # The concrete coordination backend resolved from DISTRIBUTED_COORDINATION_CONFIG.
+ CoordinationBackend = RedisCacheBackend | RedisSentinelCacheBackend
+
+logger = logging.getLogger(__name__)
+
+
+class SignalListener:
+ """Handle for a background listener started by
+ :meth:`~superset.coordination.base.CoordinationService.listen_for_signal`.
+
+ Wraps the daemon thread, its stop flag, and (in pub/sub mode) the subscription.
+ :meth:`stop` sets the flag and closes the subscription so a thread blocked in
+ ``get_message`` wakes immediately, then joins.
+ """
+
+ def __init__(
+ self,
+ thread: threading.Thread,
+ stop_event: threading.Event,
+ pubsub: Any = None,
+ ) -> None:
+ self._thread = thread
+ self._stop_event = stop_event
+ self._pubsub = pubsub
+
+ def stop(self) -> None:
+ """Signal the listener to stop and wait briefly for the thread to finish."""
+ self._stop_event.set()
+ # Closing the subscription unblocks a thread parked in get_message so
+ # teardown is near-immediate rather than waiting a full poll tick.
+ if self._pubsub is not None:
+ close_pubsub(self._pubsub)
+ if self._thread.is_alive():
+ self._thread.join(timeout=2.0)
+ if self._thread.is_alive():
+ # Daemon thread: it will be reaped at process exit. Don't block.
+ logger.warning(
+ "Signal listener thread %s did not terminate within 2s.",
+ self._thread.name,
+ )
diff --git a/superset/coordination/utils.py b/superset/coordination/utils.py
new file mode 100644
index 00000000000..153702cd72c
--- /dev/null
+++ b/superset/coordination/utils.py
@@ -0,0 +1,40 @@
+# 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.
+"""Helpers for the coordination service."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def close_pubsub(pubsub: Any) -> None:
+ """Best-effort unsubscribe + close of a pub/sub subscription.
+
+ ``unsubscribe`` and ``close`` are attempted independently so a failure of the
+ former still releases the underlying connection.
+ """
+ try:
+ pubsub.unsubscribe()
+ except Exception as ex: # pylint: disable=broad-except
+ logger.debug("Error unsubscribing pub/sub subscription: %s", ex)
+ try:
+ pubsub.close()
+ except Exception as ex: # pylint: disable=broad-except
+ logger.debug("Error closing pub/sub subscription: %s", ex)
diff --git a/superset/tasks/context.py b/superset/tasks/context.py
index 76c8a01b855..048ab7a76fc 100644
--- a/superset/tasks/context.py
+++ b/superset/tasks/context.py
@@ -35,8 +35,8 @@ from superset.tasks.constants import ABORT_STATES
from superset.tasks.utils import progress_update
if TYPE_CHECKING:
+ from superset.coordination.types import SignalListener
from superset.models.tasks import Task
- from superset.tasks.manager import AbortListener
logger = logging.getLogger(__name__)
@@ -67,7 +67,7 @@ class TaskContext(CoreTaskContext):
self._task_uuid = task.uuid
self._cleanup_handlers: list[Callable[[], None]] = []
self._abort_handlers: list[Callable[[], None]] = []
- self._abort_listener: "AbortListener | None" = None
+ self._abort_listener: "SignalListener | None" = None
self._abort_detected = False
self._abort_handlers_completed = False # Track if all abort handlers finished
self._execution_completed = False # Set by executor after task work completes
diff --git a/superset/tasks/manager.py b/superset/tasks/manager.py
index 08adb639a9c..564df0ac271 100644
--- a/superset/tasks/manager.py
+++ b/superset/tasks/manager.py
@@ -19,8 +19,6 @@
from __future__ import annotations
import logging
-import threading
-import time
from typing import Any, Callable, TYPE_CHECKING
from uuid import UUID
@@ -28,72 +26,18 @@ import redis
from flask import has_app_context
from superset_core.tasks.types import TaskProperties, TaskScope
-from superset.async_events.cache_backend import (
- RedisCacheBackend,
- RedisSentinelCacheBackend,
-)
-from superset.extensions import cache_manager
from superset.tasks.constants import ABORT_STATES, TERMINAL_STATES
from superset.tasks.utils import generate_random_task_key
if TYPE_CHECKING:
from flask import Flask
+ from superset.coordination.types import SignalListener
from superset.models.tasks import Task
logger = logging.getLogger(__name__)
-class AbortListener:
- """
- Handle for a background abort listener.
-
- Returned by TaskManager.listen_for_abort() to allow stopping the listener.
- """
-
- def __init__(
- self,
- task_uuid: UUID,
- thread: threading.Thread,
- stop_event: threading.Event,
- pubsub: redis.client.PubSub | None = None,
- ) -> None:
- self._task_uuid = task_uuid
- self._thread = thread
- self._stop_event = stop_event
- self._pubsub = pubsub
-
- def stop(self) -> None:
- """Stop the abort listener."""
- self._stop_event.set()
-
- # Close pub/sub subscription if active
- if self._pubsub is not None:
- try:
- self._pubsub.unsubscribe()
- self._pubsub.close()
- except Exception as ex:
- logger.debug("Error closing pub/sub during stop: %s", ex)
-
- # Wait for thread to finish (with timeout to avoid blocking indefinitely)
- if self._thread.is_alive():
- self._thread.join(timeout=2.0)
-
- # Check if thread is still running after timeout
- if self._thread.is_alive():
- # Thread is a daemon, so it will be killed when process exits.
- # Log warning but continue - cleanup will still proceed.
- logger.warning(
- "Abort listener thread for task %s did not terminate within "
- "2 seconds. Thread will be terminated when process exits.",
- self._task_uuid,
- )
- else:
- logger.debug("Stopped abort listener for task %s", self._task_uuid)
- else:
- logger.debug("Stopped abort listener for task %s", self._task_uuid)
-
-
class TaskManager:
"""
Handles task creation, scheduling, and abort notifications.
@@ -132,24 +76,6 @@ class TaskManager:
cls._initialized = True
- @classmethod
- def _get_cache(cls) -> RedisCacheBackend | RedisSentinelCacheBackend | None:
- """
- Get the distributed coordination backend.
-
- :returns: The distributed coordination backend, or None if not configured
- """
- return cache_manager.distributed_coordination
-
- @classmethod
- def is_pubsub_available(cls) -> bool:
- """
- Check if Redis pub/sub backend is configured and available.
-
- :returns: True if Redis is available for pub/sub, False otherwise
- """
- return cls._get_cache() is not None
-
@classmethod
def get_abort_channel(cls, task_uuid: UUID) -> str:
"""
@@ -168,13 +94,14 @@ class TaskManager:
:param task_uuid: UUID of the task to abort
:returns: True if message was published, False if Redis unavailable
"""
- cache = cls._get_cache()
- if not cache:
+ from superset.coordination.base import CoordinationService
+
+ if not CoordinationService.is_backend_defined():
return False
try:
channel = cls.get_abort_channel(task_uuid)
- subscriber_count = cache.publish(channel, "abort")
+ subscriber_count = CoordinationService.publish(channel, "abort")
logger.debug(
"Published abort to channel %s (%d subscribers)",
channel,
@@ -207,13 +134,14 @@ class TaskManager:
:param status: Final status of the task
:returns: True if message was published, False if Redis unavailable
"""
- cache = cls._get_cache()
- if not cache:
+ from superset.coordination.base import CoordinationService
+
+ if not CoordinationService.is_backend_defined():
return False
try:
channel = cls.get_completion_channel(task_uuid)
- subscriber_count = cache.publish(channel, status)
+ subscriber_count = CoordinationService.publish(channel, status)
logger.debug(
"Published completion to channel %s (status=%s, %d subscribers)",
channel,
@@ -236,8 +164,10 @@ class TaskManager:
"""
Block until task reaches terminal state.
- Uses Redis pub/sub if configured for low-latency, low-CPU waiting.
- Uses database polling if Redis is not configured.
+ Delegates the pub/sub-wake-else-poll orchestration to
+ :meth:`CoordinationService.wait_for_signal`; here we only supply the
+ completion channel and a metastore predicate that returns the task once it is
+ terminal.
:param task_uuid: UUID of the task to wait for
:param timeout: Maximum time to wait in seconds (None = no limit)
@@ -247,17 +177,9 @@ class TaskManager:
:raises TimeoutError: If timeout expires before task completes
:raises ValueError: If task not found
"""
+ from superset.coordination.base import CoordinationService
from superset.daos.tasks import TaskDAO
- start_time = time.monotonic()
-
- def time_remaining() -> float | None:
- if timeout is None:
- return None
- elapsed = time.monotonic() - start_time
- remaining = timeout - elapsed
- return remaining if remaining > 0 else 0
-
def get_task() -> "Task | None":
# Reads back the task named by the caller's own task_uuid, not
# a user-requested lookup; see TaskFilter for the
@@ -269,135 +191,20 @@ class TaskManager:
)
return TaskDAO.find_one_or_none(uuid=task_uuid, skip_base_filter=True)
- # Check current state first
- task = get_task()
- if not task:
+ # Fail fast if the task doesn't exist at all.
+ if get_task() is None:
raise ValueError(f"Task {task_uuid} not found")
- if task.status in TERMINAL_STATES:
- return task
-
- logger.debug(
- "Waiting for task %s to complete (current status=%s, timeout=%s)",
- task_uuid,
- task.status,
- timeout,
- )
-
- # Use Redis pub/sub if configured
- if (cache := cls._get_cache()) is not None:
- task = cls._wait_via_pubsub(
- task_uuid,
- cache.pubsub(),
- timeout,
- poll_interval,
- get_task,
- time_remaining,
- )
- if task:
- return task
- # Should not reach here - _wait_via_pubsub returns task or raises
- raise RuntimeError(f"Unexpected state waiting for task {task_uuid}")
-
- # Use database polling when Redis is not configured
- return cls._wait_via_polling(task_uuid, poll_interval, get_task, time_remaining)
-
- @classmethod
- def _wait_via_pubsub(
- cls,
- task_uuid: UUID,
- pubsub: redis.client.PubSub,
- timeout: float | None,
- poll_interval: float,
- get_task: Callable[[], "Task | None"],
- time_remaining: Callable[[], float | None],
- ) -> "Task | None":
- """
- Wait for task completion using Redis pub/sub.
-
- :returns: Task when completed
- :raises TimeoutError: If timeout expires
- :raises redis.RedisError: If Redis connection fails
- """
- channel = cls.get_completion_channel(task_uuid)
- pubsub.subscribe(channel)
-
- try:
- while True:
- remaining = time_remaining()
- if remaining is not None and remaining <= 0:
- raise TimeoutError(
- f"Timeout waiting for task {task_uuid} to complete"
- )
-
- # Wait for message with short timeout for responsive checking
- wait_time = min(1.0, remaining) if remaining else 1.0
- message = pubsub.get_message(
- ignore_subscribe_messages=True,
- timeout=wait_time,
- )
-
- if message and message.get("type") == "message":
- # Completion received - fetch fresh task state
- logger.debug(
- "Received completion message for task %s: %s",
- task_uuid,
- message.get("data"),
- )
- task = get_task()
- if task and task.status in TERMINAL_STATES:
- return task
-
- # Also check database periodically in case we missed the message
- # (e.g., task completed before we subscribed)
- task = get_task()
- if task and task.status in TERMINAL_STATES:
- logger.debug(
- "Task %s completed (detected via db check): status=%s",
- task_uuid,
- task.status,
- )
- return task
-
- finally:
- pubsub.unsubscribe()
- pubsub.close()
-
- @classmethod
- def _wait_via_polling(
- cls,
- task_uuid: UUID,
- poll_interval: float,
- get_task: Callable[[], "Task | None"],
- time_remaining: Callable[[], float | None],
- ) -> "Task":
- """
- Wait for task completion using database polling.
-
- :returns: Task when completed
- :raises TimeoutError: If timeout expires
- :raises ValueError: If task not found
- """
- while True:
- remaining = time_remaining()
- if remaining is not None and remaining <= 0:
- raise TimeoutError(f"Timeout waiting for task {task_uuid} to complete")
-
+ def terminal_task() -> "Task | None":
task = get_task()
- if not task:
- raise ValueError(f"Task {task_uuid} not found")
+ return task if task and task.status in TERMINAL_STATES else None
- if task.status in TERMINAL_STATES:
- logger.debug(
- "Task %s completed (detected via polling): status=%s",
- task_uuid,
- task.status,
- )
- return task
-
- # Sleep with timeout awareness
- sleep_time = min(poll_interval, remaining) if remaining else poll_interval
- time.sleep(sleep_time)
+ return CoordinationService.wait_for_signal(
+ cls.get_completion_channel(task_uuid),
+ terminal_task,
+ timeout=timeout,
+ poll_interval=poll_interval,
+ )
@classmethod
def listen_for_abort(
@@ -406,72 +213,39 @@ class TaskManager:
callback: Callable[[], None],
poll_interval: float,
app: Any = None,
- ) -> AbortListener:
+ ) -> "SignalListener":
"""
Start listening for abort notifications for a task.
- Uses Redis pub/sub if configured, otherwise uses database polling.
- The callback is invoked when an abort is detected.
+ Delegates the pub/sub-wake-else-poll orchestration to
+ :meth:`CoordinationService.listen_for_signal`; here we only supply the abort
+ channel and an (app-context-aware) abort predicate + callback.
:param task_uuid: UUID of the task to monitor (native UUID)
:param callback: Function to call when abort is detected
:param poll_interval: Interval for database polling (when Redis not configured)
:param app: Flask app for database access in background thread
- :returns: AbortListener handle to stop listening
- """
- stop_event = threading.Event()
- pubsub: redis.client.PubSub | None = None
- uuid_str = str(task_uuid)
-
- # Use Redis pub/sub if configured
- if (cache := cls._get_cache()) is not None:
- pubsub = cache.pubsub()
- channel = cls.get_abort_channel(task_uuid)
- pubsub.subscribe(channel)
- logger.debug("Subscribed to abort channel: %s", channel)
-
- # Start pub/sub listener thread
- thread = threading.Thread(
- target=cls._listen_pubsub,
- args=(task_uuid, pubsub, callback, stop_event, app),
- daemon=True,
- name=f"abort-listener-{uuid_str[:8]}",
- )
- logger.debug("Started pub/sub abort listener for task %s", task_uuid)
- else:
- # Use polling when Redis is not configured
- pubsub = None
- thread = threading.Thread(
- target=cls._poll_for_abort,
- args=(task_uuid, callback, stop_event, poll_interval, app),
- daemon=True,
- name=f"abort-poller-{uuid_str[:8]}",
- )
- logger.debug(
- "Started database abort polling for task %s (interval=%ss)",
- task_uuid,
- poll_interval,
- )
-
- thread.start()
- return AbortListener(task_uuid, thread, stop_event, pubsub)
-
- @staticmethod
- def _invoke_callback_with_context(
- callback: Callable[[], None],
- app: Any,
- ) -> None:
- """
- Invoke callback with Flask app context if provided.
-
- :param callback: Function to invoke
- :param app: Flask app for context, or None
+ :returns: SignalListener handle to stop listening
"""
- if app and not has_app_context():
- with app.app_context():
- callback()
- else:
- callback()
+ from superset.coordination.base import CoordinationService
+
+ def in_context(fn: Callable[[], Any]) -> Callable[[], Any]:
+ # The listener runs in a background thread; DB access needs app context.
+ def wrapped() -> Any:
+ if app and not has_app_context():
+ with app.app_context():
+ return fn()
+ return fn()
+
+ return wrapped
+
+ return CoordinationService.listen_for_signal(
+ cls.get_abort_channel(task_uuid),
+ check=in_context(lambda: cls._check_abort_status(task_uuid)),
+ on_signal=in_context(callback),
+ poll_interval=poll_interval,
+ name=str(task_uuid),
+ )
@classmethod
def _check_abort_status(cls, task_uuid: UUID) -> bool:
@@ -488,201 +262,6 @@ class TaskManager:
task = TaskDAO.find_one_or_none(uuid=task_uuid, skip_base_filter=True)
return task is not None and task.status in ABORT_STATES
- @classmethod
- def _run_abort_listener_loop(
- cls,
- task_uuid: UUID,
- callback: Callable[[], None],
- stop_event: threading.Event,
- interval: float,
- app: Any,
- check_fn: Callable[[], bool],
- source: str,
- ) -> None:
- """
- Common abort listener loop used by both pub/sub and polling modes.
-
- :param task_uuid: UUID of the task to monitor (native UUID)
- :param callback: Function to call when abort is detected
- :param stop_event: Event to signal loop termination
- :param interval: Wait interval between checks
- :param app: Flask app for context
- :param check_fn: Function that returns True if abort was detected
- :param source: Source identifier for logging ("pub/sub" or "polling")
- """
- while not stop_event.is_set():
- try:
- if check_fn():
- logger.info(
- "Abort detected via %s for task %s",
- source,
- task_uuid,
- )
- cls._invoke_callback_with_context(callback, app)
- break
-
- # Wait for interval or until stop is requested
- stop_event.wait(timeout=interval)
-
- except (ValueError, OSError) as ex:
- # ValueError/OSError with "I/O operation on closed file" or
- # "Bad file descriptor" typically means the connection was closed
- # during shutdown. Check if stop was requested.
- if stop_event.is_set():
- logger.debug(
- "Abort %s for task %s stopped cleanly (connection closed)",
- source,
- task_uuid,
- )
- else:
- logger.error(
- "Error in abort %s for task %s: %s",
- source,
- task_uuid,
- str(ex),
- exc_info=True,
- )
- break
-
- except Exception as ex:
- # Check if stop was requested - if so, this may be expected
- if stop_event.is_set():
- logger.debug(
- "Abort %s for task %s stopped with exception: %s",
- source,
- task_uuid,
- ex,
- )
- else:
- logger.error(
- "Error in abort %s for task %s: %s",
- source,
- task_uuid,
- str(ex),
- exc_info=True,
- )
- break
-
- @classmethod
- def _listen_pubsub(
- cls,
- task_uuid: UUID,
- pubsub: redis.client.PubSub,
- callback: Callable[[], None],
- stop_event: threading.Event,
- app: Any,
- ) -> None:
- """Listen for abort via Redis pub/sub."""
- # Track if abort was received to avoid double-callback
- abort_received = False
-
- def check_pubsub() -> bool:
- nonlocal abort_received
- message = pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0)
- if message is not None and message.get("type") == "message":
- abort_received = True
- return True
- return False
-
- try:
- cls._run_abort_listener_loop(
- task_uuid=task_uuid,
- callback=callback,
- stop_event=stop_event,
- interval=0, # pub/sub has its own timeout in get_message
- app=app,
- check_fn=check_pubsub,
- source="pub/sub",
- )
-
- except redis.RedisError as ex:
- # Check if we were asked to stop - if so, this is expected
- if stop_event.is_set():
- logger.debug(
- "Abort listener for task %s stopped (Redis error: %s)",
- task_uuid,
- ex,
- )
- else:
- # Log error but don't fall back - let the failure be visible
- logger.error(
- "Redis signal backend failed for task %s abort listener: %s. "
- "Task may not receive abort signal.",
- task_uuid,
- ex,
- )
-
- except (ValueError, OSError) as ex:
- # ValueError: "I/O operation on closed file" - expected when stop() closes
- # OSError: Similar connection-closed errors
- if stop_event.is_set():
- # Clean shutdown, expected behavior
- logger.debug(
- "Abort listener for task %s stopped cleanly",
- task_uuid,
- )
- else:
- # Unexpected error while running
- logger.error(
- "Error in abort listener for task %s: %s",
- task_uuid,
- str(ex),
- exc_info=True,
- )
-
- except Exception as ex:
- # Only log as error if we weren't asked to stop
- if stop_event.is_set():
- logger.debug(
- "Abort listener for task %s stopped with exception: %s",
- task_uuid,
- ex,
- )
- else:
- logger.error(
- "Error in abort listener for task %s: %s",
- task_uuid,
- str(ex),
- exc_info=True,
- )
-
- finally:
- # Clean up pub/sub subscription
- try:
- pubsub.unsubscribe()
- pubsub.close()
- except Exception as ex:
- logger.debug("Error closing pub/sub during cleanup: %s", ex)
-
- @classmethod
- def _poll_for_abort(
- cls,
- task_uuid: UUID,
- callback: Callable[[], None],
- stop_event: threading.Event,
- interval: float,
- app: Any,
- ) -> None:
- """Background polling loop - used when Redis pub/sub is not configured."""
-
- def check_database() -> bool:
- # Need app context for database access
- if app and not has_app_context():
- with app.app_context():
- return cls._check_abort_status(task_uuid)
- else:
- return cls._check_abort_status(task_uuid)
-
- cls._run_abort_listener_loop(
- task_uuid=task_uuid,
- callback=callback,
- stop_event=stop_event,
- interval=interval,
- app=app,
- check_fn=check_database,
- source="polling",
- )
-
@staticmethod
def submit_task(
task_type: str,
diff --git a/tests/integration_tests/async_events/api_tests.py b/tests/integration_tests/async_events/api_tests.py
index 5be8022d5b7..89e008940bd 100644
--- a/tests/integration_tests/async_events/api_tests.py
+++ b/tests/integration_tests/async_events/api_tests.py
@@ -46,13 +46,17 @@ class TestAsyncEventApi(SupersetTestCase):
def run_test_with_cache_backend(self, cache_backend_cls: Type[Any], test_func):
app._got_first_request = False
- async_query_manager_factory.init_app(app)
- # Create a mock cache backend instance
+ # GAQ resolves its own backend from get_cache_backend during init_app, so
+ # inject the mock there. init_app must run before login(): it re-registers the
+ # after_request handler, and login()'s request would otherwise trip Flask's
+ # "setup method after first request" guard before init_app gets to re-register.
mock_cache = mock.Mock(spec=cache_backend_cls)
-
- # Set the mock cache instance
- async_query_manager._cache = mock_cache
+ with mock.patch(
+ "superset.async_events.async_query_manager.get_cache_backend",
+ return_value=mock_cache,
+ ):
+ async_query_manager_factory.init_app(app)
self.login(ADMIN_USERNAME)
test_func(mock_cache)
diff --git a/tests/integration_tests/tasks/async_queries_tests.py b/tests/integration_tests/tasks/async_queries_tests.py
index 16d618f0ece..f254840804d 100644
--- a/tests/integration_tests/tasks/async_queries_tests.py
+++ b/tests/integration_tests/tasks/async_queries_tests.py
@@ -21,12 +21,7 @@ from uuid import uuid4
import pytest
from celery.exceptions import SoftTimeLimitExceeded
-from parameterized import parameterized
-from superset.async_events.cache_backend import (
- RedisCacheBackend,
- RedisSentinelCacheBackend,
-)
from superset.commands.chart.data.get_data_command import ChartDataCommand
from superset.commands.chart.exceptions import ChartDataQueryFailedError
from superset.extensions import async_query_manager, security_manager
@@ -46,24 +41,13 @@ from tests.integration_tests.test_app import app
"load_birth_names_data", "load_birth_names_dashboard_with_slices"
)
class TestAsyncQueries(SupersetTestCase):
- @parameterized.expand(
- [
- ("RedisCacheBackend", mock.Mock(spec=RedisCacheBackend)),
- ("RedisSentinelCacheBackend", mock.Mock(spec=RedisSentinelCacheBackend)),
- ]
- )
@mock.patch("superset.tasks.async_queries.set_form_data")
@mock.patch.object(async_query_manager, "update_job")
- def test_load_chart_data_into_cache(
- self, cache_type, cache_backend, mock_update_job, mock_set_form_data
- ):
+ def test_load_chart_data_into_cache(self, mock_update_job, mock_set_form_data):
from superset.tasks.async_queries import load_chart_data_into_cache
app._got_first_request = False
- async_query_manager.get_cache_backend = mock.Mock(return_value=cache_backend)
- async_query_manager.init_app(app)
-
query_context = get_query_context("birth_names")
user = security_manager.find_user("gamma")
job_metadata = {
@@ -81,26 +65,15 @@ class TestAsyncQueries(SupersetTestCase):
job_metadata, "done", result_url=mock.ANY
)
- @parameterized.expand(
- [
- ("RedisCacheBackend", mock.Mock(spec=RedisCacheBackend)),
- ("RedisSentinelCacheBackend", mock.Mock(spec=RedisSentinelCacheBackend)),
- ]
- )
@mock.patch.object(
ChartDataCommand, "run", side_effect=ChartDataQueryFailedError("Error: foo")
)
@mock.patch.object(async_query_manager, "update_job")
- def test_load_chart_data_into_cache_error(
- self, cache_type, cache_backend, mock_update_job, mock_run_command
- ):
+ def test_load_chart_data_into_cache_error(self, mock_update_job, mock_run_command):
from superset.tasks.async_queries import load_chart_data_into_cache
app._got_first_request = False
- async_query_manager.get_cache_backend = mock.Mock(return_value=cache_backend)
- async_query_manager.init_app(app)
-
query_context = get_query_context("birth_names")
user = security_manager.find_user("gamma")
job_metadata = {
@@ -117,24 +90,15 @@ class TestAsyncQueries(SupersetTestCase):
errors = [{"message": "Error: foo"}]
mock_update_job.assert_called_once_with(job_metadata, "error", errors=errors)
- @parameterized.expand(
- [
- ("RedisCacheBackend", mock.Mock(spec=RedisCacheBackend)),
- ("RedisSentinelCacheBackend", mock.Mock(spec=RedisSentinelCacheBackend)),
- ]
- )
@mock.patch.object(ChartDataCommand, "run")
@mock.patch.object(async_query_manager, "update_job")
def test_soft_timeout_load_chart_data_into_cache(
- self, cache_type, cache_backend, mock_update_job, mock_run_command
+ self, mock_update_job, mock_run_command
):
from superset.tasks.async_queries import load_chart_data_into_cache
app._got_first_request = False
- async_query_manager.get_cache_backend = mock.Mock(return_value=cache_backend)
- async_query_manager.init_app(app)
-
user = security_manager.find_user("gamma")
form_data = {}
job_metadata = {
diff --git a/tests/integration_tests/tasks/test_sync_join_wait.py b/tests/integration_tests/tasks/test_sync_join_wait.py
index 2483c57cd85..7fb07c4cf69 100644
--- a/tests/integration_tests/tasks/test_sync_join_wait.py
+++ b/tests/integration_tests/tasks/test_sync_join_wait.py
@@ -90,8 +90,10 @@ def test_wait_for_completion_timeout(app_context, login_as, get_user) -> None:
try:
# Force polling mode by mocking distributed_coordination as None
- with patch("superset.tasks.manager.cache_manager") as mock_cache_manager:
- mock_cache_manager.distributed_coordination = None
+ with patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ):
with pytest.raises(TimeoutError):
TaskManager.wait_for_completion(
task.uuid,
diff --git a/tests/unit_tests/async_events/async_query_manager_tests.py b/tests/unit_tests/async_events/async_query_manager_tests.py
index edd89612474..91dbd267e05 100644
--- a/tests/unit_tests/async_events/async_query_manager_tests.py
+++ b/tests/unit_tests/async_events/async_query_manager_tests.py
@@ -20,7 +20,7 @@ from unittest.mock import ANY, Mock
from flask import g
from jwt import encode
-from pytest import fixture, mark, raises # noqa: PT013
+from pytest import fixture, raises # noqa: PT013
from superset import security_manager
from superset.async_events.async_query_manager import (
@@ -30,7 +30,6 @@ from superset.async_events.async_query_manager import (
)
from superset.async_events.cache_backend import (
RedisCacheBackend,
- RedisSentinelCacheBackend,
)
from superset.utils import json
@@ -263,23 +262,15 @@ def test_parse_channel_id_from_request_as_guest_user_differs_per_scope(
assert with_datasets != with_rev
-@mark.parametrize(
- "cache_type, cache_backend",
- [
- ("RedisCacheBackend", mock.Mock(spec=RedisCacheBackend)),
- ("RedisSentinelCacheBackend", mock.Mock(spec=RedisSentinelCacheBackend)),
- ],
-)
@mock.patch("superset.is_feature_enabled")
def test_submit_chart_data_job_as_guest_user(
- is_feature_enabled_mock, async_query_manager, cache_type, cache_backend
+ is_feature_enabled_mock, async_query_manager
):
is_feature_enabled_mock.return_value = True
set_current_as_guest_user()
- # Mock the get_cache_backend method to return the current cache backend
- async_query_manager.get_cache_backend = mock.Mock(return_value=cache_backend)
-
+ # The manager has no GAQ backend wired (init_app not run), so the best-effort
+ # cancel registry write is skipped and submission still proceeds.
job_mock = Mock()
async_query_manager._load_chart_data_into_cache_job = job_mock
job_meta = async_query_manager.submit_chart_data_job(
@@ -370,32 +361,40 @@ def test_validate_session_guest_user_creates_valid_token(async_query_manager):
@fixture
-def cancellable_manager():
+def coordination_backend():
+ """A mock Redis backend GAQ operates against as its own dedicated backend."""
+ return mock.Mock(spec=RedisCacheBackend)
+
+
+@fixture
+def cancellable_manager(coordination_backend):
"""A manager wired to a mock Redis backend for cancellation tests."""
manager = AsyncQueryManager()
manager._jwt_expiration_seconds = 3600
manager._stream_prefix = "async-events-"
- manager._cache = mock.Mock(spec=RedisCacheBackend)
+ manager._gaq_backend = coordination_backend
return manager
-def test_init_job_registers_cancellable_record(cancellable_manager):
+def test_init_job_registers_cancellable_record(
+ cancellable_manager, coordination_backend
+):
"""init_job persists the owner identity a later cancel must match."""
cancellable_manager.init_job("chan-1", 7)
- cancellable_manager._cache.set.assert_called_once()
- key, value = cancellable_manager._cache.set.call_args.args
+ coordination_backend.set.assert_called_once()
+ key, value = coordination_backend.set.call_args.args
assert key.startswith("async-events-job-cancel:")
assert json.loads(value) == {"channel_id": "chan-1", "user_id": 7}
-def test_cancel_job_authorized_revokes_task(cancellable_manager):
+def test_cancel_job_authorized_revokes_task(cancellable_manager, coordination_backend):
cancellable_manager._stream_limit = 100
cancellable_manager._stream_limit_firehose = 1000
- cancellable_manager._cache.get.return_value = json.dumps(
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
- cancellable_manager._cache.set.return_value = True
+ coordination_backend.set.return_value = True
with mock.patch("superset.extensions.celery_app") as celery_app:
cancellable_manager.cancel_job("job-1", "chan-1", 7)
@@ -405,26 +404,24 @@ def test_cancel_job_authorized_revokes_task(cancellable_manager):
)
# The job is flagged cancelled (conditionally, xx=True) so the worker knows
# what the signal it is about to receive means.
- assert cancellable_manager._cache.set.call_args.kwargs["xx"] is True
- flagged = json.loads(cancellable_manager._cache.set.call_args.args[1])
+ assert coordination_backend.set.call_args.kwargs["xx"] is True
+ flagged = json.loads(coordination_backend.set.call_args.args[1])
assert flagged["cancelled"] is True
-def test_cancel_job_emits_the_terminal_event(cancellable_manager):
+def test_cancel_job_emits_the_terminal_event(cancellable_manager, coordination_backend):
"""A task revoked before a worker picks it up never reports on itself."""
cancellable_manager._stream_limit = 100
cancellable_manager._stream_limit_firehose = 1000
- cancellable_manager._cache.get.return_value = json.dumps(
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
- cancellable_manager._cache.set.return_value = True
+ coordination_backend.set.return_value = True
with mock.patch("superset.extensions.celery_app"):
cancellable_manager.cancel_job("job-1", "chan-1", 7)
- scoped_stream, event_data = cancellable_manager._cache.xadd.call_args_list[0].args[
- :2
- ]
+ scoped_stream, event_data = coordination_backend.xadd.call_args_list[0].args[:2]
assert scoped_stream == "async-events-chan-1"
assert json.loads(event_data["data"]) == {
"channel_id": "chan-1",
@@ -436,16 +433,18 @@ def test_cancel_job_emits_the_terminal_event(cancellable_manager):
}
# the record has to outlive the event: the worker still needs to recognize
# the signal on its way as a cancellation
- cancellable_manager._cache.delete.assert_not_called()
+ coordination_backend.delete.assert_not_called()
-def test_cancel_job_completed_between_read_and_flag(cancellable_manager):
+def test_cancel_job_completed_between_read_and_flag(
+ cancellable_manager, coordination_backend
+):
"""If the job's record is cleared after the auth read, don't revoke."""
- cancellable_manager._cache.get.return_value = json.dumps(
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
# Conditional (xx) write finds no key: the job finished and cleaned up.
- cancellable_manager._cache.set.return_value = None
+ coordination_backend.set.return_value = None
with (
mock.patch("superset.extensions.celery_app") as celery_app,
@@ -456,8 +455,8 @@ def test_cancel_job_completed_between_read_and_flag(cancellable_manager):
celery_app.control.revoke.assert_not_called()
-def test_cancel_job_wrong_user_is_rejected(cancellable_manager):
- cancellable_manager._cache.get.return_value = json.dumps(
+def test_cancel_job_wrong_user_is_rejected(cancellable_manager, coordination_backend):
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
@@ -470,9 +469,11 @@ def test_cancel_job_wrong_user_is_rejected(cancellable_manager):
celery_app.control.revoke.assert_not_called()
-def test_cancel_job_wrong_channel_is_rejected(cancellable_manager):
+def test_cancel_job_wrong_channel_is_rejected(
+ cancellable_manager, coordination_backend
+):
"""A matching user on a different channel still cannot cancel the job."""
- cancellable_manager._cache.get.return_value = json.dumps(
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
@@ -485,8 +486,8 @@ def test_cancel_job_wrong_channel_is_rejected(cancellable_manager):
celery_app.control.revoke.assert_not_called()
-def test_cancel_job_unknown_raises(cancellable_manager):
- cancellable_manager._cache.get.return_value = None
+def test_cancel_job_unknown_raises(cancellable_manager, coordination_backend):
+ coordination_backend.get.return_value = None
with (
mock.patch("superset.extensions.celery_app") as celery_app,
@@ -497,39 +498,41 @@ def test_cancel_job_unknown_raises(cancellable_manager):
celery_app.control.revoke.assert_not_called()
-def test_is_job_cancelled(cancellable_manager):
- cancellable_manager._cache.get.return_value = json.dumps(
+def test_is_job_cancelled(cancellable_manager, coordination_backend):
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7, "cancelled": True}
)
assert cancellable_manager.is_job_cancelled("job-1") is True
- cancellable_manager._cache.get.return_value = json.dumps(
+ coordination_backend.get.return_value = json.dumps(
{"channel_id": "chan-1", "user_id": 7}
)
assert cancellable_manager.is_job_cancelled("job-1") is False
- cancellable_manager._cache.get.return_value = None
+ coordination_backend.get.return_value = None
assert cancellable_manager.is_job_cancelled("job-1") is False
-def test_is_job_cancelled_swallows_cache_errors(cancellable_manager):
+def test_is_job_cancelled_swallows_cache_errors(
+ cancellable_manager, coordination_backend
+):
"""A cache failure must not escape and mask the worker's original error."""
- cancellable_manager._cache.get.side_effect = RuntimeError("redis down")
+ coordination_backend.get.side_effect = RuntimeError("redis down")
assert cancellable_manager.is_job_cancelled("job-1") is False
-def test_update_job_clears_registry_before_terminal_event(cancellable_manager):
+def test_update_job_clears_registry_before_terminal_event(
+ cancellable_manager, coordination_backend
+):
"""Clearing first is what makes a cancel that lost the race a 404."""
calls = []
cancellable_manager._stream_limit = 100
cancellable_manager._stream_limit_firehose = 1000
- cancellable_manager._cache.delete.side_effect = lambda *_: calls.append("delete")
- cancellable_manager._cache.xadd.side_effect = lambda *_: calls.append("xadd")
+ coordination_backend.delete.side_effect = lambda *_: calls.append("delete")
+ coordination_backend.xadd.side_effect = lambda *_: calls.append("xadd")
job_metadata = {"channel_id": "chan-1", "job_id": "job-1", "user_id": 7}
cancellable_manager.update_job(job_metadata, AsyncQueryManager.STATUS_DONE)
- cancellable_manager._cache.delete.assert_called_once_with(
- "async-events-job-cancel:job-1"
- )
+ coordination_backend.delete.assert_called_once_with("async-events-job-cancel:job-1")
assert calls == ["delete", "xadd", "xadd"]
diff --git a/tests/unit_tests/coordination/__init__.py b/tests/unit_tests/coordination/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/tests/unit_tests/coordination/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git a/tests/unit_tests/coordination/test_service.py b/tests/unit_tests/coordination/test_service.py
new file mode 100644
index 00000000000..c665ae37a9b
--- /dev/null
+++ b/tests/unit_tests/coordination/test_service.py
@@ -0,0 +1,240 @@
+# 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.
+from __future__ import annotations
+
+import threading
+
+import pytest
+from pytest_mock import MockerFixture
+
+from superset.coordination.base import CoordinationService
+from superset.coordination.exceptions import CoordinationBackendUnavailableError
+from superset.coordination.types import SignalListener
+
+
+def _patch_distributed_coordination(mocker: MockerFixture, backend: object) -> None:
+ mocker.patch(
+ "superset.utils.cache_manager.CacheManager.distributed_coordination",
+ new_callable=mocker.PropertyMock,
+ return_value=backend,
+ )
+
+
+def test_get_backend_prefers_distributed_coordination(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ backend = mocker.MagicMock(name="coordination_backend")
+ _patch_distributed_coordination(mocker, backend)
+
+ assert CoordinationService.get_backend() is backend
+ assert CoordinationService.is_backend_defined() is True
+
+
+def test_get_backend_none_when_distributed_coordination_unset(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ _patch_distributed_coordination(mocker, None)
+
+ assert CoordinationService.get_backend() is None
+ assert CoordinationService.is_backend_defined() is False
+
+
+def test_get_backend_ignores_legacy_gaq_config(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ # The coordinator resolves DISTRIBUTED_COORDINATION_CONFIG only; the deprecated
+ # GAQ backend must never leak into locks/GTF, even with GAQ enabled.
+ _patch_distributed_coordination(mocker, None)
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ mocker.patch.dict(
+ "flask.current_app.config",
+ {"GLOBAL_ASYNC_QUERIES_CACHE_BACKEND": {"CACHE_TYPE": "RedisCache"}},
+ )
+ get_cache_backend = mocker.patch(
+ "superset.async_events.async_query_manager.get_cache_backend",
+ )
+
+ assert CoordinationService.get_backend() is None
+ assert CoordinationService.is_backend_defined() is False
+ get_cache_backend.assert_not_called()
+
+
+def test_backend_only_ops_raise_when_backend_unavailable(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ _patch_distributed_coordination(mocker, None)
+
+ for op in (
+ lambda: CoordinationService.publish("channel", "msg"),
+ lambda: CoordinationService.get_value("key"),
+ lambda: CoordinationService.set_value("key", "value"),
+ lambda: CoordinationService.delete_value("key"),
+ lambda: CoordinationService.stream_add("stream", {"data": "x"}),
+ lambda: CoordinationService.stream_range("stream"),
+ ):
+ with pytest.raises(CoordinationBackendUnavailableError):
+ op()
+
+
+def test_ops_use_explicit_backend_without_resolving_coordinator(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ # An explicit backend (e.g. GAQ's own) is used directly; the shared coordinator
+ # is never consulted.
+ get_backend = mocker.patch.object(
+ CoordinationService, "get_backend", side_effect=AssertionError("resolved")
+ )
+ backend = mocker.MagicMock(name="explicit_backend")
+ backend.xadd.return_value = "1-0"
+
+ assert (
+ CoordinationService.stream_add("stream", {"data": "x"}, backend=backend)
+ == "1-0"
+ )
+ backend.xadd.assert_called_once_with("stream", {"data": "x"}, "*", None)
+ get_backend.assert_not_called()
+
+
+def test_ops_delegate_to_backend(app_context: None, mocker: MockerFixture) -> None:
+ backend = mocker.MagicMock(name="coordination_backend")
+ backend.publish.return_value = 3
+ backend.get.return_value = b"v"
+ backend.set.return_value = True
+ backend.delete.return_value = 1
+ backend.xadd.return_value = "1-0"
+ backend.xrange.return_value = [("1-0", {"data": "x"})]
+ _patch_distributed_coordination(mocker, backend)
+
+ assert CoordinationService.publish("chan", "msg") == 3
+ assert CoordinationService.get_value("k") == b"v"
+ assert CoordinationService.set_value("k", "v", ttl=10, if_present=True) is True
+ assert CoordinationService.delete_value("k") == 1
+ assert CoordinationService.stream_add("stream", {"data": "x"}, "*", 100) == "1-0"
+ assert CoordinationService.stream_range("stream", "-", "+", 10) == [
+ ("1-0", {"data": "x"})
+ ]
+ backend.publish.assert_called_once_with("chan", "msg")
+ # The generalized set() flags map onto the backend's Redis-native kwargs.
+ backend.set.assert_called_once_with("k", "v", ex=10, nx=False, xx=True)
+ backend.delete.assert_called_once_with("k")
+ backend.xadd.assert_called_once_with("stream", {"data": "x"}, "*", 100)
+ backend.xrange.assert_called_once_with("stream", "-", "+", 10)
+
+
+# -- wait_for_signal / listen --------------------------------------------------
+
+
+def test_wait_for_signal_returns_when_check_satisfied(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ mocker.patch.object(CoordinationService, "get_backend", return_value=None)
+ assert CoordinationService.wait_for_signal("ch", lambda: "done") == "done"
+
+
+def test_wait_for_signal_polls_until_satisfied_without_backend(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ mocker.patch.object(CoordinationService, "get_backend", return_value=None)
+ results = iter([None, "done"])
+
+ result = CoordinationService.wait_for_signal(
+ "ch", lambda: next(results), poll_interval=0.01
+ )
+ assert result == "done"
+
+
+def test_wait_for_signal_times_out(app_context: None, mocker: MockerFixture) -> None:
+ mocker.patch.object(CoordinationService, "get_backend", return_value=None)
+ with pytest.raises(TimeoutError):
+ CoordinationService.wait_for_signal(
+ "ch", lambda: None, timeout=0.05, poll_interval=0.01
+ )
+
+
+def test_wait_for_signal_wakes_via_pubsub_and_cleans_up(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ backend = mocker.MagicMock(name="backend")
+ pubsub = mocker.MagicMock(name="pubsub")
+ backend.pubsub.return_value = pubsub
+ mocker.patch.object(CoordinationService, "get_backend", return_value=backend)
+ # First check (pre-subscribe fast path) is None, so we subscribe; the next None
+ # forces one pub/sub nudge, then "done" satisfies the wait.
+ results = iter([None, None, "done"])
+
+ result = CoordinationService.wait_for_signal(
+ "ch", lambda: next(results), timeout=5.0
+ )
+ assert result == "done"
+ pubsub.subscribe.assert_called_once_with("ch")
+ # One wake-up nudge between the post-subscribe (None) and final (done) check.
+ pubsub.get_message.assert_called_once()
+ pubsub.unsubscribe.assert_called_once()
+ pubsub.close.assert_called_once()
+
+
+def test_wait_for_signal_already_satisfied_skips_backend(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ # An already-satisfied predicate returns straight from the source of truth,
+ # without resolving or subscribing to a backend — so an already-terminal task
+ # does not require Redis to be reachable.
+ backend = mocker.MagicMock(name="backend")
+ get_backend = mocker.patch.object(
+ CoordinationService, "get_backend", return_value=backend
+ )
+
+ assert CoordinationService.wait_for_signal("ch", lambda: "done") == "done"
+ get_backend.assert_not_called()
+ backend.pubsub.assert_not_called()
+
+
+def test_listen_invokes_on_signal_then_stops(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ mocker.patch.object(CoordinationService, "get_backend", return_value=None)
+ fired = threading.Event()
+
+ listener = CoordinationService.listen_for_signal(
+ "ch", check=lambda: True, on_signal=fired.set, poll_interval=0.01, name="t"
+ )
+ assert fired.wait(timeout=2.0) is True
+ listener.stop()
+
+
+def test_listen_does_not_fire_when_condition_never_met(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ mocker.patch.object(CoordinationService, "get_backend", return_value=None)
+ on_signal = mocker.MagicMock()
+
+ listener = CoordinationService.listen_for_signal(
+ "ch", check=lambda: False, on_signal=on_signal, poll_interval=0.01
+ )
+ listener.stop()
+ on_signal.assert_not_called()
+
+
+def test_signal_listener_stop_signals_and_joins(mocker: MockerFixture) -> None:
+ thread = mocker.MagicMock(name="thread")
+ thread.is_alive.side_effect = [True, False]
+ stop_event = threading.Event()
+
+ SignalListener(thread, stop_event).stop()
+
+ assert stop_event.is_set()
+ thread.join.assert_called_once_with(timeout=2.0)
diff --git a/tests/unit_tests/distributed_lock/distributed_lock_tests.py b/tests/unit_tests/distributed_lock/distributed_lock_tests.py
index 3b22c3adc43..b9eb4b4d136 100644
--- a/tests/unit_tests/distributed_lock/distributed_lock_tests.py
+++ b/tests/unit_tests/distributed_lock/distributed_lock_tests.py
@@ -18,16 +18,13 @@
# pylint: disable=invalid-name
from typing import Any
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from uuid import UUID
import pytest
from freezegun import freeze_time
from sqlalchemy.orm import Session, sessionmaker
-# Force module loading before tests run so patches work correctly
-import superset.commands.distributed_lock.acquire as acquire_module
-import superset.commands.distributed_lock.release as release_module
from superset import db
from superset.distributed_lock import DistributedLock
from superset.distributed_lock.types import LockValue
@@ -39,6 +36,12 @@ LOCK_VALUE: LockValue = {"value": True}
MAIN_KEY = get_key("ns", a=1, b=2)
OTHER_KEY = get_key("ns2", a=1, b=2)
+# Distributed locking is plumbed through the coordination service: acquire/release
+# call CoordinationService.set_value/delete_value when a backend is defined, else KV.
+BACKEND_DEFINED = "superset.coordination.base.CoordinationService.is_backend_defined"
+COORD_SET = "superset.coordination.base.CoordinationService.set_value"
+COORD_DELETE = "superset.coordination.base.CoordinationService.delete_value"
+
def _get_lock(key: UUID, session: Session) -> Any:
from superset.key_value.models import KeyValueEntry
@@ -70,11 +73,8 @@ def test_distributed_lock_kv_happy_path() -> None:
"""
session = _get_other_session()
- # Ensure Redis is not configured so KV backend is used
- with (
- patch.object(acquire_module, "get_redis_client", return_value=None),
- patch.object(release_module, "get_redis_client", return_value=None),
- ):
+ # Ensure no backend is defined so the KV backend is used
+ with patch(BACKEND_DEFINED, return_value=False):
with freeze_time("2021-01-01"):
assert _get_lock(MAIN_KEY, session) is None
@@ -100,11 +100,8 @@ def test_distributed_lock_kv_expired() -> None:
"""
session = _get_other_session()
- # Ensure Redis is not configured so KV backend is used
- with (
- patch.object(acquire_module, "get_redis_client", return_value=None),
- patch.object(release_module, "get_redis_client", return_value=None),
- ):
+ # Ensure no backend is defined so the KV backend is used
+ with patch(BACKEND_DEFINED, return_value=False):
with freeze_time("2021-01-01"):
assert _get_lock(MAIN_KEY, session) is None
with DistributedLock("ns", a=1, b=2):
@@ -116,33 +113,30 @@ def test_distributed_lock_kv_expired() -> None:
def test_distributed_lock_uses_redis_when_configured() -> None:
- """Test that DistributedLock uses Redis backend when configured."""
- mock_redis = MagicMock()
- mock_redis.set.return_value = True # Lock acquired
-
- # Use patch.object to patch on already-imported modules
+ """Test that DistributedLock uses the coordination backend when configured."""
with (
- patch.object(acquire_module, "get_redis_client", return_value=mock_redis),
- patch.object(release_module, "get_redis_client", return_value=mock_redis),
+ patch(BACKEND_DEFINED, return_value=True),
+ patch(COORD_SET, return_value=True) as mock_set,
+ patch(COORD_DELETE) as mock_delete,
):
with DistributedLock("test_redis", key="value") as lock_key:
assert lock_key is not None
# Verify SET NX EX was called
- mock_redis.set.assert_called_once()
- call_args = mock_redis.set.call_args
- assert call_args.kwargs["nx"] is True
- assert "ex" in call_args.kwargs
+ mock_set.assert_called_once()
+ call_args = mock_set.call_args
+ assert call_args.kwargs["if_absent"] is True
+ assert "ttl" in call_args.kwargs
# Verify DELETE was called on exit
- mock_redis.delete.assert_called_once()
+ mock_delete.assert_called_once()
def test_distributed_lock_redis_already_taken() -> None:
"""Test Redis lock fails when already held."""
- mock_redis = MagicMock()
- mock_redis.set.return_value = None # Lock not acquired (already taken)
-
- with patch.object(acquire_module, "get_redis_client", return_value=mock_redis):
+ with (
+ patch(BACKEND_DEFINED, return_value=True),
+ patch(COORD_SET, return_value=None), # Lock not acquired (already taken)
+ ):
with pytest.raises(AcquireDistributedLockFailedException):
with DistributedLock("test_redis", key="value"):
pass
@@ -152,10 +146,10 @@ def test_distributed_lock_redis_connection_error() -> None:
"""Test Redis connection error raises exception (fail fast)."""
import redis
- mock_redis = MagicMock()
- mock_redis.set.side_effect = redis.RedisError("Connection failed")
-
- with patch.object(acquire_module, "get_redis_client", return_value=mock_redis):
+ with (
+ patch(BACKEND_DEFINED, return_value=True),
+ patch(COORD_SET, side_effect=redis.RedisError("Connection failed")),
+ ):
with pytest.raises(AcquireDistributedLockFailedException):
with DistributedLock("test_redis", key="value"):
pass
@@ -163,45 +157,38 @@ def test_distributed_lock_redis_connection_error() -> None:
def test_distributed_lock_custom_ttl() -> None:
"""Test Redis lock with custom TTL."""
- mock_redis = MagicMock()
- mock_redis.set.return_value = True
-
with (
- patch.object(acquire_module, "get_redis_client", return_value=mock_redis),
- patch.object(release_module, "get_redis_client", return_value=mock_redis),
+ patch(BACKEND_DEFINED, return_value=True),
+ patch(COORD_SET, return_value=True) as mock_set,
+ patch(COORD_DELETE),
):
with DistributedLock("test", ttl_seconds=60, key="value"):
- call_args = mock_redis.set.call_args
- assert call_args.kwargs["ex"] == 60 # Custom TTL
+ call_args = mock_set.call_args
+ assert call_args.kwargs["ttl"] == 60 # Custom TTL
def test_distributed_lock_default_ttl(app_context: None) -> None:
"""Test Redis lock uses default TTL when not specified."""
from superset.commands.distributed_lock.base import get_default_lock_ttl
- mock_redis = MagicMock()
- mock_redis.set.return_value = True
-
with (
- patch.object(acquire_module, "get_redis_client", return_value=mock_redis),
- patch.object(release_module, "get_redis_client", return_value=mock_redis),
+ patch(BACKEND_DEFINED, return_value=True),
+ patch(COORD_SET, return_value=True) as mock_set,
+ patch(COORD_DELETE),
):
with DistributedLock("test", key="value"):
- call_args = mock_redis.set.call_args
- assert call_args.kwargs["ex"] == get_default_lock_ttl()
+ call_args = mock_set.call_args
+ assert call_args.kwargs["ttl"] == get_default_lock_ttl()
def test_distributed_lock_fallback_to_kv_when_redis_not_configured() -> None:
- """Test falls back to KV lock when Redis not configured."""
+ """Test falls back to KV lock when no backend is configured."""
session = _get_other_session()
test_key = get_key("test_fallback", key="value")
- with (
- patch.object(acquire_module, "get_redis_client", return_value=None),
- patch.object(release_module, "get_redis_client", return_value=None),
- ):
+ with patch(BACKEND_DEFINED, return_value=False):
with freeze_time("2021-01-01"):
- # When Redis is not configured, should use KV backend
+ # When no backend is defined, should use KV backend
with DistributedLock("test_fallback", key="value") as lock_key:
assert lock_key == test_key
# Verify lock exists in KV store
diff --git a/tests/unit_tests/tasks/test_handlers.py b/tests/unit_tests/tasks/test_handlers.py
index 9e50e82ea7b..0105c55ce96 100644
--- a/tests/unit_tests/tasks/test_handlers.py
+++ b/tests/unit_tests/tasks/test_handlers.py
@@ -80,11 +80,11 @@ def task_context(mock_task, mock_task_dao, mock_update_command, mock_flask_app):
with (
patch("superset.tasks.context.current_app") as mock_current_app,
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
# Configure current_app mock
mock_current_app.config = mock_flask_app.config
# Use regular Mock (not MagicMock) for _get_current_object to avoid
diff --git a/tests/unit_tests/tasks/test_manager.py b/tests/unit_tests/tasks/test_manager.py
index 9f10c4da59b..5a309f7d8fa 100644
--- a/tests/unit_tests/tasks/test_manager.py
+++ b/tests/unit_tests/tasks/test_manager.py
@@ -14,71 +14,38 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Unit tests for TaskManager pub/sub functionality"""
+"""Unit tests for TaskManager.
+
+Since PR #43316, the pub/sub-wake-else-poll orchestration lives in
+``CoordinationService`` (``publish`` / ``wait_for_signal`` / ``listen_for_signal``);
+the tests here cover TaskManager's thin GTF-facing layer: channel naming, publishing
+task signals through the service, and delegating waits/abort-listens to it.
+"""
-import threading
-import time
from unittest.mock import MagicMock, patch
+import pytest
import redis
-from superset.tasks.manager import AbortListener, TaskManager
-
-
-class TestAbortListener:
- """Tests for AbortListener class"""
-
- def test_stop_sets_event(self):
- """Test that stop() sets the stop event"""
- stop_event = threading.Event()
- thread = MagicMock(spec=threading.Thread)
- thread.is_alive.return_value = False
+from superset.tasks.manager import TaskManager
- listener = AbortListener("test-uuid", thread, stop_event)
+GET_BACKEND = "superset.coordination.base.CoordinationService.get_backend"
- assert not stop_event.is_set()
- listener.stop()
- assert stop_event.is_set()
- def test_stop_closes_pubsub(self):
- """Test that stop() closes the pub/sub connection"""
- stop_event = threading.Event()
- thread = MagicMock(spec=threading.Thread)
- thread.is_alive.return_value = False
- pubsub = MagicMock()
-
- listener = AbortListener("test-uuid", thread, stop_event, pubsub)
- listener.stop()
-
- pubsub.unsubscribe.assert_called_once()
- pubsub.close.assert_called_once()
-
- def test_stop_joins_thread(self):
- """Test that stop() joins the listener thread"""
- stop_event = threading.Event()
- thread = MagicMock(spec=threading.Thread)
- thread.is_alive.return_value = True
-
- listener = AbortListener("test-uuid", thread, stop_event)
- listener.stop()
-
- thread.join.assert_called_once_with(timeout=2.0)
+def _reset_prefixes() -> None:
+ TaskManager._initialized = False
+ TaskManager._channel_prefix = "gtf:abort:"
+ TaskManager._completion_channel_prefix = "gtf:complete:"
class TestTaskManagerInitApp:
"""Tests for TaskManager.init_app()"""
def setup_method(self):
- """Reset TaskManager state before each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
def teardown_method(self):
- """Reset TaskManager state after each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
def test_init_app_sets_channel_prefixes(self):
"""Test init_app reads channel prefixes from config"""
@@ -101,357 +68,197 @@ class TestTaskManagerInitApp:
app = MagicMock()
TaskManager.init_app(app)
- # Should not call app.config.get since already initialized
app.config.get.assert_not_called()
-class TestTaskManagerPubSub:
- """Tests for TaskManager pub/sub methods"""
+class TestTaskManagerChannels:
+ """Tests for the abort/completion channel naming."""
def setup_method(self):
- """Reset TaskManager state before each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
def teardown_method(self):
- """Reset TaskManager state after each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
-
- @patch("superset.tasks.manager.cache_manager")
- def test_is_pubsub_available_no_redis(self, mock_cache_manager):
- """Test is_pubsub_available returns False when Redis not configured"""
- mock_cache_manager.distributed_coordination = None
- assert TaskManager.is_pubsub_available() is False
-
- @patch("superset.tasks.manager.cache_manager")
- def test_is_pubsub_available_with_redis(self, mock_cache_manager):
- """Test is_pubsub_available returns True when Redis is configured"""
- mock_cache_manager.distributed_coordination = MagicMock()
- assert TaskManager.is_pubsub_available() is True
+ _reset_prefixes()
def test_get_abort_channel(self):
- """Test get_abort_channel returns correct channel name"""
- task_uuid = "abc-123-def-456"
- channel = TaskManager.get_abort_channel(task_uuid)
- assert channel == "gtf:abort:abc-123-def-456"
+ assert TaskManager.get_abort_channel("abc-123") == "gtf:abort:abc-123"
def test_get_abort_channel_custom_prefix(self):
- """Test get_abort_channel with custom prefix"""
TaskManager._channel_prefix = "custom:prefix:"
- task_uuid = "test-uuid"
- channel = TaskManager.get_abort_channel(task_uuid)
- assert channel == "custom:prefix:test-uuid"
-
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_abort_no_redis(self, mock_cache_manager):
- """Test publish_abort returns False when Redis not available"""
- mock_cache_manager.distributed_coordination = None
- result = TaskManager.publish_abort("test-uuid")
- assert result is False
-
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_abort_success(self, mock_cache_manager):
- """Test publish_abort publishes message successfully"""
- mock_redis = MagicMock()
- mock_redis.publish.return_value = 1 # One subscriber
- mock_cache_manager.distributed_coordination = mock_redis
-
- result = TaskManager.publish_abort("test-uuid")
+ assert TaskManager.get_abort_channel("test-uuid") == "custom:prefix:test-uuid"
- assert result is True
- mock_redis.publish.assert_called_once_with("gtf:abort:test-uuid", "abort")
-
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_abort_redis_error(self, mock_cache_manager):
- """Test publish_abort handles Redis errors gracefully"""
- mock_redis = MagicMock()
- mock_redis.publish.side_effect = redis.RedisError("Connection lost")
- mock_cache_manager.distributed_coordination = mock_redis
-
- result = TaskManager.publish_abort("test-uuid")
+ def test_get_completion_channel(self):
+ assert TaskManager.get_completion_channel("abc-123") == "gtf:complete:abc-123"
- assert result is False
+ def test_get_completion_channel_custom_prefix(self):
+ TaskManager._completion_channel_prefix = "custom:complete:"
+ assert (
+ TaskManager.get_completion_channel("test-uuid")
+ == "custom:complete:test-uuid"
+ )
-class TestTaskManagerListenForAbort:
- """Tests for TaskManager.listen_for_abort()"""
+class TestTaskManagerPublish:
+ """publish_abort / publish_completion route through CoordinationService."""
def setup_method(self):
- """Reset TaskManager state before each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
def teardown_method(self):
- """Reset TaskManager state after each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
-
- @patch("superset.tasks.manager.cache_manager")
- def test_listen_for_abort_no_redis_uses_polling(self, mock_cache_manager):
- """Test listen_for_abort falls back to polling when Redis unavailable"""
- mock_cache_manager.distributed_coordination = None
- callback = MagicMock()
+ _reset_prefixes()
- with patch.object(TaskManager, "_poll_for_abort", return_value=None):
- listener = TaskManager.listen_for_abort(
- task_uuid="test-uuid",
- callback=callback,
- poll_interval=1.0,
- app=None,
- )
-
- # Give thread time to start
- time.sleep(0.1)
- listener.stop()
+ @patch(GET_BACKEND, return_value=None)
+ def test_publish_abort_no_backend(self, mock_backend):
+ assert TaskManager.publish_abort("test-uuid") is False
- # Should use polling since no Redis
- assert listener._pubsub is None
+ @patch(GET_BACKEND)
+ def test_publish_abort_success(self, mock_get_backend):
+ backend = MagicMock()
+ backend.publish.return_value = 1
+ mock_get_backend.return_value = backend
- @patch("superset.tasks.manager.cache_manager")
- def test_listen_for_abort_with_redis_uses_pubsub(self, mock_cache_manager):
- """Test listen_for_abort uses pub/sub when Redis available"""
- mock_redis = MagicMock()
- mock_pubsub = MagicMock()
- mock_redis.pubsub.return_value = mock_pubsub
- mock_cache_manager.distributed_coordination = mock_redis
+ assert TaskManager.publish_abort("test-uuid") is True
+ backend.publish.assert_called_once_with("gtf:abort:test-uuid", "abort")
- callback = MagicMock()
+ @patch(GET_BACKEND)
+ def test_publish_abort_redis_error(self, mock_get_backend):
+ backend = MagicMock()
+ backend.publish.side_effect = redis.RedisError("Connection lost")
+ mock_get_backend.return_value = backend
- with patch.object(TaskManager, "_listen_pubsub", return_value=None):
- listener = TaskManager.listen_for_abort(
- task_uuid="test-uuid",
- callback=callback,
- poll_interval=1.0,
- app=None,
- )
+ assert TaskManager.publish_abort("test-uuid") is False
- # Give thread time to start
- time.sleep(0.1)
- listener.stop()
+ @patch(GET_BACKEND, return_value=None)
+ def test_publish_completion_no_backend(self, mock_backend):
+ assert TaskManager.publish_completion("test-uuid", "success") is False
- # Should subscribe to channel
- mock_pubsub.subscribe.assert_called_once_with("gtf:abort:test-uuid")
+ @patch(GET_BACKEND)
+ def test_publish_completion_success(self, mock_get_backend):
+ backend = MagicMock()
+ backend.publish.return_value = 1
+ mock_get_backend.return_value = backend
- @patch("superset.tasks.manager.cache_manager")
- def test_listen_for_abort_redis_subscribe_failure_raises(self, mock_cache_manager):
- """Test listen_for_abort raises exception on subscribe failure
- when Redis configured"""
- import pytest
+ assert TaskManager.publish_completion("test-uuid", "success") is True
+ backend.publish.assert_called_once_with("gtf:complete:test-uuid", "success")
- mock_redis = MagicMock()
- mock_redis.pubsub.side_effect = redis.RedisError("Connection failed")
- mock_cache_manager.distributed_coordination = mock_redis
+ @patch(GET_BACKEND)
+ def test_publish_completion_redis_error(self, mock_get_backend):
+ backend = MagicMock()
+ backend.publish.side_effect = redis.RedisError("Connection lost")
+ mock_get_backend.return_value = backend
- callback = MagicMock()
-
- # With fail-fast behavior, Redis subscribe failure raises exception
- with pytest.raises(redis.RedisError, match="Connection failed"):
- TaskManager.listen_for_abort(
- task_uuid="test-uuid",
- callback=callback,
- poll_interval=1.0,
- app=None,
- )
+ assert TaskManager.publish_completion("test-uuid", "success") is False
-class TestTaskManagerCompletion:
- """Tests for TaskManager completion pub/sub and wait_for_completion"""
+class TestTaskManagerListenForAbort:
+ """listen_for_abort delegates to CoordinationService.listen_for_signal()."""
def setup_method(self):
- """Reset TaskManager state before each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
def teardown_method(self):
- """Reset TaskManager state after each test"""
- TaskManager._initialized = False
- TaskManager._channel_prefix = "gtf:abort:"
- TaskManager._completion_channel_prefix = "gtf:complete:"
+ _reset_prefixes()
- def test_get_completion_channel(self):
- """Test get_completion_channel returns correct channel name"""
- task_uuid = "abc-123-def-456"
- channel = TaskManager.get_completion_channel(task_uuid)
- assert channel == "gtf:complete:abc-123-def-456"
+ @patch("superset.tasks.manager.TaskManager._check_abort_status")
+ @patch("superset.coordination.base.CoordinationService.listen_for_signal")
+ def test_listen_for_abort_delegates_channel_and_predicate(
+ self, mock_listen, mock_check
+ ):
+ sentinel = MagicMock(name="listener")
+ mock_listen.return_value = sentinel
+ callback = MagicMock()
- def test_get_completion_channel_custom_prefix(self):
- """Test get_completion_channel with custom prefix"""
- TaskManager._completion_channel_prefix = "custom:complete:"
- task_uuid = "test-uuid"
- channel = TaskManager.get_completion_channel(task_uuid)
- assert channel == "custom:complete:test-uuid"
+ listener = TaskManager.listen_for_abort(
+ task_uuid="test-uuid",
+ callback=callback,
+ poll_interval=3.0,
+ app=None,
+ )
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_completion_no_redis(self, mock_cache_manager):
- """Test publish_completion returns False when Redis not available"""
- mock_cache_manager.distributed_coordination = None
- result = TaskManager.publish_completion("test-uuid", "success")
- assert result is False
+ assert listener is sentinel
+ args, kwargs = mock_listen.call_args
+ assert args[0] == "gtf:abort:test-uuid"
+ assert kwargs["poll_interval"] == 3.0
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_completion_success(self, mock_cache_manager):
- """Test publish_completion publishes message successfully"""
- mock_redis = MagicMock()
- mock_redis.publish.return_value = 1 # One subscriber
- mock_cache_manager.distributed_coordination = mock_redis
+ # The predicate closure checks abort status for this task.
+ kwargs["check"]()
+ mock_check.assert_called_once_with("test-uuid")
- result = TaskManager.publish_completion("test-uuid", "success")
+ # The on_signal closure invokes the caller's callback.
+ kwargs["on_signal"]()
+ callback.assert_called_once()
- assert result is True
- mock_redis.publish.assert_called_once_with("gtf:complete:test-uuid", "success")
- @patch("superset.tasks.manager.cache_manager")
- def test_publish_completion_redis_error(self, mock_cache_manager):
- """Test publish_completion handles Redis errors gracefully"""
- mock_redis = MagicMock()
- mock_redis.publish.side_effect = redis.RedisError("Connection lost")
- mock_cache_manager.distributed_coordination = mock_redis
+class TestTaskManagerWaitForCompletion:
+ """wait_for_completion delegates the wait to CoordinationService."""
- result = TaskManager.publish_completion("test-uuid", "success")
+ def setup_method(self):
+ _reset_prefixes()
- assert result is False
+ def teardown_method(self):
+ _reset_prefixes()
- @patch("superset.tasks.manager.cache_manager")
+ @patch(GET_BACKEND, return_value=None)
@patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_task_not_found(self, mock_dao, mock_cache_manager):
- """Test wait_for_completion raises ValueError for missing task"""
- import pytest
-
- mock_cache_manager.distributed_coordination = None
+ def test_task_not_found_raises(self, mock_dao, mock_backend):
mock_dao.find_one_or_none.return_value = None
-
with pytest.raises(ValueError, match="not found"):
TaskManager.wait_for_completion("nonexistent-uuid")
- @patch("superset.tasks.manager.cache_manager")
+ @patch(GET_BACKEND, return_value=None)
@patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_already_complete(self, mock_dao, mock_cache_manager):
- """Test wait_for_completion returns immediately for terminal state"""
- mock_cache_manager.distributed_coordination = None
- mock_task = MagicMock()
- mock_task.uuid = "test-uuid"
- mock_task.status = "success"
- mock_dao.find_one_or_none.return_value = mock_task
-
- result = TaskManager.wait_for_completion("test-uuid")
+ def test_already_complete_returns_immediately(self, mock_dao, mock_backend):
+ task = MagicMock()
+ task.status = "success"
+ mock_dao.find_one_or_none.return_value = task
- assert result == mock_task
- # Should only call find_one_or_none once (initial check)
- mock_dao.find_one_or_none.assert_called_once()
+ assert TaskManager.wait_for_completion("test-uuid") is task
- @patch("superset.tasks.manager.cache_manager")
+ @patch(GET_BACKEND, return_value=None)
@patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_timeout(self, mock_dao, mock_cache_manager):
- """Test wait_for_completion raises TimeoutError when timeout expires"""
- import pytest
+ def test_timeout_raises(self, mock_dao, mock_backend):
+ task = MagicMock()
+ task.status = "in_progress" # never terminal
+ mock_dao.find_one_or_none.return_value = task
- mock_cache_manager.distributed_coordination = None
- mock_task = MagicMock()
- mock_task.uuid = "test-uuid"
- mock_task.status = "in_progress" # Never completes
- mock_dao.find_one_or_none.return_value = mock_task
-
- with pytest.raises(TimeoutError, match="Timeout waiting"):
- TaskManager.wait_for_completion("test-uuid", timeout=0.1)
+ with pytest.raises(TimeoutError, match="Timed out waiting"):
+ TaskManager.wait_for_completion(
+ "test-uuid", timeout=0.05, poll_interval=0.01
+ )
- @patch("superset.tasks.manager.cache_manager")
+ @patch(GET_BACKEND, return_value=None)
@patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_polling_success(self, mock_dao, mock_cache_manager):
- """Test wait_for_completion returns when task completes via polling"""
- mock_cache_manager.distributed_coordination = None
- mock_task_pending = MagicMock()
- mock_task_pending.uuid = "test-uuid"
- mock_task_pending.status = "pending"
-
- mock_task_complete = MagicMock()
- mock_task_complete.uuid = "test-uuid"
- mock_task_complete.status = "success"
-
- # First call returns pending, second returns complete
- mock_dao.find_one_or_none.side_effect = [
- mock_task_pending,
- mock_task_complete,
- ]
+ def test_polling_success(self, mock_dao, mock_backend):
+ pending = MagicMock()
+ pending.status = "pending"
+ complete = MagicMock()
+ complete.status = "success"
+ mock_dao.find_one_or_none.side_effect = [pending, complete]
result = TaskManager.wait_for_completion(
- "test-uuid",
- timeout=5.0,
- poll_interval=0.1,
+ "test-uuid", timeout=5.0, poll_interval=0.01
)
-
assert result.status == "success"
- @patch("superset.tasks.manager.cache_manager")
+ @patch(GET_BACKEND)
@patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_with_pubsub(self, mock_dao, mock_cache_manager):
- """Test wait_for_completion uses pub/sub when Redis available"""
- mock_task_pending = MagicMock()
- mock_task_pending.uuid = "test-uuid"
- mock_task_pending.status = "pending"
-
- mock_task_complete = MagicMock()
- mock_task_complete.uuid = "test-uuid"
- mock_task_complete.status = "success"
-
- # First call returns pending, second returns complete
- mock_dao.find_one_or_none.side_effect = [
- mock_task_pending,
- mock_task_complete,
- ]
-
- # Set up mock Redis with pub/sub
- mock_redis = MagicMock()
- mock_pubsub = MagicMock()
- # Simulate receiving a completion message
- mock_pubsub.get_message.return_value = {
- "type": "message",
- "data": "success",
- }
- mock_redis.pubsub.return_value = mock_pubsub
- mock_cache_manager.distributed_coordination = mock_redis
+ def test_pubsub_success_subscribes_and_cleans_up(self, mock_dao, mock_get_backend):
+ pending = MagicMock()
+ pending.status = "pending"
+ complete = MagicMock()
+ complete.status = "success"
+ # find_one_or_none is called for: the existence check, the pre-subscribe fast
+ # path (still pending → we subscribe), then the post-subscribe check (success).
+ mock_dao.find_one_or_none.side_effect = [pending, pending, complete]
+
+ backend = MagicMock()
+ pubsub = MagicMock()
+ backend.pubsub.return_value = pubsub
+ mock_get_backend.return_value = backend
- result = TaskManager.wait_for_completion(
- "test-uuid",
- timeout=5.0,
- )
+ result = TaskManager.wait_for_completion("test-uuid", timeout=5.0)
assert result.status == "success"
- # Should have subscribed to completion channel
- mock_pubsub.subscribe.assert_called_once_with("gtf:complete:test-uuid")
- # Should have cleaned up
- mock_pubsub.unsubscribe.assert_called_once()
- mock_pubsub.close.assert_called_once()
-
- @patch("superset.tasks.manager.cache_manager")
- @patch("superset.daos.tasks.TaskDAO")
- def test_wait_for_completion_pubsub_error_raises(
- self, mock_dao, mock_cache_manager
- ):
- """Test wait_for_completion raises exception on Redis error when
- Redis configured"""
- import pytest
-
- mock_task_pending = MagicMock()
- mock_task_pending.uuid = "test-uuid"
- mock_task_pending.status = "pending"
-
- mock_dao.find_one_or_none.return_value = mock_task_pending
-
- # Set up mock Redis that fails
- mock_redis = MagicMock()
- mock_redis.pubsub.side_effect = redis.RedisError("Connection failed")
- mock_cache_manager.distributed_coordination = mock_redis
-
- # With fail-fast behavior, Redis error is raised instead of falling back
- with pytest.raises(redis.RedisError, match="Connection failed"):
- TaskManager.wait_for_completion(
- "test-uuid",
- timeout=5.0,
- poll_interval=0.1,
- )
+ pubsub.subscribe.assert_called_once_with("gtf:complete:test-uuid")
+ pubsub.unsubscribe.assert_called_once()
+ pubsub.close.assert_called_once()
diff --git a/tests/unit_tests/tasks/test_timeout.py b/tests/unit_tests/tasks/test_timeout.py
index f66d55e5a17..073fd1878da 100644
--- a/tests/unit_tests/tasks/test_timeout.py
+++ b/tests/unit_tests/tasks/test_timeout.py
@@ -87,11 +87,11 @@ def task_context_for_timeout(mock_flask_app, mock_task_abortable):
with (
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
# Configure current_app mock
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
@@ -275,11 +275,11 @@ class TestTimeoutTrigger:
patch(
"superset.commands.tasks.update.UpdateTaskCommand"
) as mock_update_cmd,
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable
@@ -321,11 +321,11 @@ class TestTimeoutTrigger:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.tasks.context.logger") as mock_logger,
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_not_abortable
@@ -361,11 +361,11 @@ class TestTimeoutTrigger:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.commands.tasks.update.UpdateTaskCommand"),
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable
@@ -467,11 +467,11 @@ class TestTimeoutTerminalState:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.commands.tasks.update.UpdateTaskCommand"),
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable
@@ -508,11 +508,11 @@ class TestTimeoutTerminalState:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.commands.tasks.update.UpdateTaskCommand"),
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable
@@ -545,11 +545,11 @@ class TestTimeoutTerminalState:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.commands.tasks.update.UpdateTaskCommand"),
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable
@@ -582,11 +582,11 @@ class TestTimeoutTerminalState:
patch("superset.tasks.context.current_app") as mock_current_app,
patch("superset.daos.tasks.TaskDAO") as mock_dao,
patch("superset.commands.tasks.update.UpdateTaskCommand"),
- patch("superset.tasks.manager.cache_manager") as mock_cache_manager,
+ patch(
+ "superset.coordination.base.CoordinationService.get_backend",
+ return_value=None,
+ ),
):
- # Disable Redis by making distributed_coordination return None
- mock_cache_manager.distributed_coordination = None
-
mock_current_app.config = mock_flask_app.config
mock_current_app._get_current_object.return_value = mock_flask_app
mock_dao.find_one_or_none.return_value = mock_task_abortable