mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(sandbox): opt-in OpenSandbox hard cap (overflow_policy: reject) (#8639)
* feat(sandbox): add opt-in OpenSandbox capacity rejection * fix(sandbox): count reclaimed OpenSandbox slots and warn on burst - Keep a reclaimed warm sandbox reserved until it is registered as active, so a concurrent create cannot exceed the reject cap while the reclaimed sandbox's skill view is prepared. - Release a create reservation under the same lock as the registration, so a registered sandbox is never counted twice. - Give the capacity error the 30 second retry hint E2B uses. - Log a warning when overflow_policy is burst: OpenSandbox keeps the soft cap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com> * fix(sandbox): keep OpenSandbox slots counted until deletion is confirmed Review of #8639 (WillemJiang), reproduced with the offline SDK fixture: - The idle reaper and a failed health check now mark the remotes they remove as retiring under the same lock, and the reject cap counts them until their deletion succeeds (new mixin hook, a no-op for the other providers). - A failed eviction keeps the slot occupied and returns a retryable capacity error instead of creating a replacement. An unconfirmed remote stays counted until its server-side lifetime ends, or until the Gateway restarts when sandbox_timeout is 0. - A failed reclaim hands its reservation back to the warm pool under the same lock that restores the warm entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com> --------- Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com> Co-authored-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5c93f6d0be
commit
80cbad0584
@ -1779,6 +1779,7 @@ sandbox:
|
||||
sandbox_timeout: 14400 # remote lifetime; 0 = explicit cleanup
|
||||
bash_command_timeout: 600 # default remote command timeout seconds
|
||||
replicas: 3 # active + warm cap per gateway process
|
||||
overflow_policy: wait # optional: reject adds a process-local hard cap
|
||||
idle_timeout: 600 # warm seconds before destroy; 0 disables
|
||||
environment:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
@ -1820,7 +1821,12 @@ horizon. File transfer uses OpenSandbox's native filesystem API; bounded
|
||||
`find`/`grep` commands implement the directory and content-search surface.
|
||||
Downloads are restricted to `/mnt/user-data` and all file paths reject
|
||||
traversal. Multi-process discovery and ownership coordination are not yet
|
||||
implemented, so `replicas` is a per-Gateway-process soft cap.
|
||||
implemented, so `replicas` is a per-Gateway-process soft cap by default. With
|
||||
`overflow_policy: reject`, it becomes a process-local hard cap that also counts
|
||||
in-flight creates. If all slots are occupied and no warm sandbox can be evicted,
|
||||
acquisition raises `SandboxCapacityExceededError` before calling the SDK. This
|
||||
can protect a namespace ResourceQuota only when one Gateway process owns the
|
||||
provider and `replicas` does not exceed the quota's pod capacity.
|
||||
|
||||
**boxd Machine Sandbox** (runs each sandbox as an isolated [boxd](https://boxd.sh?ref=deer-flow) machine):
|
||||
|
||||
|
||||
@ -16,8 +16,8 @@ import threading
|
||||
import time
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import ExitStack
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from datetime import timedelta
|
||||
from functools import partial
|
||||
from pathlib import Path, PurePosixPath
|
||||
@ -26,6 +26,7 @@ from urllib.parse import urlsplit
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.sandbox.acquire_serialization import AcquireSerializer, AcquireSerializerClosed
|
||||
from deerflow.sandbox.exceptions import SandboxCapacityExceededError
|
||||
from deerflow.sandbox.identity import derive_sandbox_scope_token
|
||||
from deerflow.sandbox.sandbox import Sandbox, _validate_extra_env
|
||||
from deerflow.sandbox.sandbox_provider import SandboxProvider
|
||||
@ -136,6 +137,9 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
# or initializing remote can already hold a different view.
|
||||
supports_lazy_agent_skill_isolation = True
|
||||
_idle_checker_thread_name = "opensandbox-idle-reaper"
|
||||
# Retry hint for overflow_policy: reject. A slot frees when any run releases
|
||||
# its sandbox, so this matches the E2B capacity hint rather than idle_timeout.
|
||||
CAPACITY_RETRY_AFTER_SECONDS = 30.0
|
||||
_MAX_SYNC_FILES = 2000
|
||||
_MAX_SYNC_TOTAL_BYTES = 512 * 1024 * 1024
|
||||
_MAX_SYNC_LISTING_BYTES = 512 * 1024
|
||||
@ -149,6 +153,10 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
self._sandboxes: dict[str, OpenSandboxSandbox] = {}
|
||||
self._thread_sandboxes: dict[tuple[str, str], str] = {}
|
||||
self._warm_pool: dict[str, tuple[OpenSandboxSandbox, float]] = {}
|
||||
self._reserved_creates: set[str] = set()
|
||||
# Remotes out of the pool whose deletion is not confirmed yet: id -> monotonic release time,
|
||||
# or None while the deletion runs or when the remote has no server-side lifetime.
|
||||
self._retiring: dict[str, float | None] = {}
|
||||
self._acquire_serializer: AcquireSerializer[str] = AcquireSerializer(thread_name_prefix="opensandbox-acquire-wait")
|
||||
self._idle_checker_stop = threading.Event()
|
||||
self._idle_checker_thread: threading.Thread | None = None
|
||||
@ -213,6 +221,9 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
logger.warning("OpenSandboxProvider: no api_key or domain configured (set sandbox.api_key/sandbox.domain in config.yaml or OPEN_SANDBOX_API_KEY/OPEN_SANDBOX_DOMAIN). The SDK will default to unauthenticated localhost:8080.")
|
||||
if _uses_insecure_remote_http(effective_domain, protocol):
|
||||
logger.warning("OpenSandboxProvider: remote OpenSandbox domain uses HTTP; use HTTPS to protect credentials and sandbox traffic.")
|
||||
overflow_policy = option("overflow_policy") or "wait"
|
||||
if overflow_policy == "burst":
|
||||
logger.warning("OpenSandboxProvider: overflow_policy 'burst' is E2B-only; OpenSandbox keeps the replicas soft cap. Use 'reject' for a hard cap.")
|
||||
# $VARS in config.yaml are already resolved by AppConfig.resolve_env_variables;
|
||||
# resolving again would rewrite a secret that itself starts with $.
|
||||
environment = dict(option("environment") or {})
|
||||
@ -239,6 +250,7 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
"command_timeout": self._positive_float("bash_command_timeout", option("bash_command_timeout"), DEFAULT_COMMAND_TIMEOUT),
|
||||
"environment": environment,
|
||||
"replicas": replicas if replicas is not None else self.DEFAULT_REPLICAS,
|
||||
"overflow_policy": overflow_policy,
|
||||
"idle_timeout": idle_timeout if idle_timeout is not None else self.DEFAULT_IDLE_TIMEOUT,
|
||||
"resource": resource_option("resource"),
|
||||
"resource_requests": resource_option("resource_requests"),
|
||||
@ -286,7 +298,35 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
return len(self._sandboxes)
|
||||
|
||||
def _destroy_warm_entry(self, sandbox_id: str, entry: OpenSandboxSandbox, *, reason: str) -> None:
|
||||
self._destroy_quietly(entry, context=f"warm pool, reason={reason}")
|
||||
self._retire(sandbox_id, entry, reason=reason)
|
||||
|
||||
def _warm_entries_retiring_locked(self, sandbox_ids: list[str]) -> None:
|
||||
for sandbox_id in sandbox_ids:
|
||||
self._retiring[sandbox_id] = None
|
||||
|
||||
def _retire(self, sandbox_id: str, sandbox: OpenSandboxSandbox, *, reason: str) -> bool:
|
||||
"""Destroy a remote that left the warm pool; it stays counted until deletion is confirmed."""
|
||||
try:
|
||||
sandbox.destroy()
|
||||
except Exception as exc:
|
||||
lifetime = self._config["sandbox_timeout"]
|
||||
with self._lock:
|
||||
if sandbox_id in self._retiring:
|
||||
self._retiring[sandbox_id] = None if lifetime is None else time.monotonic() + lifetime
|
||||
if lifetime is None:
|
||||
logger.warning("Error destroying OpenSandbox %s (warm pool, reason=%s): %s; its slot stays occupied until the Gateway restarts", sandbox.id, reason, exc)
|
||||
else:
|
||||
logger.warning("Error destroying OpenSandbox %s (warm pool, reason=%s): %s; its slot stays occupied until its server-side lifetime ends", sandbox.id, reason, exc)
|
||||
return False
|
||||
with self._lock:
|
||||
self._retiring.pop(sandbox_id, None)
|
||||
return True
|
||||
|
||||
def _retiring_count_locked(self) -> int:
|
||||
now = time.monotonic()
|
||||
for sandbox_id in [key for key, until in self._retiring.items() if until is not None and until <= now]:
|
||||
del self._retiring[sandbox_id]
|
||||
return len(self._retiring)
|
||||
|
||||
@staticmethod
|
||||
def _destroy_quietly(sandbox: OpenSandboxSandbox, *, context: str) -> None:
|
||||
@ -328,22 +368,25 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
raise RuntimeError("OpenSandboxProvider has been shut down")
|
||||
if thread_id is None:
|
||||
sandbox_id = str(uuid.uuid4())[:8]
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=None, user_id=user_id)
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=None, user_id=user_id)
|
||||
except BaseException:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
else:
|
||||
self._sandboxes[sandbox_id] = sandbox
|
||||
destroy_after_unlock = False
|
||||
if destroy_after_unlock:
|
||||
self._destroy_quietly(sandbox, context="created during shutdown")
|
||||
raise RuntimeError("OpenSandboxProvider shut down during acquire")
|
||||
return sandbox_id
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(self._create_capacity(sandbox_id))
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=None, user_id=user_id)
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=None, user_id=user_id)
|
||||
except BaseException:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
else:
|
||||
self._sandboxes[sandbox_id] = sandbox
|
||||
self._reserved_creates.discard(sandbox_id)
|
||||
destroy_after_unlock = False
|
||||
if destroy_after_unlock:
|
||||
self._destroy_quietly(sandbox, context="created during shutdown")
|
||||
raise RuntimeError("OpenSandboxProvider shut down during acquire")
|
||||
return sandbox_id
|
||||
|
||||
key = self._thread_key(thread_id, user_id)
|
||||
sandbox_id = self._sandbox_id(thread_id, user_id or "")
|
||||
@ -383,33 +426,83 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
logger.info("Rebuilding terminal OpenSandbox %s during acquire", existing)
|
||||
sandbox = self._reclaim_warm_pool(sandbox_id)
|
||||
reclaimed = sandbox is not None
|
||||
if sandbox is None:
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id)
|
||||
with ExitStack() as stack:
|
||||
if reclaimed:
|
||||
stack.callback(self._release_reservation, sandbox_id)
|
||||
else:
|
||||
stack.enter_context(self._create_capacity(sandbox_id))
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id)
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=thread_id, user_id=user_id)
|
||||
except BaseException as exc:
|
||||
if reclaimed and isinstance(exc, _SkillUploadError):
|
||||
self._park_failed_skill_upload(sandbox, was_active=False)
|
||||
else:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
else:
|
||||
self._sandboxes[sandbox_id] = sandbox
|
||||
self._thread_sandboxes[key] = sandbox_id
|
||||
self._reserved_creates.discard(sandbox_id)
|
||||
destroy_after_unlock = False
|
||||
if destroy_after_unlock:
|
||||
self._destroy_quietly(sandbox, context="created during shutdown")
|
||||
raise RuntimeError("OpenSandboxProvider shut down during acquire")
|
||||
return sandbox_id
|
||||
|
||||
@contextmanager
|
||||
def _create_capacity(self, sandbox_id: str) -> Iterator[None]:
|
||||
"""Reserve a hard-cap slot through active registration, or preserve the soft cap."""
|
||||
if self._config["overflow_policy"] != "reject":
|
||||
yield
|
||||
return
|
||||
|
||||
evicted: tuple[str, OpenSandboxSandbox] | None = None
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=thread_id, user_id=user_id)
|
||||
except BaseException as exc:
|
||||
if reclaimed and isinstance(exc, _SkillUploadError):
|
||||
self._park_failed_skill_upload(sandbox, was_active=False)
|
||||
else:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
replicas = int(self._config["replicas"])
|
||||
retiring = self._retiring_count_locked()
|
||||
total = len(self._sandboxes) + len(self._warm_pool) + len(self._reserved_creates) + retiring
|
||||
if total >= replicas:
|
||||
if not self._warm_pool:
|
||||
raise self._capacity_error_locked(replicas, retiring)
|
||||
warm_id, (warm, _) = min(self._warm_pool.items(), key=lambda item: item[1][1])
|
||||
self._warm_pool.pop(warm_id)
|
||||
self._retiring[warm_id] = None
|
||||
evicted = (warm_id, warm)
|
||||
self._reserved_creates.add(sandbox_id)
|
||||
if evicted is not None and not self._retire(evicted[0], evicted[1], reason="replica_enforcement"):
|
||||
# The evicted remote may still hold its slot: never create a replacement beside it.
|
||||
with self._lock:
|
||||
raise self._capacity_error_locked(replicas, self._retiring_count_locked())
|
||||
yield
|
||||
finally:
|
||||
self._release_reservation(sandbox_id)
|
||||
|
||||
def _capacity_error_locked(self, replicas: int, retiring: int) -> SandboxCapacityExceededError:
|
||||
return SandboxCapacityExceededError(
|
||||
f"All {replicas} OpenSandbox capacity slots are in use and overflow_policy is 'reject'",
|
||||
active=len(self._sandboxes),
|
||||
warm=len(self._warm_pool),
|
||||
reserved=len(self._reserved_creates),
|
||||
transitioning=retiring,
|
||||
replicas=replicas,
|
||||
retry_after_seconds=self.CAPACITY_RETRY_AFTER_SECONDS,
|
||||
)
|
||||
|
||||
def _release_reservation(self, sandbox_id: str) -> None:
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
else:
|
||||
self._sandboxes[sandbox_id] = sandbox
|
||||
self._thread_sandboxes[key] = sandbox_id
|
||||
destroy_after_unlock = False
|
||||
if destroy_after_unlock:
|
||||
self._destroy_quietly(sandbox, context="created during shutdown")
|
||||
raise RuntimeError("OpenSandboxProvider shut down during acquire")
|
||||
return sandbox_id
|
||||
self._reserved_creates.discard(sandbox_id)
|
||||
|
||||
def _create_sandbox(self, sandbox_id: str, *, thread_id: str | None, user_id: str | None) -> OpenSandboxSandbox:
|
||||
replicas, total = self._replica_count()
|
||||
if total >= replicas:
|
||||
evicted = self._evict_oldest_warm()
|
||||
self._log_replicas_soft_cap(replicas, sandbox_id, evicted)
|
||||
if self._config["overflow_policy"] != "reject":
|
||||
replicas, total = self._replica_count()
|
||||
if total >= replicas:
|
||||
evicted = self._evict_oldest_warm()
|
||||
self._log_replicas_soft_cap(replicas, sandbox_id, evicted)
|
||||
|
||||
sandbox_cls, connection_config_cls, run_command_opts_cls = self._get_sdk()
|
||||
connection_config = self._new_connection_config(connection_config_cls)
|
||||
@ -468,6 +561,8 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
if not sandbox.ping():
|
||||
with self._lock:
|
||||
removed = self._warm_pool.pop(sandbox_id, None)
|
||||
if removed is not None:
|
||||
self._retiring[sandbox_id] = None
|
||||
if removed is not None:
|
||||
self._destroy_warm_entry(sandbox_id, removed[0], reason="health_check_failed")
|
||||
return None
|
||||
@ -475,6 +570,8 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
removed = self._warm_pool.pop(sandbox_id, None)
|
||||
if removed is None:
|
||||
return None
|
||||
# Keep the slot counted until the caller registers or releases it.
|
||||
self._reserved_creates.add(sandbox_id)
|
||||
logger.info("Reclaimed warm OpenSandbox %s (remote=%s)", sandbox_id, sandbox.remote_id)
|
||||
return removed[0]
|
||||
|
||||
@ -511,6 +608,8 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
self._thread_sandboxes.pop(key)
|
||||
if not self._shutdown_called:
|
||||
self._warm_pool[sandbox_id] = (sandbox, time.monotonic())
|
||||
# A reclaimed remote's slot moves back from its reservation to the pool in one step.
|
||||
self._reserved_creates.discard(sandbox_id)
|
||||
return
|
||||
self._destroy_quietly(sandbox, context="skill upload failed during shutdown")
|
||||
|
||||
|
||||
@ -36,6 +36,9 @@ class WarmPoolLifecycleMixin[WarmEntryT]:
|
||||
"""Destroy a warm-pool entry after it has been removed from the pool."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _warm_entries_retiring_locked(self, sandbox_ids: list[str]) -> None:
|
||||
"""Hook while ``_lock`` is held: these entries left the pool and will be destroyed next."""
|
||||
|
||||
def _replica_count(self) -> tuple[int, int]:
|
||||
"""Return configured replicas and current active + warm entry count."""
|
||||
replicas = int(self._config.get("replicas", DEFAULT_REPLICAS))
|
||||
@ -82,6 +85,7 @@ class WarmPoolLifecycleMixin[WarmEntryT]:
|
||||
expired.append((sandbox_id, entry))
|
||||
for sandbox_id, _ in expired:
|
||||
self._warm_pool.pop(sandbox_id, None)
|
||||
self._warm_entries_retiring_locked([sandbox_id for sandbox_id, _ in expired])
|
||||
|
||||
for sandbox_id, entry in expired:
|
||||
self._destroy_warm_entry(sandbox_id, entry, reason="idle_timeout")
|
||||
|
||||
@ -346,7 +346,7 @@ class SandboxConfig(BaseModel):
|
||||
)
|
||||
overflow_policy: SandboxOverflowPolicy = Field(
|
||||
default="wait",
|
||||
description="E2B capacity policy. Use wait, reject, or burst.",
|
||||
description="E2B and OpenSandbox capacity policy. OpenSandbox wait keeps its legacy soft cap; reject enforces a process-local hard cap. Burst is E2B-only.",
|
||||
)
|
||||
acquire_timeout: int = Field(
|
||||
default=30,
|
||||
|
||||
@ -32,11 +32,12 @@ import httpx
|
||||
import pytest
|
||||
from langgraph.runtime import Runtime
|
||||
|
||||
from deerflow.community.opensandbox.provider import OpenSandboxProvider, _import_sdk
|
||||
from deerflow.community.opensandbox.provider import OpenSandboxProvider, _import_sdk, _SkillUploadError
|
||||
from deerflow.community.opensandbox.sandbox import OpenSandboxSandbox
|
||||
from deerflow.config import ExtensionsConfig, SkillsConfig
|
||||
from deerflow.config.extensions_config import SkillStateConfig
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.sandbox.exceptions import SandboxCapacityExceededError
|
||||
from deerflow.sandbox.middleware import SandboxMiddleware
|
||||
from deerflow.sandbox.sandbox_provider import reset_sandbox_provider, set_sandbox_provider
|
||||
from deerflow.skills.projection import get_thread_skill_projection_paths
|
||||
@ -297,6 +298,231 @@ def _box(
|
||||
)
|
||||
|
||||
|
||||
def test_wait_policy_preserves_the_legacy_soft_cap(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "wait"})
|
||||
try:
|
||||
provider.acquire("thread-1")
|
||||
provider.acquire("thread-2")
|
||||
assert len(sdk.create_calls) == 2
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_enforces_capacity_and_transfers_warm_slots(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "reject"})
|
||||
try:
|
||||
first_id = provider.acquire("thread-1")
|
||||
with pytest.raises(SandboxCapacityExceededError) as caught:
|
||||
provider.acquire("thread-2")
|
||||
assert caught.value.details["code"] == SandboxCapacityExceededError.CODE
|
||||
assert caught.value.details["active"] == 1
|
||||
assert caught.value.details["replicas"] == 1
|
||||
assert caught.value.details["retryable"] is True
|
||||
assert caught.value.details["retry_after_seconds"] == OpenSandboxProvider.CAPACITY_RETRY_AFTER_SECONDS
|
||||
assert len(sdk.create_calls) == 1
|
||||
|
||||
provider.release(first_id)
|
||||
second_id = provider.acquire("thread-2")
|
||||
assert sdk.remotes[0].destroy_calls == 1
|
||||
assert len(sdk.create_calls) == 2
|
||||
with pytest.raises(SandboxCapacityExceededError):
|
||||
provider.acquire("thread-3")
|
||||
assert len(sdk.create_calls) == 2
|
||||
assert provider.get(second_id) is not None
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_reserves_capacity_during_inflight_create(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
first_create_entered = threading.Event()
|
||||
release_first_create = threading.Event()
|
||||
second_finished = threading.Event()
|
||||
factory_calls = 0
|
||||
|
||||
def remote_factory(index: int) -> _FakeRemote:
|
||||
nonlocal factory_calls
|
||||
factory_calls += 1
|
||||
if factory_calls == 1:
|
||||
first_create_entered.set()
|
||||
assert release_first_create.wait(timeout=5)
|
||||
return _FakeRemote(f"remote-{factory_calls}")
|
||||
|
||||
provider, sdk = _install(
|
||||
monkeypatch,
|
||||
sdk=_FakeSandboxClass(remote_factory=remote_factory),
|
||||
config={"replicas": 1, "overflow_policy": "reject"},
|
||||
)
|
||||
results: dict[str, str] = {}
|
||||
errors: dict[str, Exception] = {}
|
||||
|
||||
def acquire(name: str) -> None:
|
||||
try:
|
||||
results[name] = provider.acquire(name)
|
||||
except Exception as exc:
|
||||
errors[name] = exc
|
||||
finally:
|
||||
if name == "thread-2":
|
||||
second_finished.set()
|
||||
|
||||
first = threading.Thread(target=acquire, args=("thread-1",))
|
||||
second = threading.Thread(target=acquire, args=("thread-2",))
|
||||
try:
|
||||
first.start()
|
||||
assert first_create_entered.wait(timeout=5)
|
||||
second.start()
|
||||
assert second_finished.wait(timeout=5)
|
||||
assert isinstance(errors.get("thread-2"), SandboxCapacityExceededError)
|
||||
assert errors["thread-2"].details["reserved"] == 1
|
||||
assert len(sdk.create_calls) == 1
|
||||
finally:
|
||||
release_first_create.set()
|
||||
first.join(timeout=5)
|
||||
second.join(timeout=5)
|
||||
provider.shutdown()
|
||||
assert not first.is_alive()
|
||||
assert not second.is_alive()
|
||||
assert "thread-1" not in errors
|
||||
assert results["thread-1"]
|
||||
|
||||
|
||||
def test_reject_policy_releases_capacity_after_create_failure(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
factory_calls = 0
|
||||
|
||||
def fail_first_create(index: int) -> _FakeRemote:
|
||||
nonlocal factory_calls
|
||||
factory_calls += 1
|
||||
if factory_calls == 1:
|
||||
raise RuntimeError("synthetic create failure")
|
||||
return _FakeRemote(f"remote-{factory_calls}")
|
||||
|
||||
provider, sdk = _install(
|
||||
monkeypatch,
|
||||
sdk=_FakeSandboxClass(remote_factory=fail_first_create),
|
||||
config={"replicas": 1, "overflow_policy": "reject"},
|
||||
)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="synthetic create failure"):
|
||||
provider.acquire("thread-1")
|
||||
assert provider.acquire("thread-2")
|
||||
assert len(sdk.create_calls) == 2
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_keeps_a_reclaimed_warm_slot_counted_until_registration(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "reject"})
|
||||
competing: list[BaseException] = []
|
||||
prepare = provider._prepare_new_skill_view
|
||||
|
||||
def prepare_then_compete(sandbox, *, thread_id, user_id):
|
||||
prepare(sandbox, thread_id=thread_id, user_id=user_id)
|
||||
if thread_id == "thread-1" and sdk.create_calls and not competing:
|
||||
# The reclaimed sandbox has left the warm pool but is not active yet.
|
||||
try:
|
||||
provider.acquire("thread-2")
|
||||
except SandboxCapacityExceededError as exc:
|
||||
competing.append(exc)
|
||||
|
||||
try:
|
||||
provider.release(provider.acquire("thread-1"))
|
||||
monkeypatch.setattr(provider, "_prepare_new_skill_view", prepare_then_compete)
|
||||
assert provider.acquire("thread-1")
|
||||
assert len(competing) == 1
|
||||
assert competing[0].details["reserved"] == 1
|
||||
assert len(sdk.create_calls) == 1
|
||||
assert provider._reserved_creates == set()
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_counts_an_idle_sandbox_until_its_deletion_finishes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "reject"})
|
||||
deleting, finish = threading.Event(), threading.Event()
|
||||
try:
|
||||
provider.release(provider.acquire("thread-1"))
|
||||
remote = sdk.remotes[0]
|
||||
|
||||
def slow_destroy() -> None:
|
||||
deleting.set()
|
||||
assert finish.wait(timeout=5)
|
||||
remote.destroy_calls += 1
|
||||
|
||||
remote.destroy = slow_destroy
|
||||
reaper = threading.Thread(target=provider._reap_expired_warm, args=(1e-9,))
|
||||
reaper.start()
|
||||
assert deleting.wait(timeout=5)
|
||||
with pytest.raises(SandboxCapacityExceededError) as caught:
|
||||
provider.acquire("thread-2")
|
||||
assert caught.value.details["transitioning"] == 1
|
||||
assert len(sdk.create_calls) == 1
|
||||
finish.set()
|
||||
reaper.join(timeout=5)
|
||||
assert provider.acquire("thread-2")
|
||||
assert len(sdk.create_calls) == 2
|
||||
finally:
|
||||
finish.set()
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_refuses_a_replacement_when_eviction_fails(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "reject"})
|
||||
try:
|
||||
provider.release(provider.acquire("thread-1"))
|
||||
|
||||
def failing_destroy() -> None:
|
||||
raise RuntimeError("synthetic deletion timeout")
|
||||
|
||||
sdk.remotes[0].destroy = failing_destroy
|
||||
for thread_id in ("thread-2", "thread-3"):
|
||||
with pytest.raises(SandboxCapacityExceededError) as caught:
|
||||
provider.acquire(thread_id)
|
||||
assert caught.value.details["transitioning"] == 1
|
||||
assert len(sdk.create_calls) == 1
|
||||
assert provider._reserved_creates == set()
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_reject_policy_hands_a_failed_reclaim_back_to_the_pool_atomically(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 2, "overflow_policy": "reject"})
|
||||
try:
|
||||
provider.release(provider.acquire("thread-1"))
|
||||
|
||||
def failing_upload(sandbox, *, thread_id, user_id):
|
||||
raise _SkillUploadError("synthetic skill upload failure")
|
||||
|
||||
counted_twice: list[bool] = []
|
||||
release = provider._release_reservation
|
||||
|
||||
def observe_release(sandbox_id: str) -> None:
|
||||
with provider._lock:
|
||||
counted_twice.append(sandbox_id in provider._reserved_creates and sandbox_id in provider._warm_pool)
|
||||
release(sandbox_id)
|
||||
|
||||
monkeypatch.setattr(provider, "_prepare_new_skill_view", failing_upload)
|
||||
monkeypatch.setattr(provider, "_release_reservation", observe_release)
|
||||
with pytest.raises(_SkillUploadError):
|
||||
provider.acquire("thread-1")
|
||||
assert counted_twice == [False]
|
||||
assert len(provider._warm_pool) == 1
|
||||
assert provider._reserved_creates == set()
|
||||
assert sdk.remotes[0].destroy_calls == 0
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_burst_policy_warns_that_opensandbox_keeps_the_soft_cap(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
||||
with caplog.at_level(logging.WARNING, logger="deerflow.community.opensandbox.provider"):
|
||||
provider, sdk = _install(monkeypatch, config={"replicas": 1, "overflow_policy": "burst"})
|
||||
try:
|
||||
assert "overflow_policy 'burst' is E2B-only" in caplog.text
|
||||
provider.acquire("thread-1")
|
||||
provider.acquire("thread-2")
|
||||
assert len(sdk.create_calls) == 2
|
||||
finally:
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_missing_sdk_has_actionable_error(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
for module_name in (
|
||||
"opensandbox",
|
||||
|
||||
@ -2052,6 +2052,7 @@ sandbox:
|
||||
# # sandbox_timeout: 14400 # finite non-negative remote lifetime seconds; 0 = explicit cleanup
|
||||
# # bash_command_timeout: 600 # default remote command timeout seconds
|
||||
# # replicas: 3 # active + warm cap per gateway process
|
||||
# # overflow_policy: wait # reject adds a process-local hard cap including in-flight creates
|
||||
# # idle_timeout: 600 # warm seconds before destroy; 0 disables
|
||||
# # environment: # create-time and per-command defaults
|
||||
# # PYTHONUNBUFFERED: "1"
|
||||
|
||||
@ -294,6 +294,16 @@ from a complete scan with no produced outputs; it does not prove that no outputs
|
||||
were produced. Outputs modified and observed in both snapshots still participate
|
||||
in that check.
|
||||
|
||||
`OpenSandboxProvider` preserves its legacy soft cap by default. Set
|
||||
`overflow_policy: reject` to make `replicas` a process-local hard cap covering
|
||||
active sandboxes, the warm pool and in-flight create reservations. A full pool
|
||||
with no warm sandbox to evict raises `SandboxCapacityExceededError` before an
|
||||
SDK create, with a 30 second retry hint. Failed creates release their
|
||||
reservations. `burst` is E2B-only: OpenSandbox logs a warning and keeps the
|
||||
soft cap. This is not a
|
||||
multi-process quota: use it only when one Gateway process owns the provider and
|
||||
`replicas` fits the Kubernetes ResourceQuota.
|
||||
|
||||
`E2BSandboxProvider` uses `wait` as its default overflow policy. It waits for
|
||||
`acquire_timeout`, then fails the agent turn. DeerFlow does not retry the turn
|
||||
automatically. Clients can use the structured error to schedule a retry.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user