fix(sandbox): support Redis Cluster for shared sandbox ownership (#8505)

* fix(sandbox): support Redis Cluster for shared sandbox ownership

* fix(gateway): warm Redis Cluster sandbox provider off the event loop

* fix(gateway): preserve sandbox SIGHUP cleanup after cluster warmup
This commit is contained in:
LuisQin 2026-11-23 10:24:35 +08:00 committed by GitHub
parent b4eb44f06f
commit 30cdd2a7bb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 440 additions and 60 deletions

View File

@ -1,7 +1,7 @@
import asyncio
import logging
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress
from contextlib import ExitStack, asynccontextmanager, suppress
from typing import Any
from deerflow_extension_api import (
@ -69,7 +69,7 @@ from app.gateway.routers import (
from app.gateway.trace_middleware import TraceMiddleware
from deerflow.config import app_config as deerflow_app_config
from deerflow.logging_config import DEFAULT_LOG_DATE_FORMAT, DEFAULT_LOG_FORMAT, configure_logging
from deerflow.sandbox.sandbox_provider import hold_sandbox_shutdown_ownership
from deerflow.sandbox.sandbox_provider import get_sandbox_provider, hold_sandbox_shutdown_ownership
from deerflow.tracing.monocle import setup_monocle_tracing_if_enabled
from deerflow.uploads.manager import cleanup_stale_upload_staging_files
from deerflow.utils.file_io import await_drained
@ -591,7 +591,13 @@ async def _start_scheduled_task_notification_delivery(app: FastAPI, startup_conf
@asynccontextmanager
async def _runtime_with_mcp_pool_shutdown(app: FastAPI, startup_config: AppConfig) -> AsyncGenerator[None, None]:
"""Close MCP transports and initialized sandboxes after runtime shutdown."""
signal_handlers = ExitStack()
try:
ownership = getattr(getattr(startup_config, "sandbox", None), "ownership", None)
if ownership is not None and ownership.redis_mode == "cluster":
# Discover Redis slots before async request handlers can cold-start the provider.
provider = await await_drained(asyncio.to_thread(get_sandbox_provider))
signal_handlers.enter_context(provider.gateway_signal_handlers())
async with langgraph_runtime(app, startup_config):
yield
finally:
@ -624,6 +630,8 @@ async def _runtime_with_mcp_pool_shutdown(app: FastAPI, startup_config: AppConfi
await await_drained(asyncio.to_thread(shutdown_sandbox_provider))
except Exception:
logger.exception("Failed to shut down sandbox provider")
finally:
signal_handlers.close()
@asynccontextmanager

View File

@ -316,7 +316,7 @@ class AioSandboxProvider(WarmPoolLifecycleMixin[SandboxInfo], SandboxProvider):
# Register shutdown handler
atexit.register(self.shutdown)
self._register_signal_handlers()
self._register_or_defer_signal_handlers()
# Reconcile orphaned containers from previous process lifecycles
self._reconcile_orphans()

View File

@ -65,7 +65,10 @@ def resolve_ownership_redis_url(
config: SandboxOwnershipConfig,
) -> str:
"""Resolve the Redis endpoint shared by ownership-adjacent stores."""
return config.redis_url or os.getenv(_ENV_OWNERSHIP_REDIS_URL) or os.getenv(_ENV_STREAM_BRIDGE_REDIS_URL) or os.getenv("REDIS_URL") or "redis://localhost:6379/0"
url = config.redis_url or os.getenv(_ENV_OWNERSHIP_REDIS_URL) or os.getenv(_ENV_STREAM_BRIDGE_REDIS_URL) or os.getenv("REDIS_URL")
if config.redis_mode == "cluster" and not url:
raise ValueError("sandbox.ownership cluster mode requires a seed redis_url or Redis URL environment variable")
return url or "redis://localhost:6379/0"
def compute_lease_ttl(config: SandboxOwnershipConfig) -> float:
@ -104,6 +107,7 @@ def make_sandbox_ownership_store(config: SandboxOwnershipConfig | None, *, owner
return RedisOwnershipStore(
owner_id=effective_owner_id,
redis_url=redis_url,
cluster_nodes=resolved.cluster_nodes,
ttl_seconds=ttl,
key_prefix=resolved.key_prefix,
)

View File

@ -23,11 +23,14 @@ from __future__ import annotations
import logging
import math
from deerflow.config.sandbox_config import parse_cluster_node, validate_cluster_redis_url
from .base import OwnershipBackendError, RenewOutcome, SandboxOwnershipStore
try:
from redis import Redis
from redis.exceptions import RedisError
from redis.cluster import ClusterNode, RedisCluster
from redis.exceptions import RedisClusterException, RedisError
except ImportError: # pragma: no cover - only hit when the optional extra is missing
# ``redis`` is an optional extra (mirrors the stream_bridge redis path). This
# module is imported lazily from ``make_sandbox_ownership_store`` only when
@ -54,6 +57,18 @@ _DEL = "del:"
# open indefinitely. Without a socket timeout redis-py blocks forever.
_STORE_SOCKET_TIMEOUT_SECONDS = 5.0
def make_ownership_redis_client(redis_url: str, cluster_nodes: list[str] | None) -> Redis | RedisCluster:
"""Both the lease store and the E2B capacity ledger must use the configured topology."""
options = dict(decode_responses=True, socket_timeout=_STORE_SOCKET_TIMEOUT_SECONDS, socket_connect_timeout=_STORE_SOCKET_TIMEOUT_SECONDS)
if cluster_nodes is None:
return Redis.from_url(redis_url, **options)
validate_cluster_redis_url(redis_url) # The effective URL can come from the environment.
seeds = [ClusterNode(*parse_cluster_node(node)) for node in cluster_nodes]
# redis-py defaults to primary-only reads. Topology discovery happens here.
return RedisCluster.from_url(redis_url, startup_nodes=seeds, **options)
# Acquire-path takeover. Overwrites a live peer's normal lease on purpose — a
# thread's turn has routed here — but refuses a teardown in progress, which is
# what stops us handing out a container a peer is about to stop.
@ -130,27 +145,15 @@ class RedisOwnershipStore(SandboxOwnershipStore):
redis_url: str,
ttl_seconds: float,
key_prefix: str = "deerflow:sandbox:owner",
client: Redis | None = None,
client: Redis | RedisCluster | None = None,
cluster_nodes: list[str] | None = None,
) -> None:
self._owner_id = owner_id
# Redis accepts integer milliseconds; round up so conversion never
# shortens the configured lease.
self._ttl_ms = max(1, math.ceil(float(ttl_seconds) * 1000))
self._key_prefix = key_prefix.rstrip(":")
# Redis.from_url is lazy, so an unreachable Redis does not block provider
# construction; the first claim raises instead. socket_timeout bounds
# every round-trip (see _STORE_SOCKET_TIMEOUT_SECONDS) so no store call —
# in particular a teardown-heartbeat refresh — can block unbounded.
self._redis = (
client
if client is not None
else Redis.from_url(
redis_url,
decode_responses=True,
socket_timeout=_STORE_SOCKET_TIMEOUT_SECONDS,
socket_connect_timeout=_STORE_SOCKET_TIMEOUT_SECONDS,
)
)
self._redis = client if client is not None else make_ownership_redis_client(redis_url, cluster_nodes)
self._owns_client = client is None
self._take = self._redis.register_script(_TAKE_SCRIPT)
self._claim = self._redis.register_script(_CLAIM_SCRIPT)
@ -167,21 +170,21 @@ class RedisOwnershipStore(SandboxOwnershipStore):
def take(self, sandbox_id: str) -> bool:
try:
result = self._take(keys=[self._key(sandbox_id)], args=[self._owner_id, self._ttl_ms])
except RedisError as e:
except (RedisError, RedisClusterException) as e:
raise OwnershipBackendError(f"failed to publish sandbox ownership for {sandbox_id}: {e}") from e
return bool(result)
def claim(self, sandbox_id: str, *, for_destroy: bool = False) -> bool:
try:
result = self._claim(keys=[self._key(sandbox_id)], args=[self._owner_id, self._ttl_ms, "1" if for_destroy else "0"])
except RedisError as e:
except (RedisError, RedisClusterException) as e:
raise OwnershipBackendError(f"failed to claim sandbox ownership for {sandbox_id}: {e}") from e
return bool(result)
def renew(self, sandbox_id: str) -> RenewOutcome:
try:
result = int(self._renew(keys=[self._key(sandbox_id)], args=[self._owner_id, self._ttl_ms]))
except RedisError as e:
except (RedisError, RedisClusterException) as e:
raise OwnershipBackendError(f"failed to renew sandbox ownership for {sandbox_id}: {e}") from e
if result == 1:
return RenewOutcome.RENEWED
@ -192,13 +195,13 @@ class RedisOwnershipStore(SandboxOwnershipStore):
def release(self, sandbox_id: str) -> None:
try:
self._release(keys=[self._key(sandbox_id)], args=[self._owner_id])
except RedisError as e:
except (RedisError, RedisClusterException) as e:
raise OwnershipBackendError(f"failed to release sandbox ownership for {sandbox_id}: {e}") from e
def owner(self, sandbox_id: str) -> str | None:
try:
value = self._redis.get(self._key(sandbox_id))
except RedisError as e:
except (RedisError, RedisClusterException) as e:
raise OwnershipBackendError(f"failed to read sandbox ownership for {sandbox_id}: {e}") from e
if value is None:
return None

View File

@ -10,8 +10,6 @@ from deerflow.config.sandbox_config import SandboxOwnershipConfig
logger = logging.getLogger(__name__)
_SOCKET_TIMEOUT_SECONDS = 5.0
_LEDGER_SCRIPT = """
local function now_ms()
local current = redis.call('TIME')
@ -184,24 +182,21 @@ class RedisE2BCapacityStore:
redis_url: str,
hard_limit: int,
key_prefix: str = "deerflow:sandbox:owner",
cluster_nodes: list[str] | None = None,
) -> None:
if hard_limit < 1:
raise ValueError("hard_limit must be at least 1")
try:
from redis import Redis
from redis.exceptions import RedisError
from redis.exceptions import RedisClusterException, RedisError
from deerflow.community.aio_sandbox.ownership.redis import make_ownership_redis_client
except ImportError: # pragma: no cover - optional extra
raise ImportError("Redis E2B capacity requires: cd backend && uv sync --extra redis") from None
self._hard_limit = hard_limit
self._key = f"{key_prefix.rstrip(':')}:e2b-capacity"
self._redis_error = RedisError
self._redis = Redis.from_url(
redis_url,
decode_responses=True,
socket_timeout=_SOCKET_TIMEOUT_SECONDS,
socket_connect_timeout=_SOCKET_TIMEOUT_SECONDS,
)
self._redis_error = (RedisError, RedisClusterException)
self._redis = make_ownership_redis_client(redis_url, cluster_nodes)
self._script = self._redis.register_script(_LEDGER_SCRIPT)
@property
@ -281,6 +276,7 @@ def make_e2b_capacity_store(
logger.info("E2B deployment capacity: redis (key_prefix=%s, hard_limit=%d)", ownership.key_prefix, hard_limit)
return RedisE2BCapacityStore(
redis_url=resolve_ownership_redis_url(ownership),
cluster_nodes=ownership.cluster_nodes,
hard_limit=hard_limit,
key_prefix=ownership.key_prefix,
)

View File

@ -376,15 +376,20 @@ class E2BSandboxProvider(SandboxProvider):
self._ownership_config,
owner_id=self._owner_id,
)
self._deployment_capacity = make_e2b_capacity_store(
self._ownership_config,
hard_limit=self._capacity_limit(),
)
try:
self._deployment_capacity = make_e2b_capacity_store(
self._ownership_config,
hard_limit=self._capacity_limit(),
)
except Exception:
# Cluster discovery can fail after the lease client has already connected.
self._ownership.close()
raise
if not self._ownership.supports_cross_process:
logger.warning("E2B sandbox ownership is process-local. Multi-worker gateways must configure sandbox.ownership.type: redis for safe reconciliation.")
atexit.register(self._shutdown_at_exit)
self._register_signal_handlers()
self._register_or_defer_signal_handlers()
self._start_maintenance_threads()
def _load_config(self) -> dict[str, Any]:

View File

@ -1,6 +1,8 @@
import ipaddress
import math
import re
from typing import Literal
from urllib.parse import parse_qs, urlsplit
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validator
@ -99,6 +101,28 @@ class SandboxNetworkConfig(BaseModel):
return normalized
def parse_cluster_node(address: str) -> tuple[str, int]:
match = re.fullmatch(r"(\[[0-9a-fA-F:.]+\]|[a-zA-Z0-9._-]+):([0-9]{1,5})", address)
if not match or not 1 <= int(match[2]) <= 65535:
raise ValueError("redis_cluster_nodes entries must be host:port or [IPv6]:port")
host = match[1]
if host.startswith("["):
host = str(ipaddress.IPv6Address(host[1:-1]))
return host, int(match[2])
def validate_cluster_redis_url(url: str) -> None:
seed = urlsplit(url)
if seed.scheme not in {"redis", "rediss"} or not seed.hostname or seed.port == 0 or seed.fragment:
raise ValueError("cluster redis_url requires a redis:// or rediss:// seed host")
options = parse_qs(seed.query, keep_blank_values=True)
if seed.path not in {"", "/", "/0"} or any(db != "0" for db in options.get("db", [])):
raise ValueError("Redis Cluster supports database 0 only")
# redis-py gives URL query parameters precedence over client kwargs.
if options.keys() & {"decode_responses", "socket_timeout", "socket_connect_timeout", "read_from_replicas", "load_balancing_strategy"}:
raise ValueError("cluster redis_url cannot override ownership read routing, decoding or socket timeouts")
class SandboxOwnershipConfig(BaseModel):
"""Configuration for cross-instance sandbox container ownership (#4206).
@ -117,8 +141,11 @@ class SandboxOwnershipConfig(BaseModel):
)
redis_url: str | None = Field(
default=None,
description="Redis URL for the redis ownership type. If omitted, DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL, DEER_FLOW_STREAM_BRIDGE_REDIS_URL, REDIS_URL, or redis://localhost:6379/0 is used.",
description="Redis endpoint or cluster seed URL. Falls back to DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL, DEER_FLOW_STREAM_BRIDGE_REDIS_URL, then REDIS_URL. Standalone also defaults to redis://localhost:6379/0.",
)
redis_mode: Literal["standalone", "cluster"] = Field(default="standalone", description="startup-only: Redis topology for sandbox ownership and E2B capacity.")
redis_cluster_nodes: list[str] = Field(default_factory=list, description="startup-only: Additional Redis Cluster discovery seeds (host:port or [IPv6]:port).")
renewal_interval_seconds: float = Field(
default=30.0,
gt=0,
@ -145,6 +172,24 @@ class SandboxOwnershipConfig(BaseModel):
description="Redis key prefix for ownership leases. Only applies to the redis ownership type.",
)
@model_validator(mode="after")
def validate_redis_topology(self) -> "SandboxOwnershipConfig":
if self.redis_mode == "cluster":
if self.type != "redis":
raise ValueError("redis_mode: cluster requires sandbox.ownership.type: redis")
if self.redis_url is not None:
validate_cluster_redis_url(self.redis_url)
for node in self.redis_cluster_nodes:
parse_cluster_node(node)
elif self.redis_cluster_nodes:
raise ValueError("redis_cluster_nodes requires redis_mode: cluster")
return self
@property
def cluster_nodes(self) -> list[str] | None:
"""An empty list enables cluster discovery from the seed URL alone."""
return self.redis_cluster_nodes if self.redis_mode == "cluster" else None
@model_validator(mode="after")
def validate_lease_ttl(self) -> "SandboxOwnershipConfig":
lease_ttl_seconds = self.renewal_interval_seconds * self.ttl_multiplier

View File

@ -1,4 +1,5 @@
import asyncio
import signal
import threading
from abc import ABC, abstractmethod
from collections.abc import Iterator
@ -27,6 +28,38 @@ class SandboxProvider(ABC):
# without a separate sync_agent_skills upload before tools can access it.
supports_lazy_agent_skill_isolation: bool = False
_signal_handlers_deferred = False
def _register_signal_handlers(self) -> None:
"""Install process signal handlers for providers that own sandbox resources."""
def _register_or_defer_signal_handlers(self) -> None:
if threading.current_thread() is threading.main_thread():
self._register_signal_handlers()
else:
self._signal_handlers_deferred = True
@contextmanager
def gateway_signal_handlers(self) -> Iterator[None]:
"""Install a worker-built provider's SIGHUP fallback for the Gateway lifespan."""
if not self._signal_handlers_deferred or not hasattr(signal, "SIGHUP") or threading.current_thread() is not threading.main_thread():
yield
return
previous = signal.getsignal(signal.SIGHUP)
if previous is None: # A native handler cannot be restored with signal.signal().
yield
return
self._register_signal_handlers()
installed = signal.getsignal(signal.SIGHUP)
self._signal_handlers_deferred = False
try:
yield
finally:
if signal.getsignal(signal.SIGHUP) is installed:
signal.signal(signal.SIGHUP, previous)
self._signal_handlers_deferred = True
@abstractmethod
def acquire(self, thread_id: str | None = None, *, user_id: str | None = None) -> str:
"""Acquire a sandbox environment and return its ID.

View File

@ -191,7 +191,14 @@ def test_overlay_points_explicit_sandbox_ownership_at_the_harness_redis():
base = {
"sandbox": {
"use": "deerflow.sandbox.local:LocalSandboxProvider",
"ownership": {"type": "redis", "redis_url": "redis://prod-redis:6379/3", "renewal_interval_seconds": 7.5, "ttl_multiplier": 3},
"ownership": {
"type": "redis",
"redis_url": "rediss://ops:example-password@prod-redis:6379/0",
"redis_mode": "cluster",
"redis_cluster_nodes": ["prod-backup:6379"],
"renewal_interval_seconds": 7.5,
"ttl_multiplier": 3,
},
}
}
@ -199,6 +206,7 @@ def test_overlay_points_explicit_sandbox_ownership_at_the_harness_redis():
assert config["sandbox"]["ownership"] == {"type": "redis", "redis_url": REDIS_URL, "renewal_interval_seconds": 7.5, "ttl_multiplier": 3}
assert any("sandbox.ownership" in note for note in notes)
assert all("example-password" not in note for note in notes)
def test_overlay_gives_local_aio_sandboxes_a_harness_container_prefix():

View File

@ -11,7 +11,6 @@ import pytest
from deerflow.community.e2b_sandbox.capacity import (
CapacityBackendError,
RedisE2BCapacityStore,
ReserveStatus,
make_e2b_capacity_store,
)
@ -21,25 +20,28 @@ REDIS_URL = os.environ.get("DEER_FLOW_TEST_REDIS_URL", "redis://localhost:6379/1
pytestmark = pytest.mark.integration
@pytest.fixture
def make_store():
@pytest.fixture(params=["standalone", pytest.param("cluster", marks=pytest.mark.skipif(not os.getenv("TEST_REDIS_CLUSTER_URL"), reason="TEST_REDIS_CLUSTER_URL is unset"))])
def make_store(request):
redis = pytest.importorskip("redis")
probe = redis.Redis.from_url(REDIS_URL, decode_responses=True, socket_connect_timeout=0.5)
try:
probe.ping()
except Exception:
probe.close()
pytest.skip(f"Redis not reachable at {REDIS_URL}")
mode = request.param
if mode == "cluster":
url = os.environ["TEST_REDIS_CLUSTER_URL"]
probe = redis.RedisCluster.from_url(url, decode_responses=True)
else:
url = REDIS_URL
probe = redis.Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.5)
try:
probe.ping()
except Exception:
probe.close()
pytest.skip(f"Redis not reachable at {url}")
prefix = f"deerflow:test:{uuid.uuid4().hex}"
config = SandboxOwnershipConfig(type="redis", redis_url=url, redis_mode=mode, key_prefix=prefix)
stores = []
def make(hard_limit: int = 1):
store = RedisE2BCapacityStore(
redis_url=REDIS_URL,
hard_limit=hard_limit,
key_prefix=prefix,
)
store = make_e2b_capacity_store(config, hard_limit=hard_limit)
stores.append(store)
return store
@ -83,6 +85,23 @@ def test_factory_is_lazy_and_backend_errors_fail_closed() -> None:
store.close()
def test_cluster_capacity_discovers_topology_at_startup_and_propagates_failure(monkeypatch):
from redis.cluster import NodesManager
from redis.exceptions import RedisClusterException
seeds = set()
def offline(manager):
seeds.update((node.host, node.port) for node in manager.startup_nodes.values())
raise RedisClusterException("no reachable seed")
monkeypatch.setattr(NodesManager, "initialize", offline)
config = SandboxOwnershipConfig(type="redis", redis_mode="cluster", redis_url="redis://seed:6379/0", redis_cluster_nodes=["second:6379"])
with pytest.raises(RedisClusterException, match="no reachable seed"):
make_e2b_capacity_store(config, hard_limit=1)
assert seeds == {("seed", 6379), ("second", 6379)}
def test_two_gateways_atomically_share_one_hash(make_store) -> None:
gateway_a, gateway_b = make_store(), make_store()
assert gateway_a.reserve("not-ready") is ReserveStatus.NOT_READY

View File

@ -4566,6 +4566,20 @@ def test_grep_single_file_path_with_matching_glob():
# Capacity enforcement tests (#4339)
def test_capacity_startup_failure_closes_the_ownership_store(monkeypatch):
from deerflow.community.e2b_sandbox import e2b_sandbox_provider as provider
monkeypatch.setattr(provider.E2BSandboxProvider, "_load_config", lambda self: {"replicas": 1, "overflow_policy": "wait"})
ownership = MagicMock()
monkeypatch.setattr(provider, "make_sandbox_ownership_store", lambda *args, **kwargs: ownership)
capacity = MagicMock(side_effect=CapacityBackendError("discovery failed"))
monkeypatch.setattr(provider, "make_e2b_capacity_store", capacity)
with pytest.raises(CapacityBackendError, match="discovery failed"):
provider.E2BSandboxProvider()
capacity.assert_called_once()
ownership.close.assert_called_once()
def test_deployment_capacity_reserves_commits_and_rejects_globally(monkeypatch) -> None:
gateway_a = _make_provider(replicas=1, overflow_policy="reject")
gateway_b = _make_provider(replicas=1, overflow_policy="reject")

View File

@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
import logging
import signal
import threading
from contextlib import ExitStack, asynccontextmanager
from types import SimpleNamespace
@ -654,6 +655,103 @@ def _gateway_lifespan_patches(startup_config, *, pool=None, browser_manager=None
return patches
@pytest.mark.asyncio
@pytest.mark.parametrize("redis_mode", ["cluster", "standalone"])
async def test_lifespan_warms_cluster_sandbox_provider_off_loop(monkeypatch, redis_mode):
from app.gateway.app import lifespan
from deerflow.config.sandbox_config import SandboxOwnershipConfig
from deerflow.sandbox import sandbox_provider
config = MagicMock()
config.log_level = "INFO"
config.memory.enabled = False
config.sandbox.ownership = SandboxOwnershipConfig(type="redis", redis_mode=redis_mode)
loop_thread = threading.get_ident()
construction_threads = []
provider = MagicMock()
def build_provider():
construction_threads.append(threading.get_ident())
return provider
monkeypatch.setattr(sandbox_provider, "_default_sandbox_provider", None)
monkeypatch.setattr(sandbox_provider, "get_app_config", lambda: config)
monkeypatch.setattr(sandbox_provider, "resolve_class", lambda *_: build_provider)
pool = MagicMock(close_all=AsyncMock())
with ExitStack() as stack:
for patcher in _gateway_lifespan_patches(config, pool=pool):
stack.enter_context(patcher)
async with lifespan(FastAPI()):
if redis_mode == "cluster":
assert sandbox_provider.get_initialized_sandbox_provider() is provider
assert sandbox_provider.get_sandbox_provider() is provider
assert len(construction_threads) == 1
assert construction_threads[0] != loop_thread
else:
assert sandbox_provider.get_initialized_sandbox_provider() is None
assert provider.shutdown.call_count == (1 if redis_mode == "cluster" else 0)
@pytest.mark.asyncio
@pytest.mark.skipif(not hasattr(signal, "SIGHUP"), reason="SIGHUP is POSIX-only")
@pytest.mark.parametrize("backend", ["aio", "e2b"])
async def test_cluster_warmup_preserves_sighup_cleanup(monkeypatch, backend):
from redis import RedisCluster
from redis.cluster import NodesManager
from app.gateway.app import lifespan
from deerflow.community.aio_sandbox import AioSandboxProvider
from deerflow.community.e2b_sandbox import E2BSandboxProvider
from deerflow.config.sandbox_config import SandboxOwnershipConfig
from deerflow.sandbox import sandbox_provider
config = MagicMock()
config.log_level = "INFO"
config.memory.enabled = False
config.sandbox.ownership = SandboxOwnershipConfig(type="redis", redis_mode="cluster", redis_url="redis://seed:7000/0")
discovery_threads = []
def discover(manager):
discovery_threads.append(threading.current_thread())
manager.default_node = next(iter(manager.startup_nodes.values()))
monkeypatch.setattr(NodesManager, "initialize", discover)
monkeypatch.setattr(RedisCluster, "command", lambda self: {})
cls = AioSandboxProvider if backend == "aio" else E2BSandboxProvider
monkeypatch.setattr(cls, "_load_config", lambda self: dict(ownership=config.sandbox.ownership, idle_timeout=0, replicas=1, overflow_policy="reject", reconciliation_max_seconds=1))
if backend == "aio":
monkeypatch.setattr(cls, "_create_backend", lambda self: MagicMock())
monkeypatch.setattr(cls, "_reconcile_orphans", lambda self: None)
else:
monkeypatch.setattr(cls, "_start_maintenance_threads", lambda self: None)
monkeypatch.setattr(sandbox_provider, "_default_sandbox_provider", None)
monkeypatch.setattr(sandbox_provider, "get_app_config", lambda: config)
monkeypatch.setattr(sandbox_provider, "resolve_class", lambda *_: cls)
forwarded = []
def previous(signum, frame):
forwarded.append(signum)
with ExitStack() as stack:
stack.callback(signal.signal, signal.SIGHUP, signal.signal(signal.SIGHUP, previous))
stop_handlers = [signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGINT)]
for patcher in _gateway_lifespan_patches(config, pool=MagicMock(close_all=AsyncMock())):
stack.enter_context(patcher)
async with lifespan(FastAPI()):
provider = sandbox_provider.get_sandbox_provider()
assert discovery_threads and threading.main_thread() not in discovery_threads
assert [signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGINT)] == stop_handlers
handler = signal.getsignal(signal.SIGHUP)
assert callable(handler) and handler is not previous
with patch.object(provider, "shutdown", wraps=provider.shutdown) as shutdown:
signal.raise_signal(signal.SIGHUP)
shutdown.assert_called_once_with()
assert forwarded == [signal.SIGHUP]
assert signal.getsignal(signal.SIGHUP) is previous
def test_lifespan_closes_pooled_mcp_sessions_on_shutdown():
"""Pooled MCP sessions must be closed while the worker is still shutting down.

View File

@ -19,6 +19,7 @@ import os
import threading
import time
import uuid
from contextlib import ExitStack
from unittest.mock import MagicMock
import pytest
@ -340,6 +341,113 @@ def test_unknown_type_raises():
make_sandbox_ownership_store(config, owner_id="A")
def test_cluster_factory_uses_all_seeds_credentials_and_bounded_primary_reads(monkeypatch):
from redis import RedisCluster
from redis.cluster import NodesManager
from redis.connection import SSLConnection
from redis.exceptions import SlotNotCoveredError
# Keep redis-py's real URL parsing, TLS setup and node construction.
# Replace only the two startup network reads (slot map and command table).
def partial_topology(manager):
manager.default_node = next(iter(manager.startup_nodes.values()))
monkeypatch.setattr(NodesManager, "initialize", partial_topology)
monkeypatch.setattr(RedisCluster, "command", lambda self: {})
monkeypatch.setenv("DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL", "rediss://operator:p%40ss@seed-a:7000/0")
config = SandboxOwnershipConfig(type="redis", redis_mode="cluster", redis_cluster_nodes=["seed-b:7001", "[::1]:7002"])
store = make_sandbox_ownership_store(config)
try:
client = store._redis
assert isinstance(client, RedisCluster)
assert {(n.host, n.port) for n in client.startup_nodes} == {("seed-a", 7000), ("seed-b", 7001), ("::1", 7002)}
options = client.nodes_manager.connection_kwargs
assert options["connection_class"] is SSLConnection
assert (options["username"], options["password"]) == ("operator", "p@ss")
assert options["decode_responses"] is True
assert options["socket_timeout"] == options["socket_connect_timeout"] == 5
assert not client.read_from_replicas
assert not getattr(client, "load_balancing_strategy", None)
# Discovery supplied no slots. This SDK exception is outside RedisError.
with pytest.raises(OwnershipBackendError) as error:
store.claim("unmapped")
assert isinstance(error.value.__cause__, SlotNotCoveredError)
close = MagicMock()
monkeypatch.setattr(client, "close", close)
finally:
store.close()
close.assert_called_once()
@pytest.mark.parametrize("node", ["", "seed", "seed:0", "seed:65536", "seed:not-a-port", "redis://seed:7000", "user@seed:7000", "::1:7000"])
def test_cluster_seed_must_be_a_host_and_port(node):
with pytest.raises(ValueError, match="host:port"):
SandboxOwnershipConfig(type="redis", redis_mode="cluster", redis_cluster_nodes=[node])
@pytest.mark.parametrize(
"settings",
[
{"type": "memory", "redis_mode": "cluster"},
{"type": "redis", "redis_cluster_nodes": ["seed:7000"]},
{"type": "redis", "redis_mode": "cluster", "redis_url": "redis://seed/2"},
{"type": "redis", "redis_mode": "cluster", "redis_url": "redis://seed/0?db=2"},
{"type": "redis", "redis_mode": "cluster", "redis_url": "unix:///tmp/redis.sock"},
{"type": "redis", "redis_mode": "cluster", "redis_url": "redis://seed/0?socket_timeout=0"},
{"type": "redis", "redis_mode": "cluster", "redis_url": "redis://seed/0?read_from_replicas=true"},
],
)
def test_invalid_cluster_configuration_is_rejected(settings):
with pytest.raises(ValueError):
SandboxOwnershipConfig(**settings)
def test_cluster_requires_an_explicit_seed_url(monkeypatch):
for variable in ("DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL", "DEER_FLOW_STREAM_BRIDGE_REDIS_URL", "REDIS_URL"):
monkeypatch.delenv(variable, raising=False)
config = SandboxOwnershipConfig(type="redis", redis_mode="cluster")
with pytest.raises(ValueError, match="seed redis_url"):
make_sandbox_ownership_store(config)
monkeypatch.setenv("REDIS_URL", "redis://seed/5")
with pytest.raises(ValueError, match="database 0"):
make_sandbox_ownership_store(config)
@pytest.mark.integration
@pytest.mark.skipif(not os.getenv("TEST_REDIS_CLUSTER_URL"), reason="TEST_REDIS_CLUSTER_URL is unset")
def test_ownership_across_two_cluster_primaries():
from redis import RedisCluster
seed = os.environ["TEST_REDIS_CLUSTER_URL"]
prefix = f"deerflow:test:{uuid.uuid4().hex}"
config = SandboxOwnershipConfig(type="redis", redis_mode="cluster", redis_url=seed, key_prefix=prefix)
with ExitStack() as stack:
topology = stack.enter_context(RedisCluster.from_url(seed))
by_primary = {}
for index in range(256):
sandbox_id = str(index)
primary = topology.get_node_from_key(f"{prefix}:{sandbox_id}")
by_primary.setdefault(primary.name, sandbox_id)
if len(by_primary) == 2:
break
assert len(by_primary) == 2, "test requires keys on two distinct Redis primaries"
a = make_sandbox_ownership_store(config, owner_id="A")
stack.callback(a.close)
b = make_sandbox_ownership_store(config, owner_id="B")
stack.callback(b.close)
for sandbox_id in by_primary.values():
assert a.claim(sandbox_id)
assert a.renew(sandbox_id) is RenewOutcome.RENEWED
assert b.take(sandbox_id)
assert a.renew(sandbox_id) is RenewOutcome.LOST
a.release(sandbox_id)
assert a.owner(sandbox_id) == "B"
assert b.claim(sandbox_id, for_destroy=True)
assert not a.take(sandbox_id)
b.release(sandbox_id)
assert a.renew(sandbox_id) is RenewOutcome.LAPSED
def test_ttl_derives_from_renewal_interval_not_idle_timeout():
"""The coupling that let leases lapse under idle_timeout: 0 must stay broken."""
config = SandboxOwnershipConfig(renewal_interval_seconds=30, ttl_multiplier=4)

View File

@ -1941,6 +1941,9 @@ sandbox:
# # ownership:
# # type: redis # required for multi-instance / load-balanced
# # redis_url: redis://redis:6379/0
# # redis_mode: standalone # use cluster for Redis Cluster (database 0)
# # # redis_cluster_nodes: # optional extra discovery seeds in cluster mode
# # # - redis-1:6379
# # renewal_interval_seconds: 30 # how often an owner refreshes its leases
# # ttl_multiplier: 4 # lease TTL = interval x this (min 2, so a
# # # single missed renewal cannot expire a live
@ -1950,8 +1953,9 @@ sandbox:
# # key_prefix: deerflow:sandbox:owner
# #
# # NOTE: the redis ownership store is fail-closed, matching the stream bridge's
# # fail-hard policy. Redis.from_url is lazy so a down Redis does not block
# # startup, but a sandbox whose ownership cannot be published is not handed out
# # fail-hard policy. Standalone Redis connects on first use. Cluster mode
# # discovers the topology at provider startup and requires a reachable seed.
# # A sandbox whose ownership cannot be published is not handed out
# # — acquiring raises instead. The alternative (proceed unowned) is exactly the
# # #4206 cross-instance kill. Run Redis with HA / a restart policy.
# #

View File

@ -125,6 +125,39 @@ saved API error responses and avoids blocking later reads when the optional
`tool_progress` guard is enabled. Actual read failures and output truncation
still retain their error or partial-result status.
## Redis Cluster for shared sandbox ownership
Gateways sharing AIO containers or E2B VMs can store ownership leases in Redis
Cluster. E2B uses the same connection settings for its deployment-wide capacity
ledger. Configure the same cluster and key prefix on every Gateway.
```yaml
sandbox:
ownership:
type: redis
redis_mode: cluster
redis_url: $DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL
redis_cluster_nodes:
- redis-1:6379
- redis-2:6379
```
Set the seed URL to `redis://host:port/0` or `rediss://user:password@host:port/0`
for TLS and ACL authentication. Percent-encode credentials in the URL. The
extra discovery nodes are optional and share the URL's credentials and TLS
settings. Use `[IPv6]:port` for an IPv6 node. When `redis_url` is omitted,
the first populated variable among `DEER_FLOW_SANDBOX_OWNERSHIP_REDIS_URL`,
`DEER_FLOW_STREAM_BRIDGE_REDIS_URL`, and `REDIS_URL` supplies it. Cluster mode
requires an explicit seed URL from one of these sources and uses database 0.
In cluster mode, the Gateway initializes the sandbox provider on a worker
thread before accepting requests. Startup fails if slot discovery fails. The Gateway needs connectivity
to the addresses the cluster advertises. Lease reads use primaries and each
lease transition runs atomically on the primary holding that sandbox's key.
Restart the Gateway after changing the topology. Standalone Redis remains the
default for `type: redis` and connects lazily. Other Redis-backed components,
including the stream bridge, have their own client configuration.
## Sandbox & File System
AIO runs commands from independent subagents concurrently, including Lark CLI

View File

@ -149,7 +149,9 @@ def build_multi_instance_config(
# An explicit section stops ownership from inheriting the bridge's
# Redis, so its endpoint must be rewritten; timing settings stay.
ownership = dict(ownership) if isinstance(ownership, Mapping) else {}
previous = f"type {ownership.get('type', 'memory')!r}" + (f", {ownership['redis_url']}" if ownership.get("redis_url") else "")
previous = f"type {ownership.get('type', 'memory')!r}"
ownership.pop("redis_mode", None)
ownership.pop("redis_cluster_nodes", None)
ownership.update(type="redis", redis_url=redis_url)
sandbox["ownership"] = ownership
notes.append(f"pointed sandbox.ownership at the harness Redis (was {previous})")