fix(sandbox): defer fresh OpenSandbox skill-policy acquisition (#8590)

* fix(sandbox): defer fresh OpenSandbox skill-policy acquisition

OpenSandbox acquire now installs the thread's prepared skill view on new
and warm remotes (clearing first, so a failed upload never leaves another
view behind), and the provider opts in to
supports_lazy_agent_skill_isolation. A fresh run with an explicit Agent
skill list, including an empty one, no longer acquires a remote before
its first sandbox tool call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>

* fix(sandbox): keep eager skill sync when the thread's OpenSandbox remote is active

A deferred acquire reuses an active remote after renew() without installing
the run's prepared skill view, so a policy-scoped run that starts while an
upload holds the thread's remote would keep the previous view. Providers can
now report such a remote (holds_active_thread_sandbox); the middleware then
keeps the eager acquire and strict sync_agent_skills. Fresh runs still defer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>

* docs: remove changelog changes from OpenSandbox fix

* fix(opensandbox): sync skills when a remote is initializing

---------

Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
Bas Cancrinus 2026-11-25 14:26:16 +01:00 committed by GitHub
parent 72ca21dd4b
commit f56fb962d0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 159 additions and 16 deletions

View File

@ -80,11 +80,13 @@ model request.
### Sandbox System
With lazy initialization, a fresh AIO run prepares its authorized Agent skill
view without acquiring a container until a sandbox-backed tool needs one.
Existing sandbox state still requires eager policy rebinding; upload-based
providers still acquire and synchronize skills eagerly. Explicit sandbox
prewarming remains a separate opt-in behavior.
With lazy initialization, a fresh AIO or OpenSandbox run prepares its
authorized Agent skill view without acquiring a sandbox until a sandbox-backed
tool needs one. OpenSandbox installs that view when the tool acquires the
remote. A run with existing sandbox state still rebinds eagerly. OpenSandbox
also synchronizes eagerly when another operation holds or is initializing the
thread's remote. Other upload-based providers acquire and synchronize skills
eagerly. Explicit sandbox prewarming remains a separate opt-in behavior.
Per-thread isolated execution with virtual path translation:

View File

@ -21,6 +21,12 @@ for the SDK default.
- **Deadline tests use execution results.** A `TimeoutError` that only a fake
raises does not test the contract.
## Agent skill views
Keep eager skill synchronization when the thread's remote is active or its
acquire is in flight. Read the registry and scope serializer together so the
remote cannot be published between the two checks.
## Output synchronization
- **Release mirrors the output files to the host before it parks the client.**

View File

@ -131,6 +131,10 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
uses_thread_data_mounts = False
needs_upload_permission_adjustment = True
supports_agent_skill_isolation = True
# acquire() installs the thread's prepared skill view on new and warm
# remotes, so a fresh policy-scoped run can defer acquisition. An active
# or initializing remote can already hold a different view.
supports_lazy_agent_skill_isolation = True
_idle_checker_thread_name = "opensandbox-idle-reaper"
_MAX_SYNC_FILES = 2000
_MAX_SYNC_TOTAL_BYTES = 512 * 1024 * 1024
@ -307,6 +311,17 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
logger.warning("Invalidating OpenSandbox %s after terminal failure: %s", sandbox_id, reason)
self._destroy_quietly(sandbox, context="terminal failure")
def requires_eager_agent_skill_sync(self, thread_id: str, *, user_id: str | None) -> bool:
sandbox_id = self._sandbox_id(thread_id, user_id or "")
with self._lock:
existing = self._thread_sandboxes.get(self._thread_key(thread_id, user_id))
if existing is not None and existing in self._sandboxes:
return True
# An acquire can already be uploading an older view before the
# remote enters the active registry. Read both under the registry
# lock so publication cannot fall between these checks.
return self._acquire_serializer.has_pending(sandbox_id)
def acquire(self, thread_id: str | None = None, *, user_id: str | None = None) -> str:
with self._lock:
if self._shutdown_called:
@ -470,14 +485,20 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
def _prepare_new_skill_view(self, sandbox: OpenSandboxSandbox, *, thread_id: str | None, user_id: str | None) -> None:
if not user_id:
return
from deerflow.skills.projection import ensure_skill_projections, thread_skill_projection_exists
from deerflow.skills.projection import ensure_skill_projections, get_thread_skill_projection_paths, thread_skill_projection_exists
from deerflow.skills.storage import get_or_new_user_skill_storage
storage = get_or_new_user_skill_storage(user_id, app_config=get_app_config())
# Eager middleware installs the scoped view. Until then do not expose
# either the shared view or the previous agent's files on a warm remote.
projection = None if thread_id is not None and thread_skill_projection_exists(storage, thread_id) else ensure_skill_projections(storage)
self._replace_skill_projection(sandbox, projection)
if thread_id is not None and thread_skill_projection_exists(storage, thread_id):
# A policy-scoped thread gets the view the middleware prepared for
# the run. Clear first so a failed upload never leaves the shared
# view or a previous agent's files on a parked warm remote.
# Installing the view here lets the middleware defer acquisition
# to the first sandbox tool call (supports_lazy_agent_skill_isolation).
self._replace_skill_projection(sandbox, None)
self._replace_skill_projection(sandbox, get_thread_skill_projection_paths(storage, thread_id))
return
self._replace_skill_projection(sandbox, ensure_skill_projections(storage))
def _park_failed_skill_upload(self, sandbox: OpenSandboxSandbox, *, was_active: bool) -> None:
sandbox_id = sandbox.id

View File

@ -124,6 +124,11 @@ class AcquireSerializer[KeyT: Hashable]:
"""
return self._executor
def has_pending(self, key: KeyT) -> bool:
"""Report a holder or waiter for this key without taking its scope lock."""
with self._table_lock:
return key in self._table
async def run_on_executor[**P, T](self, func: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
"""Run a blocking callable on the serializer's dedicated executor.

View File

@ -150,9 +150,12 @@ class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]):
return False
provider = get_sandbox_provider()
self._require_projection_support(provider, projection)
# AIO mounts the stable projection roots during canonical acquisition.
# Upload-based providers still need eager acquire + strict skill sync.
return provider.supports_lazy_agent_skill_isolation
# Providers that install the view during acquire may defer, unless
# the provider needs to refresh an active or initializing remote.
if not provider.supports_lazy_agent_skill_isolation:
return False
thread_id = (runtime.context or {}).get("thread_id")
return not provider.requires_eager_agent_skill_sync(thread_id, user_id=resolve_runtime_user_id(runtime))
def _acquire_sandbox(
self,

View File

@ -30,6 +30,15 @@ class SandboxProvider(ABC):
_signal_handlers_deferred = False
def requires_eager_agent_skill_sync(self, thread_id: str, *, user_id: str | None) -> bool:
"""Whether this scope needs eager synchronization on a lazy provider.
Providers can require eager acquisition and strict ``sync_agent_skills``
when an active or initializing remote could reuse an older skill view.
This lookup reads only in-memory state.
"""
return False
def _register_signal_handlers(self) -> None:
"""Install process signal handlers for providers that own sandbox resources."""

View File

@ -22,6 +22,7 @@ import sys
import threading
import time
import types
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import timedelta
from pathlib import Path
@ -645,8 +646,11 @@ def test_opensandbox_skill_views_replace_on_warm_reuse(opensandbox_skill_view):
for allowlist, expected in [({"alpha"}, {"alpha"}), (set(), set()), (None, {"alpha", "beta", "alice-only"})]:
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
update = SandboxMiddleware(lazy_init=True, available_skills=allowlist).before_agent({}, runtime)
assert update == {"sandbox": {"sandbox_id": alice_id}}
# A fresh run defers acquisition; the first sandbox tool's acquire
# reclaims the warm remote with the run's scoped view.
assert SandboxMiddleware(lazy_init=True, available_skills=allowlist).before_agent({}, runtime) is None
assert "sandbox_id" not in runtime.context
assert env.provider.acquire("thread", user_id="alice") == alice_id
assert _remote_skills(alice) == expected
assert {p.name for p in alice.skill_root.iterdir()} == {"public", "custom", "legacy", "integrations"}
env.provider.release(alice_id)
@ -654,6 +658,98 @@ def test_opensandbox_skill_views_replace_on_warm_reuse(opensandbox_skill_view):
assert _remote_skills(bob) == {"alpha", "beta", "bob-only"}
def test_opensandbox_policy_run_without_sandbox_tool_creates_no_remote(opensandbox_skill_view):
env = opensandbox_skill_view
env.skill("alpha")
runtime = Runtime(context={"thread_id": "fresh", "user_id": "alice"})
assert SandboxMiddleware(lazy_init=True, available_skills=set()).before_agent({}, runtime) is None
assert env.sdk.remotes == []
assert "sandbox_id" not in runtime.context
# A later sandbox tool gets a remote holding only the (empty) scoped view.
sandbox_id = env.provider.acquire("fresh", user_id="alice")
remote = env.sdk.remotes[0]
assert env.provider.get(sandbox_id) is not None
assert _remote_skills(remote) == set()
assert {p.name for p in remote.skill_root.iterdir()} == {"public", "custom", "legacy", "integrations"}
def test_opensandbox_policy_run_syncs_a_remote_an_upload_holds(opensandbox_skill_view):
env = opensandbox_skill_view
env.skill("alpha")
# An upload acquired the thread's remote before the run started.
sandbox_id = env.provider.acquire("thread", user_id="alice")
remote = env.sdk.remotes[0]
assert _remote_skills(remote) == {"alpha"}
env.skill("beta")
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
# The active remote would be reused without the run's view: stay eager.
update = SandboxMiddleware(lazy_init=True, available_skills={"alpha", "beta"}).before_agent({}, runtime)
assert update == {"sandbox": {"sandbox_id": sandbox_id}}
assert env.sdk.remotes == [remote]
assert _remote_skills(remote) == {"alpha", "beta"}
assert env.provider.acquire("thread", user_id="alice") == sandbox_id
assert _remote_skills(remote) == {"alpha", "beta"}
def test_opensandbox_policy_run_syncs_a_remote_an_upload_is_initializing(opensandbox_skill_view, monkeypatch):
env = opensandbox_skill_view
env.skill("alpha")
initial_skill_written = threading.Event()
allow_publish = threading.Event()
create_remote = env.sdk.remote_factory
def create_paused_remote(index):
remote = create_remote(index)
write_file = remote.files.write_file
def write(path, data, *, mode):
write_file(path, data, mode=mode)
if not initial_skill_written.is_set():
initial_skill_written.set()
assert allow_publish.wait(10)
remote.files.write_file = write
return remote
monkeypatch.setattr(env.sdk, "remote_factory", create_paused_remote)
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
middleware = SandboxMiddleware(lazy_init=True, available_skills={"alpha", "beta"})
decision_made = threading.Event()
can_defer = middleware._can_defer_sandbox_acquisition
def record_decision(*args):
result = can_defer(*args)
decision_made.set()
return result
monkeypatch.setattr(middleware, "_can_defer_sandbox_acquisition", record_decision)
with ThreadPoolExecutor(max_workers=2) as executor:
upload = executor.submit(env.provider.acquire, "thread", user_id="alice")
try:
assert initial_skill_written.wait(10)
remote = env.sdk.remotes[0]
assert _remote_skills(remote) == {"alpha"}
env.skill("beta")
# Another user's run on the same thread ID can still stay lazy.
other_user = Runtime(context={"thread_id": "thread", "user_id": "bob"})
assert SandboxMiddleware(lazy_init=True, available_skills={"alpha"}).before_agent({}, other_user) is None
run = executor.submit(middleware.before_agent, {}, runtime)
assert decision_made.wait(10)
finally:
allow_publish.set()
sandbox_id = upload.result(timeout=10)
update = run.result(timeout=10)
assert env.provider.acquire("thread", user_id="alice") == sandbox_id
assert env.sdk.remotes == [remote]
assert _remote_skills(remote) == {"alpha", "beta"}
assert update == {"sandbox": {"sandbox_id": sandbox_id}}
@pytest.mark.parametrize("restricted", [False, True])
def test_opensandbox_skill_partial_upload_preserves_warm_workspace(opensandbox_skill_view, monkeypatch, restricted):
env = opensandbox_skill_view
@ -711,7 +807,8 @@ def test_opensandbox_skill_upload_preserves_package_links(opensandbox_skill_view
(package / "empty link").symlink_to("assets/empty", target_is_directory=True)
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
SandboxMiddleware(lazy_init=True, available_skills={"allowed"}).before_agent({}, runtime)
assert SandboxMiddleware(lazy_init=True, available_skills={"allowed"}).before_agent({}, runtime) is None
env.provider.acquire("thread", user_id="alice")
uploaded = env.sdk.remotes[0].skill_root / "custom" / "allowed"
assert (uploaded / "file link").is_symlink()
assert (uploaded / "file link").read_bytes() == b"data"