Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(workspace): add workspace pool for pooling (#1755)
Yue Cuib0229ba49f4e
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex 46df69ce6..9a7216abc 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -285,6 +285,7 @@ def create_app(# Attach shared state that lifespan and dependencies read from app.stateapp.state.storage = storageapp.state.message_bus = message_bus+ workspace_manager.bind_storage(storage)app.state.workspace_manager = workspace_managerapp.state.knowledge_base_manager = knowledge_base_managerapp.state.extra_agent_middlewares = extra_agent_middlewaresdiff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex a4b2b8dd4..f90cb22f6 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -336,7 +336,7 @@ async def create_session(# flows to force sharing); otherwise defer to the manager's# isolation policy — see ``WorkspaceManagerBase.assign_workspace_id``.resolved_workspace_id = body.workspace_id or (- workspace_manager.assign_workspace_id(+ await workspace_manager.assign_workspace_id(user_id=user_id,agent_id=body.agent_id,session_id=_generate_id(),diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.pyindex 187242873..3691da8f1 100644--- a/src/agentscope/app/_tool/_agent_invite.py+++ b/src/agentscope/app/_tool/_agent_invite.py@@ -345,7 +345,7 @@ class AgentInvite(_TeamToolBase):)else:borrowed_workspace_id = (- self._workspace_manager.assign_workspace_id(+ await self._workspace_manager.assign_workspace_id(user_id=self._user_id,agent_id=invited.id,session_id=_generate_id(),diff --git a/src/agentscope/app/channel/_gateway.py b/src/agentscope/app/channel/_gateway.pyindex b63fd0ecd..a7f560735 100644--- a/src/agentscope/app/channel/_gateway.py+++ b/src/agentscope/app/channel/_gateway.py@@ -243,7 +243,7 @@ class ChannelGateway:fallback = record.session.fallback_chat_model_configsession_config = SessionConfig(- workspace_id=self._workspace_manager.assign_workspace_id(+ workspace_id=await self._workspace_manager.assign_workspace_id(user_id=record.user_id,agent_id=agent_id,session_id=session_id,diff --git a/src/agentscope/app/channel/worker/__init__.py b/src/agentscope/app/channel/worker/__init__.pyindex 35126dc20..b332a8a93 100644--- a/src/agentscope/app/channel/worker/__init__.py+++ b/src/agentscope/app/channel/worker/__init__.py@@ -95,6 +95,7 @@ async def run_channel_worker(async with AsyncExitStack() as stack:await stack.enter_async_context(storage)await stack.enter_async_context(message_bus)+ workspace_manager.bind_storage(storage)await stack.enter_async_context(workspace_manager)dispatcher = ChannelLifecycleDispatcher(diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.pyindex fd88ca9b6..4b27f0e42 100644--- a/src/agentscope/app/workspace_manager/__init__.py+++ b/src/agentscope/app/workspace_manager/__init__.py@@ -3,6 +3,7 @@and their lifecycles, and filesystem isolation."""from ._base import IsolationPolicy, WorkspaceManagerBase+from ._prewarm import PrewarmConfigfrom ._local_workspace_manager import LocalWorkspaceManagerfrom ._docker_workspace_manager import DockerWorkspaceManagerfrom ._e2b_workspace_manager import E2BWorkspaceManager@@ -16,6 +17,7 @@ from ._bubblewrap_workspace_manager import BubblewrapWorkspaceManager__all__ = ["IsolationPolicy",+ "PrewarmConfig","WorkspaceManagerBase","LocalWorkspaceManager","BubblewrapWorkspaceManager",diff --git a/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.pyindex 0d2af4ade..6987779d6 100644--- a/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py@@ -175,7 +175,7 @@ class AppleContainerWorkspaceManager(WorkspaceManagerBase):del session_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",diff --git a/src/agentscope/app/workspace_manager/_base.py b/src/agentscope/app/workspace_manager/_base.pyindex 2a6ba1eef..a0b03693f 100644--- a/src/agentscope/app/workspace_manager/_base.py+++ b/src/agentscope/app/workspace_manager/_base.py@@ -1,14 +1,19 @@# -*- coding: utf-8 -*-"""Workspace manager implementations."""+import asyncioimport hashlibfrom abc import ABC, abstractmethod+from collections import defaultdictfrom enum import StrEnum-from typing import Self+from typing import TYPE_CHECKING, Selffrom ..._utils._common import _generate_idfrom ...workspace import WorkspaceBase+if TYPE_CHECKING:+ from ..storage import StorageBase+class IsolationPolicy(StrEnum):"""Workspace isolation grain for@@ -49,8 +54,33 @@ class WorkspaceManagerBase(ABC):Isolation grain for the manager."""self._isolation: IsolationPolicy = isolation+ self._storage: "StorageBase | None" = None+ # Serialises read-binding-then-mint per (user, agent), so two+ # concurrent first sessions cannot each mint a workspace.+ self._bind_locks: defaultdict[+ tuple[str, str],+ asyncio.Lock,+ ] = defaultdict(asyncio.Lock)+ # Ids handed out but not yet persisted by the session flow.+ # The lock is released before that write lands, so without+ # this the next request would read an empty session list and+ # bind a second workspace to the same pair.+ self._reserved: dict[tuple[str, str], str] = {}++ def bind_storage(self, storage: "StorageBase") -> None:+ """Hand the manager the backend holding workspace bindings.++ Wired by :func:`agentscope.app.create_app` rather than taken as+ a constructor argument, because the application author builds+ the manager before the app exists to supply a storage backend.++ Args:+ storage (`StorageBase`):+ The application's storage backend.+ """+ self._storage = storage- def assign_workspace_id(+ async def assign_workspace_id(self,*,user_id: str,@@ -59,14 +89,27 @@ class WorkspaceManagerBase(ABC):) -> str:"""Mint a workspace id under :attr:`_isolation`.- Pure function — no I/O, no storage access. Called by the- session-creation flow when the caller did not supply an- explicit ``workspace_id``.+ Called by the session-creation flow when the caller did not+ supply an explicit ``workspace_id``.* ``PER_SESSION`` → fresh UUID.- * ``PER_AGENT`` → deterministic BLAKE2b of ``user::agent``.+ * ``PER_AGENT`` → the id an earlier session of this+ ``(user, agent)`` already bound, else a fresh one. A team+ worker's binding is its leader's workspace, which the team+ flow assigns on purpose. Without a storage backend the+ binding cannot be read, so a deterministic BLAKE2b of+ ``user::agent`` stands in for it.+ A minted id is held until a session record carries it, since+ that write lands after this returns. Both the serialisation+ and the reservation are process-local: two app workers+ racing the very first session of one pair can still bind two+ workspaces to it.* ``PER_USER`` → deterministic BLAKE2b of ``user::``.+ Managers that pre-warm override this to draw the fresh ids from+ their buffer, so the id of an already-running workspace becomes+ the binding rather than naming one still to be built.+Args:user_id (`str`):The owning user id.@@ -81,16 +124,40 @@ class WorkspaceManagerBase(ABC):A workspace id."""del session_id- if self._isolation is IsolationPolicy.PER_AGENT:+ if self._isolation is IsolationPolicy.PER_USER:return hashlib.blake2b(- f"{user_id}::{agent_id}".encode("utf-8"),+ f"user::{user_id}".encode("utf-8"),digest_size=8,).hexdigest()- if self._isolation is IsolationPolicy.PER_USER:+ if self._isolation is not IsolationPolicy.PER_AGENT:+ return await self._mint_workspace_id()++ if self._storage is None:return hashlib.blake2b(- f"user::{user_id}".encode("utf-8"),+ f"{user_id}::{agent_id}".encode("utf-8"),digest_size=8,).hexdigest()+ async with self._bind_locks[(user_id, agent_id)]:+ for record in await self._storage.list_sessions(+ user_id,+ agent_id,+ ):+ if record.config.workspace_id:+ self._reserved.pop((user_id, agent_id), None)+ return record.config.workspace_id+ reserved = self._reserved.get((user_id, agent_id))+ if reserved:+ return reserved+ workspace_id = await self._mint_workspace_id()+ self._reserved[(user_id, agent_id)] = workspace_id+ return workspace_id++ async def _mint_workspace_id(self) -> str:+ """Produce an id for a workspace nobody holds yet.++ The pre-warming managers override this to return the id of a+ buffered, already-running workspace.+ """return _generate_id()@abstractmethoddiff --git a/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.pyindex 86dccbffc..e6e34d406 100644--- a/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py@@ -149,7 +149,7 @@ class BubblewrapWorkspaceManager(WorkspaceManagerBase):) -> BubblewrapWorkspace:"""Return an initialized workspace, creating it on cache miss."""if workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id=session_id,diff --git a/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.pyindex 22860da2a..7049cba15 100644--- a/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py@@ -208,7 +208,7 @@ class DaytonaWorkspaceManager(WorkspaceManagerBase):del session_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",diff --git a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py b/src/agentscope/app/workspace_manager/_docker_workspace_manager.pyindex ca7e144d3..ed5784a0d 100644--- a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_docker_workspace_manager.py@@ -33,6 +33,7 @@ from typing import Selffrom typing_extensions import deprecatedfrom ..._logging import logger+from ..._utils._common import _generate_idfrom ...mcp import MCPClientfrom ...workspace import DockerWorkspacefrom ...workspace._docker._make_dockerfile import (@@ -40,11 +41,15 @@ from ...workspace._docker._make_dockerfile import (DEFAULT_GATEWAY_PORT,)from ._base import WorkspaceManagerBase, IsolationPolicy+from ._prewarm import PrewarmConfig, WorkspacePrewarmMixinDEFAULT_SWEEP_INTERVAL = 300.0-class DockerWorkspaceManager(WorkspaceManagerBase):+class DockerWorkspaceManager(+ WorkspacePrewarmMixin[DockerWorkspace],+ WorkspaceManagerBase,+):"""Manages :class:`DockerWorkspace` instances with TTL-based caching.The manager owns a single set of image-build parameters@@ -71,15 +76,20 @@ class DockerWorkspaceManager(WorkspaceManagerBase):skill_paths: list[str] | None = None,ttl: float = 3600.0,sweep_interval: float = DEFAULT_SWEEP_INTERVAL,+ prewarm: PrewarmConfig | None = None,) -> None:"""Initialize the docker workspace manager.Args:basedir (`str`):- Host root under which per-user/per-agent workdir are- created (``<basedir>/<user_id>/<agent_id>``). Each- workdir is bind-mounted to ``/workspace`` inside its- container.+ Host root under which per-workspace workdir are+ created (``<basedir>/<workspace_id>``). Each workdir+ is bind-mounted to ``/workspace`` inside its container.+ Keying on the workspace id — rather than on+ ``(user, agent)`` — is what lets a container be built+ before anyone knows who will get it. Workspaces built+ under the older ``<basedir>/<user_id>/<agent_id>``+ layout keep mounting that directory.isolation (`IsolationPolicy`, defaults to `PER_AGENT`):Isolation grain for :meth:`assign_workspace_id`.``PER_SESSION`` → fresh UUID (one workspace per@@ -113,6 +123,10 @@ class DockerWorkspaceManager(WorkspaceManagerBase):sweep_interval (`float`, defaults to `DEFAULT_SWEEP_INTERVAL`):How often (seconds) the background sweeper wakes upto look for idle workspaces. Defaults to 5 minutes.+ prewarm (`PrewarmConfig | None`, optional):+ Keep this many containers built and idle, ready to be+ handed to the next session that needs one. ``None``+ disables pre-warming."""self._basedir = os.path.abspath(basedir)self._base_image = base_image@@ -122,7 +136,8 @@ class DockerWorkspaceManager(WorkspaceManagerBase):self._env = dict(env or {})self._default_mcps = list(default_mcps or [])self._skill_paths = list(skill_paths or [])- super().__init__(isolation=isolation)+ WorkspacePrewarmMixin.__init__(self, prewarm=prewarm)+ WorkspaceManagerBase.__init__(self, isolation=isolation)self._ttl = ttlself._sweep_interval = sweep_interval@@ -133,35 +148,81 @@ class DockerWorkspaceManager(WorkspaceManagerBase):# ── isolation helpers ─────────────────────────────────────────- def _workdir_for(self, user_id: str, agent_id: str) -> str:- """Resolve the host workdir for ``(user_id, agent_id)``.+ def _workdir_for(+ self,+ workspace_id: str,+ user_id: str = "",+ agent_id: str = "",+ ) -> str:+ """Resolve the host workdir bind-mounted into ``workspace_id``.++ Keyed on the workspace id, so the directory can be created+ alongside a pre-warmed container, long before the+ ``(user, agent)`` that will own it is known.++ A session may name its own ``workspace_id``, and this path is+ bind-mounted read-write into the container, so a value that+ escapes ``basedir`` would hand the container the host+ filesystem. Anything not landing strictly inside is rejected.- Two-level layout — ``<basedir>/<user_id>/<agent_id>`` — so- different users never share a bind-mount even when their- ``agent_id`` collides.+ Args:+ workspace_id (`str`):+ The workspace whose bind mount is being resolved.+ user_id (`str`, defaults to `""`):+ Owner of the workspace, for the legacy layout below.+ Empty for a workspace nobody owns yet.+ agent_id (`str`, defaults to `""`):+ Agent of the workspace, for the legacy layout below.++ Raises:+ `ValueError`:+ If ``workspace_id`` resolves outside ``basedir``."""- return os.path.join(self._basedir, user_id, agent_id)+ root = os.path.realpath(self._basedir)+ workdir = os.path.realpath(os.path.join(root, workspace_id))+ if not workdir.startswith(root + os.sep):+ raise ValueError(+ f"workspace_id {workspace_id!r} escapes the workspace "+ f"base directory",+ )+ if os.path.isdir(workdir) or not (user_id and agent_id):+ return workdir++ # Workspaces built before the id-keyed layout live under+ # ``<basedir>/<user_id>/<agent_id>``. Keep mounting such a+ # directory where it stands: several workspace ids may share+ # one, so no rename can move them all. Legacy paths escaping+ # ``basedir`` are declined rather than rejected, leaving the+ # caller with an ordinary empty workspace.+ legacy = os.path.realpath(os.path.join(root, user_id, agent_id))+ if legacy.startswith(root + os.sep) and os.path.isdir(legacy):+ return legacy+ return workdir# ── workspace construction ────────────────────────────────────async def _build_and_start(self,*,- workspace_id: str,- user_id: str,- agent_id: str,+ workspace_id: str | None = None,+ user_id: str = "",+ agent_id: str = "",) -> DockerWorkspace:- """Create a :class:`DockerWorkspace` for ``(user_id, agent_id)``- and run its full ``initialize``.-- ``workspace_id`` is forwarded so the container name is- deterministic and the same id round-trips through the cache.+ """Create a :class:`DockerWorkspace` and run its full+ ``initialize``.++ ``workspace_id`` names both the container and its host workdir,+ so the same id round-trips through the cache and re-attaches+ after a restart. ``None`` mints one. ``user_id``/``agent_id``+ are forwarded only to find a legacy workdir — see+ :meth:`_workdir_for`."""- workdir = self._workdir_for(user_id, agent_id)+ workspace_id = workspace_id or _generate_id()+ workdir = self._workdir_for(workspace_id, user_id, agent_id)os.makedirs(workdir, exist_ok=True)ws = DockerWorkspace(workspace_id=workspace_id,- workdir=workdir,+ host_workdir=workdir,base_image=self._base_image,node_version=self._node_version,extra_pip=self._extra_pip,@@ -215,7 +276,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):del session_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",@@ -277,21 +338,9 @@ class DockerWorkspaceManager(WorkspaceManagerBase):`DockerWorkspace`:The newly built workspace, already initialised."""- del session_id # accepted for interface parity; not used here+ del user_id, agent_id, session_id # kept for interface parity- workdir = self._workdir_for(user_id, agent_id)- os.makedirs(workdir, exist_ok=True)- ws = DockerWorkspace(- host_workdir=workdir,- base_image=self._base_image,- node_version=self._node_version,- extra_pip=self._extra_pip,- gateway_port=self._gateway_port,- env=self._env,- default_mcps=self._default_mcps,- skill_paths=self._skill_paths,- )- await ws.initialize()+ ws = await self._build_and_start()async with self._lock:self._cache[ws.workspace_id] = (ws, time.monotonic())return ws@@ -329,16 +378,37 @@ class DockerWorkspaceManager(WorkspaceManagerBase):return_exceptions=True,)+ # ── pre-warming hooks ─────────────────────────────────────────++ async def _create_prewarmed(self) -> DockerWorkspace:+ """Build a container for nobody in particular."""+ ws = await self._build_and_start()+ logger.info(+ "DockerWorkspaceManager: pre-warmed workspace %s",+ ws.workspace_id,+ )+ return ws++ async def _adopt_prewarmed(self, workspace: DockerWorkspace) -> None:+ """Track a handed-out container under the ordinary TTL cache."""+ async with self._lock:+ self._cache[workspace.workspace_id] = (+ workspace,+ time.monotonic(),+ )+# ── async context manager ─────────────────────────────────────async def __aenter__(self) -> Self:- """Start the TTL sweeper task."""+ """Start the TTL sweeper task and fill the pre-warm buffer."""if self._sweep_task is None:self._sweep_task = asyncio.create_task(self._sweep_loop())+ self._start_prewarm()return selfasync def __aexit__(self, *exc: object) -> None:- """Stop the TTL sweeper task, then close every cached workspace."""+ """Stop the sweeper and buffer, then close every workspace."""+ await self._stop_prewarm()if self._sweep_task is not None:self._sweep_task.cancel()try:diff --git a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.pyindex 0c641c365..b3745867c 100644--- a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py@@ -47,11 +47,15 @@ from ...workspace._e2b._constants import (DEFAULT_TIMEOUT,)from ._base import WorkspaceManagerBase, IsolationPolicy+from ._prewarm import PrewarmConfig, WorkspacePrewarmMixinDEFAULT_SWEEP_INTERVAL = 300.0-class E2BWorkspaceManager(WorkspaceManagerBase):+class E2BWorkspaceManager(+ WorkspacePrewarmMixin[E2BWorkspace],+ WorkspaceManagerBase,+):"""Manages :class:`E2BWorkspace` instances with TTL-based caching.Use the manager as an ``async with`` context manager: entering it@@ -75,6 +79,7 @@ class E2BWorkspaceManager(WorkspaceManagerBase):skill_paths: list[str] | None = None,ttl: float = 3600.0,sweep_interval: float = DEFAULT_SWEEP_INTERVAL,+ prewarm: PrewarmConfig | None = None,) -> None:"""Initialize the E2B workspace manager.@@ -118,6 +123,11 @@ class E2BWorkspaceManager(WorkspaceManagerBase):sweep_interval (`float`, defaults to `DEFAULT_SWEEP_INTERVAL`):How often (seconds) the background sweeper wakes upto look for idle workspaces. Defaults to 5 minutes.+ prewarm (`PrewarmConfig | None`, optional):+ Keep this many sandboxes created and idle, ready to be+ handed to the next session that needs one. ``None``+ disables pre-warming. Idle sandboxes stay running, so+ they bill while they wait — keep the buffer small."""self._template = templateself._api_key = api_key@@ -131,7 +141,8 @@ class E2BWorkspaceManager(WorkspaceManagerBase):self._skill_paths = list(skill_paths or [])self._ttl = ttlself._sweep_interval = sweep_interval- super().__init__(isolation=isolation)+ WorkspacePrewarmMixin.__init__(self, prewarm=prewarm)+ WorkspaceManagerBase.__init__(self, isolation=isolation)# workspace_id → (workspace, last_access_monotonic)self._cache: dict[str, tuple[E2BWorkspace, float]] = {}@@ -186,9 +197,67 @@ class E2BWorkspaceManager(WorkspaceManagerBase):default_mcps=self._default_mcps,skill_paths=self._skill_paths,)- await ws.initialize()+ try:+ await ws.initialize()+ except BaseException:+ # The remote sandbox may already exist — initialize also+ # bootstraps the gateway, and that half can fail on its+ # own. Nothing else holds this workspace, so it would bill+ # forever.+ await self._dispose_prewarmed(ws)+ raisereturn ws+ # ── pre-warming hooks ─────────────────────────────────────────++ async def _create_prewarmed(self) -> E2BWorkspace:+ """Create a sandbox for nobody in particular.++ Carries no ``(user, agent)`` metadata — it is stamped with the+ workspace id only, which is all reattachment needs.+ """+ ws = await self._build_and_start(+ workspace_id=None,+ user_id="",+ agent_id="",+ )+ logger.info(+ "E2BWorkspaceManager: pre-warmed workspace %s",+ ws.workspace_id,+ )+ return ws++ async def _adopt_prewarmed(self, workspace: E2BWorkspace) -> None:+ """Track a handed-out sandbox under the ordinary TTL cache."""+ async with self._lock:+ self._cache[workspace.workspace_id] = (+ workspace,+ time.monotonic(),+ )++ async def _dispose_prewarmed(self, workspace: E2BWorkspace) -> None:+ """Kill a sandbox nobody will come looking for.++ ``close`` only pauses, so that the next ``initialize`` can+ reattach by metadata. An unclaimed sandbox has no such future:+ its id was never persisted, nothing will look it up, and a+ paused sandbox bills for its snapshot indefinitely.+ """+ sandbox = workspace._sandbox # pylint: disable=protected-access+ if sandbox is not None:+ try:+ await sandbox.kill()+ # pylint: disable-next=protected-access+ workspace._sandbox = None+ except Exception as e:+ logger.warning(+ "E2BWorkspaceManager: failed to kill unclaimed "+ "sandbox %s: %s",+ workspace.workspace_id,+ e,+ )+ await workspace.close()+# ── public API ────────────────────────────────────────────────async def get_workspace(@@ -234,7 +303,7 @@ class E2BWorkspaceManager(WorkspaceManagerBase):del session_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",@@ -343,13 +412,15 @@ class E2BWorkspaceManager(WorkspaceManagerBase):# ── async context manager ─────────────────────────────────────async def __aenter__(self) -> Self:- """Start the TTL sweeper task."""+ """Start the TTL sweeper task and fill the pre-warm buffer."""if self._sweep_task is None:self._sweep_task = asyncio.create_task(self._sweep_loop())+ self._start_prewarm()return selfasync def __aexit__(self, *exc: object) -> None:- """Stop the TTL sweeper task, then close every cached workspace."""+ """Stop the sweeper and buffer, then close every workspace."""+ await self._stop_prewarm()if self._sweep_task is not None:self._sweep_task.cancel()try:diff --git a/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.pyindex ffdb49f56..bdf550792 100644--- a/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py@@ -198,7 +198,7 @@ class K8sWorkspaceManager(WorkspaceManagerBase):del session_idif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",diff --git a/src/agentscope/app/workspace_manager/_local_workspace_manager.py b/src/agentscope/app/workspace_manager/_local_workspace_manager.pyindex 1a4e08a69..e5a7907e3 100644--- a/src/agentscope/app/workspace_manager/_local_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_local_workspace_manager.py@@ -88,7 +88,7 @@ class LocalWorkspaceManager(WorkspaceManagerBase):del user_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id="",agent_id=agent_id,session_id="",diff --git a/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py b/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.pyindex c9fd286ca..f7f45e0f2 100644--- a/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py@@ -237,7 +237,7 @@ class OpenSandboxWorkspaceManager(WorkspaceManagerBase):del session_id # accepted for interface parity; not used hereif workspace_id is None:- workspace_id = self.assign_workspace_id(+ workspace_id = await self.assign_workspace_id(user_id=user_id,agent_id=agent_id,session_id="",diff --git a/src/agentscope/app/workspace_manager/_prewarm.py b/src/agentscope/app/workspace_manager/_prewarm.pynew file mode 100644index 000000000..9608c353e--- /dev/null+++ b/src/agentscope/app/workspace_manager/_prewarm.py@@ -0,0 +1,224 @@+# -*- coding: utf-8 -*-+"""Pre-warming for workspace managers.++Provisioning a sandboxed workspace — image pull, container/sandbox+create, gateway bootstrap, health poll — costs seconds to tens of+seconds, and today every one of those seconds lands on the session that+asked for it. :class:`WorkspacePrewarmMixin` keeps a small buffer of+workspaces built *ahead of demand* so a session can be handed one that+is already running.++A buffered slot is an :class:`asyncio.Future`, not a finished+workspace. A taker awaits its slot: ready slots return instantly, and a+slot still being built is simply awaited to completion. So a request+that arrives mid-build waits out the remainder of a build already in+flight rather than starting a second one of its own.++Buffered workspaces are never recycled. One is built, handed out once,+and then lives under the manager's ordinary cache and TTL rules — there+is no check-in path, hence no reset step and no cross-user state to+scrub.+"""++import asyncio+from collections import deque+from typing import Generic, TypeVar++from pydantic import BaseModel, Field++from ..._logging import logger+from ...workspace import WorkspaceBase+from ._base import WorkspaceManagerBase++T = TypeVar("T", bound=WorkspaceBase)+++class PrewarmConfig(BaseModel):+ """How many workspaces a manager keeps built ahead of demand."""++ size: int = Field(+ default=0,+ ge=0,+ description=(+ "Workspaces to keep built and idle, ready to hand to the "+ "next session that needs one. 0 disables pre-warming."+ ),+ )++ max_creating: int = Field(+ default=4,+ gt=0,+ description=(+ "Ceiling on builds running at once, so a burst of sessions "+ "queues instead of stampeding the provider."+ ),+ )+++class WorkspacePrewarmMixin(WorkspaceManagerBase, Generic[T]):+ """A buffer of pre-built, unassigned workspaces.++ Mix in *before* :class:`WorkspaceManagerBase`, parameterised by the+ concrete workspace type, and implement+ :meth:`_create_prewarmed` and :meth:`_adopt_prewarmed`. Drive the+ buffer from the manager's ``__aenter__`` / ``__aexit__`` via+ :meth:`_start_prewarm` and :meth:`_stop_prewarm`.++ No lock guards the buffer: every mutation of :attr:`_slots` and+ :attr:`_built` runs to completion without an intervening ``await``,+ so on asyncio's single thread no other coroutine can observe a+ half-applied change.+ """++ def __init__(self, prewarm: PrewarmConfig | None = None) -> None:+ """Size the buffer and the build concurrency.++ Args:+ prewarm (`PrewarmConfig | None`, optional):+ Buffer settings. ``None`` disables pre-warming.+ """+ self._prewarm = prewarm or PrewarmConfig()+ self._slots: deque[asyncio.Future] = deque()+ self._prewarm_tasks: set[asyncio.Task] = set()+ self._creating = asyncio.Semaphore(self._prewarm.max_creating)+ # Built but not yet handed to the manager's cache. Whatever is+ # still here at shutdown — never taken, or taken by a caller+ # that was cancelled mid-await — would otherwise leak.+ self._built: set[T] = set()++ # ── subclass hooks ────────────────────────────────────────────++ async def _create_prewarmed(self) -> T:+ """Build one initialised workspace bound to no user.++ Every input must be manager-level configuration — a buffered+ workspace is built before anyone knows who will get it.+ """+ raise NotImplementedError++ async def _adopt_prewarmed(self, workspace: T) -> None:+ """Track a handed-out workspace as if built on demand.++ Called once, before the workspace's id is returned as a+ binding, so the manager's own cache can answer the+ ``get_workspace`` that follows.+ """+ raise NotImplementedError++ async def _dispose_prewarmed(self, workspace: T) -> None:+ """Discard a workspace nobody ever claimed.++ Its id was never persisted, so nothing will reattach to it and+ nothing else will reap it. Providers whose ``close`` preserves+ the sandbox for a later reattach — E2B pauses rather than+ kills — must override this to delete it outright.+ """+ await workspace.close()++ # ── lifecycle ─────────────────────────────────────────────────++ def _start_prewarm(self) -> None:+ """Fill the buffer. Returns at once; builds run in background."""+ self._refill()++ async def _stop_prewarm(self) -> None:+ """Drain the buffer, closing every workspace still unclaimed.++ In-flight builds are awaited rather than cancelled — a build+ killed halfway leaves an orphaned container or sandbox that+ nothing will ever reap.+ """+ self._prewarm = PrewarmConfig()+ if self._prewarm_tasks:+ await asyncio.gather(+ *self._prewarm_tasks,+ return_exceptions=True,+ )+ self._slots.clear()+ unclaimed, self._built = self._built, set()+ await asyncio.gather(+ *(self._dispose_prewarmed(ws) for ws in unclaimed),+ return_exceptions=True,+ )++ # ── buffer ────────────────────────────────────────────────────++ def _refill(self) -> None:+ """Top the buffer back up to :attr:`PrewarmConfig.size` slots."""+ while len(self._slots) < self._prewarm.size:+ future: asyncio.Future = asyncio.get_running_loop().create_future()+ self._slots.append(future)+ task = asyncio.create_task(self._fill_slot(future))+ self._prewarm_tasks.add(task)+ task.add_done_callback(self._prewarm_tasks.discard)++ async def _fill_slot(self, future: asyncio.Future) -> None:+ """Build one workspace and resolve ``future`` with it.++ Every path resolves the future — a slot left pending would hang+ its taker for good, so bookkeeping that could raise stays+ inside the guarded block.+ """+ try:+ async with self._creating:+ workspace = await self._create_prewarmed()+ self._built.add(workspace)+ except Exception as e:+ # Drop the slot rather than rebuild straight away, so a+ # provider that is down cannot spin a hot retry loop; the+ # next take refills. A slot already taken keeps its waiter,+ # who falls back to an ordinary id.+ if future in self._slots:+ # Unclaimed, and now unreachable — nobody will ever+ # retrieve an exception set here.+ self._slots.remove(future)+ future.cancel()+ elif not future.done():+ future.set_exception(e)+ logger.warning(+ "%s: pre-warm build failed: %s",+ type(self).__name__,+ e,+ )+ return+ if future.done(): # cancelled while building+ self._built.discard(workspace)+ await self._dispose_prewarmed(workspace)+ return+ future.set_result(workspace)++ async def _mint_workspace_id(self) -> str:+ """Hand out a buffered workspace and return its id.++ Falls through to the base — a plain fresh id naming a workspace+ still to be built — when pre-warming is off, when the buffer is+ starved because recent builds failed, or when the build behind+ this slot is the one that failed. A pre-warm failure must not+ take the session down with it: without pre-warming the session+ would simply have built its own workspace later.+ """+ if not self._prewarm.size:+ return await super()._mint_workspace_id()+ future = self._slots.popleft() if self._slots else None+ self._refill()+ if future is None:+ return await super()._mint_workspace_id()+ try:+ workspace = await future+ except Exception:+ # Only a failed build reaches the taker as an exception;+ # ``_fill_slot`` cancels unclaimed slots instead. So a+ # ``CancelledError`` here is the caller's own, and must+ # not be turned into a workspace nobody asked for.+ return await super()._mint_workspace_id()+ try:+ await self._adopt_prewarmed(workspace)+ except BaseException:+ # The cache never took it and the caller is gone, so+ # nothing is left holding it — reclaim it now rather than+ # waiting for shutdown.+ self._built.discard(workspace)+ await self._dispose_prewarmed(workspace)+ raise+ self._built.discard(workspace)+ return workspace.workspace_iddiff --git a/tests/channel_worker_test.py b/tests/channel_worker_test.pyindex 3299e6628..22c936785 100644--- a/tests/channel_worker_test.py+++ b/tests/channel_worker_test.py@@ -28,6 +28,11 @@ class _TrackedContext:def __init__(self) -> None:self.entered = Falseself.exited = False+ self.storage: object = None++ def bind_storage(self, storage: object) -> None:+ """Record the storage the worker handed over."""+ self.storage = storageasync def __aenter__(self) -> "_TrackedContext":"""Record that the worker opened this backend."""diff --git a/tests/workspace_manager_applecontainer_test.py b/tests/workspace_manager_applecontainer_test.pyindex e9f5cd31d..4e750293c 100644--- a/tests/workspace_manager_applecontainer_test.py+++ b/tests/workspace_manager_applecontainer_test.py@@ -187,12 +187,12 @@ class TestAppleContainerWorkspaceManager(IsolatedAsyncioTestCase):manager = AppleContainerWorkspaceManager(isolation=IsolationPolicy.PER_AGENT,)- id1 = manager.assign_workspace_id(+ id1 = await manager.assign_workspace_id(user_id="u1",agent_id="a1",session_id="s1",)- id2 = manager.assign_workspace_id(+ id2 = await manager.assign_workspace_id(user_id="u1",agent_id="a1",session_id="s2",@@ -200,7 +200,7 @@ class TestAppleContainerWorkspaceManager(IsolatedAsyncioTestCase):# Same user+agent, different session → same id.self.assertEqual(id1, id2)- id3 = manager.assign_workspace_id(+ id3 = await manager.assign_workspace_id(user_id="u1",agent_id="a2",session_id="s1",@@ -213,12 +213,12 @@ class TestAppleContainerWorkspaceManager(IsolatedAsyncioTestCase):manager = AppleContainerWorkspaceManager(isolation=IsolationPolicy.PER_SESSION,)- id1 = manager.assign_workspace_id(+ id1 = await manager.assign_workspace_id(user_id="u1",agent_id="a1",session_id="s1",)- id2 = manager.assign_workspace_id(+ id2 = await manager.assign_workspace_id(user_id="u1",agent_id="a1",session_id="s2",diff --git a/tests/workspace_manager_daytona_test.py b/tests/workspace_manager_daytona_test.pyindex bdfe1d5f3..265397135 100644--- a/tests/workspace_manager_daytona_test.py+++ b/tests/workspace_manager_daytona_test.py@@ -120,7 +120,7 @@ class TestDaytonaWorkspaceManager(IsolatedAsyncioTestCase):self.assertEqual(len(_FakeWorkspace.created), 1)self.assertEqual(first.kwargs["workspace_id"],- manager.assign_workspace_id(+ await manager.assign_workspace_id(user_id="u",agent_id="a1",session_id="",diff --git a/tests/workspace_manager_docker_test.py b/tests/workspace_manager_docker_test.pynew file mode 100644index 000000000..9cd8cf6df--- /dev/null+++ b/tests/workspace_manager_docker_test.py@@ -0,0 +1,186 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Test cases for :class:`DockerWorkspaceManager`."""++import asyncio+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patch++from agentscope.app.workspace_manager import (+ PrewarmConfig,+ DockerWorkspaceManager,+ IsolationPolicy,+)+++class _FakeWorkspace:+ """Workspace double used by manager tests."""++ created: list["_FakeWorkspace"] = []++ def __init__(self, **kwargs: object) -> None:+ self.kwargs = kwargs+ self.workspace_id = str(kwargs.get("workspace_id") or "new-id")+ self.closed = False+ _FakeWorkspace.created.append(self)++ async def initialize(self) -> None:+ """Yield once so builds can interleave."""+ await asyncio.sleep(0)++ async def close(self) -> None:+ """Mark closed."""+ self.closed = True+++class TestDockerWorkspaceManager(IsolatedAsyncioTestCase):+ """Workdir layout and the pre-warm hand-off."""++ async def asyncSetUp(self) -> None:+ """Patch the workspace class and give the manager a basedir."""+ _FakeWorkspace.created.clear()+ self.workspace_patch = patch(+ "agentscope.app.workspace_manager."+ "_docker_workspace_manager.DockerWorkspace",+ _FakeWorkspace,+ )+ self.workspace_patch.start()+ # realpath: on macOS the temp dir is reached through a symlink,+ # while the manager containment check resolves it.+ self.basedir = os.path.realpath(tempfile.mkdtemp())++ async def asyncTearDown(self) -> None:+ """Undo patches."""+ self.workspace_patch.stop()++ async def test_workdir_is_keyed_by_workspace_id(self) -> None:+ """The bind-mounted host dir is named after the workspace id."""+ manager = DockerWorkspaceManager(self.basedir)++ ws = await manager.get_workspace("u1", "a1", "s1", "fixed-id")++ self.assertDictEqual(+ ws.kwargs,+ {+ "workspace_id": "fixed-id",+ "host_workdir": os.path.join(self.basedir, "fixed-id"),+ "base_image": "python:3.11-slim",+ "node_version": "20",+ "extra_pip": [],+ "gateway_port": 5600,+ "env": {},+ "default_mcps": [],+ "skill_paths": [],+ },+ )+ self.assertTrue(os.path.isdir(os.path.join(self.basedir, "fixed-id")))++ async def test_workspace_id_cannot_escape_the_basedir(self) -> None:+ """A caller-supplied id may not point the bind-mount outside."""+ manager = DockerWorkspaceManager(self.basedir)++ for workspace_id in ("../../etc", "/etc", "a/../../../etc"):+ with self.assertRaises(ValueError):+ manager._workdir_for(workspace_id)++ async def test_legacy_workdir_is_kept_mounted(self) -> None:+ """A pre-existing <basedir>/<user>/<agent> keeps being used."""+ legacy = os.path.join(self.basedir, "u1", "a1")+ os.makedirs(legacy)+ manager = DockerWorkspaceManager(self.basedir)++ ws = await manager.get_workspace("u1", "a1", "s1", "fixed-id")++ self.assertDictEqual(+ ws.kwargs,+ {+ "workspace_id": "fixed-id",+ "host_workdir": legacy,+ "base_image": "python:3.11-slim",+ "node_version": "20",+ "extra_pip": [],+ "gateway_port": 5600,+ "env": {},+ "default_mcps": [],+ "skill_paths": [],+ },+ )++ async def test_the_id_keyed_workdir_wins_once_it_exists(self) -> None:+ """With both layouts on disk, the workspace id names the mount."""+ os.makedirs(os.path.join(self.basedir, "u1", "a1"))+ os.makedirs(os.path.join(self.basedir, "fixed-id"))+ manager = DockerWorkspaceManager(self.basedir)++ ws = await manager.get_workspace("u1", "a1", "s1", "fixed-id")++ self.assertEqual(+ ws.kwargs["host_workdir"],+ os.path.join(self.basedir, "fixed-id"),+ )++ async def test_prewarmed_container_never_takes_a_legacy_workdir(+ self,+ ) -> None:+ """A container built for nobody cannot adopt anyone's files."""+ os.makedirs(os.path.join(self.basedir, "u1", "a1"))+ manager = DockerWorkspaceManager(+ self.basedir,+ isolation=IsolationPolicy.PER_SESSION,+ prewarm=PrewarmConfig(size=1),+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ prewarmed = _FakeWorkspace.created[0]++ self.assertEqual(+ prewarmed.kwargs["host_workdir"],+ os.path.join(self.basedir, prewarmed.workspace_id),+ )+ await manager._stop_prewarm()++ async def test_prewarmed_container_is_handed_over_without_rebuild(+ self,+ ) -> None:+ """The buffered workspace's id becomes the session binding, and+ ``get_workspace`` then answers from the cache."""+ manager = DockerWorkspaceManager(+ self.basedir,+ isolation=IsolationPolicy.PER_SESSION,+ prewarm=PrewarmConfig(size=1),+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ self.assertEqual(len(_FakeWorkspace.created), 1)+ prewarmed = _FakeWorkspace.created[0]++ workspace_id = await manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )+ ws = await manager.get_workspace("u1", "a1", "s1", workspace_id)++ self.assertEqual(workspace_id, prewarmed.workspace_id)+ self.assertIs(ws, prewarmed)+ # One replacement build, and nothing built for the request itself.+ await asyncio.sleep(0.05)+ self.assertEqual(len(_FakeWorkspace.created), 2)++ async def test_aexit_closes_buffered_and_cached_workspaces(self) -> None:+ """Neither the buffer nor the cache survives shutdown."""+ manager = DockerWorkspaceManager(+ self.basedir,+ prewarm=PrewarmConfig(size=2),+ )+ async with manager:+ await asyncio.sleep(0.05)+ await manager.get_workspace("u1", "a1", "s1", "cached-id")+ self.assertEqual(len(_FakeWorkspace.created), 3)++ self.assertListEqual(+ [ws.closed for ws in _FakeWorkspace.created],+ [True, True, True],+ )diff --git a/tests/workspace_manager_e2b_test.py b/tests/workspace_manager_e2b_test.pynew file mode 100644index 000000000..538ec896b--- /dev/null+++ b/tests/workspace_manager_e2b_test.py@@ -0,0 +1,160 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Test cases for :class:`E2BWorkspaceManager` pre-warming."""++import asyncio+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patch++from agentscope.app.workspace_manager import (+ E2BWorkspaceManager,+ IsolationPolicy,+ PrewarmConfig,+)+++class _FakeSandbox:+ """E2B sandbox double recording pause / kill."""++ def __init__(self) -> None:+ """Start alive and unpaused."""+ self.killed = False+ self.paused = False++ async def kill(self) -> None:+ """Record a permanent delete."""+ self.killed = True++ async def pause(self) -> None:+ """Record a snapshot-preserving pause."""+ self.paused = True+++class _FakeWorkspace:+ """Workspace double whose ``close`` pauses, as E2B's does."""++ created: list["_FakeWorkspace"] = []+ fail_initialize = False++ def __init__(self, **kwargs: object) -> None:+ self.kwargs = kwargs+ self.workspace_id = str(kwargs.get("workspace_id") or "new-id")+ self._sandbox = _FakeSandbox()+ # Stable handle: the manager clears ``_sandbox`` once killed.+ self.sandbox = self._sandbox+ _FakeWorkspace.created.append(self)++ async def initialize(self) -> None:+ """Yield once so builds can interleave."""+ await asyncio.sleep(0)+ if _FakeWorkspace.fail_initialize:+ raise RuntimeError("gateway bootstrap failed")++ async def close(self) -> None:+ """Pause the sandbox — never kill it."""+ if self._sandbox is not None:+ await self._sandbox.pause()+++class TestE2BWorkspaceManagerPrewarm(IsolatedAsyncioTestCase):+ """Hand-off from the buffer and disposal of unclaimed sandboxes."""++ async def asyncSetUp(self) -> None:+ """Patch the workspace class used by the manager."""+ _FakeWorkspace.created.clear()+ _FakeWorkspace.fail_initialize = False+ self.workspace_patch = patch(+ "agentscope.app.workspace_manager."+ "_e2b_workspace_manager.E2BWorkspace",+ _FakeWorkspace,+ )+ self.workspace_patch.start()++ async def asyncTearDown(self) -> None:+ """Undo patches."""+ self.workspace_patch.stop()++ async def test_prewarmed_sandbox_is_handed_over_without_rebuild(+ self,+ ) -> None:+ """The buffered sandbox's id becomes the binding, and+ ``get_workspace`` then answers from the cache."""+ manager = E2BWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ prewarm=PrewarmConfig(size=1),+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ prewarmed = _FakeWorkspace.created[0]++ workspace_id = await manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )+ ws = await manager.get_workspace("u1", "a1", "s1", workspace_id)+ await asyncio.sleep(0.05)++ self.assertEqual(workspace_id, prewarmed.workspace_id)+ self.assertIs(ws, prewarmed)+ self.assertFalse(prewarmed.sandbox.killed)+ # One replacement build, nothing built for the request itself.+ self.assertEqual(len(_FakeWorkspace.created), 2)++ async def test_unclaimed_sandbox_is_killed_not_paused(self) -> None:+ """Shutdown deletes buffered sandboxes outright — a paused one+ is stranded, since its id was never persisted."""+ manager = E2BWorkspaceManager(prewarm=PrewarmConfig(size=2))+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ self.assertEqual(len(_FakeWorkspace.created), 2)++ await manager._stop_prewarm()++ self.assertListEqual(+ [ws.sandbox.killed for ws in _FakeWorkspace.created],+ [True, True],+ )++ async def test_claimed_sandbox_is_only_paused_on_close(self) -> None:+ """A sandbox handed to a session keeps the reattachable path."""+ manager = E2BWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ prewarm=PrewarmConfig(size=1),+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ claimed = _FakeWorkspace.created[0]+ workspace_id = await manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )++ await manager.close(workspace_id)++ self.assertFalse(claimed.sandbox.killed)+ self.assertTrue(claimed.sandbox.paused)++ async def test_a_kill_is_not_followed_by_a_pause(self) -> None:+ """Pausing a sandbox that was just killed is a wasted remote+ call that logs a failure on every shutdown."""+ manager = E2BWorkspaceManager(prewarm=PrewarmConfig(size=1))+ manager._start_prewarm()+ await asyncio.sleep(0.05)++ await manager._stop_prewarm()++ sandbox = _FakeWorkspace.created[0].sandbox+ self.assertListEqual([sandbox.killed, sandbox.paused], [True, False])++ async def test_a_half_built_sandbox_is_killed(self) -> None:+ """``initialize`` can fail after the remote sandbox exists, and+ nothing else holds it."""+ _FakeWorkspace.fail_initialize = True+ manager = E2BWorkspaceManager(prewarm=PrewarmConfig(size=1))+ manager._start_prewarm()+ await asyncio.sleep(0.05)++ self.assertEqual(len(_FakeWorkspace.created), 1)+ self.assertTrue(_FakeWorkspace.created[0].sandbox.killed)diff --git a/tests/workspace_prewarm_test.py b/tests/workspace_prewarm_test.pynew file mode 100644index 000000000..1ee0147d3--- /dev/null+++ b/tests/workspace_prewarm_test.py@@ -0,0 +1,357 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Test cases for :class:`WorkspacePrewarmMixin`."""++import asyncio+from types import SimpleNamespace+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.app.workspace_manager._base import (+ IsolationPolicy,+ WorkspaceManagerBase,+)+from agentscope.app.workspace_manager._prewarm import (+ PrewarmConfig,+ WorkspacePrewarmMixin,+)+++class _Workspace:+ """Workspace double. A plain class, so it stays hashable."""++ def __init__(self, workspace_id: str, alive: list[str]) -> None:+ """Track this double in the manager's ``built`` list."""+ self.workspace_id = workspace_id+ self._alive = alive++ async def close(self) -> None:+ """Drop the double from the manager's ``built`` list."""+ self._alive.remove(self.workspace_id)+++class _Manager(WorkspacePrewarmMixin, WorkspaceManagerBase):+ """Minimal manager exercising only the pre-warm buffer."""++ def __init__(+ self,+ *,+ prewarm: PrewarmConfig | None = None,+ isolation: IsolationPolicy = IsolationPolicy.PER_SESSION,+ build_delay: float = 0.0,+ fail_builds: int = 0,+ ) -> None:+ """Bind the buffer, the isolation policy and the build script."""+ self.build_delay = build_delay+ self.fail_builds = fail_builds+ self.built: list[str] = []+ self.adopted: list[str] = []+ self.concurrent = 0+ self.peak_concurrent = 0+ WorkspacePrewarmMixin.__init__(self, prewarm=prewarm)+ WorkspaceManagerBase.__init__(self, isolation=isolation)++ async def _create_prewarmed(self) -> _Workspace:+ """Build a workspace double, tracking build concurrency."""+ self.concurrent += 1+ self.peak_concurrent = max(self.peak_concurrent, self.concurrent)+ try:+ await asyncio.sleep(self.build_delay)+ if self.fail_builds > 0:+ self.fail_builds -= 1+ raise RuntimeError("provider down")+ workspace_id = f"ws-{len(self.built)}"+ self.built.append(workspace_id)+ return _Workspace(workspace_id, self.built)+ finally:+ self.concurrent -= 1++ async def _adopt_prewarmed(self, workspace: object) -> None:+ """Record the hand-off."""+ self.adopted.append(workspace.workspace_id)++ async def get_workspace(self, *args: object, **kwargs: object) -> object:+ """Unused by these tests."""++ async def close(self, workspace_id: str) -> None:+ """Unused by these tests."""++ async def close_all(self) -> None:+ """Unused by these tests."""+++class TestWorkspacePrewarm(IsolatedAsyncioTestCase):+ """Buffer filling, hand-off, burst behaviour and shutdown."""++ async def test_disabled_by_default(self) -> None:+ """``prewarm=0`` builds nothing and mints a plain id."""+ manager = _Manager()+ manager._start_prewarm()+ await asyncio.sleep(0)++ workspace_id = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ )++ self.assertListEqual(manager.built, [])+ self.assertListEqual(manager.adopted, [])+ self.assertNotIn(workspace_id, ("", None))++ async def test_buffer_fills_and_hands_out_prebuilt(self) -> None:+ """A ready slot is handed out and immediately replaced."""+ manager = _Manager(prewarm=PrewarmConfig(size=2))+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ self.assertListEqual(manager.built, ["ws-0", "ws-1"])++ workspace_id = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ )+ await asyncio.sleep(0.05)++ self.assertEqual(workspace_id, "ws-0")+ self.assertListEqual(manager.adopted, ["ws-0"])+ self.assertListEqual(manager.built, ["ws-0", "ws-1", "ws-2"])+ self.assertEqual(len(manager._slots), 2)++ async def test_burst_waits_on_in_flight_builds(self) -> None:+ """Every request is served from the buffer, bounded by+ ``max_creating``, and no request starts a build of its own."""+ manager = _Manager(+ prewarm=PrewarmConfig(size=2, max_creating=3),+ build_delay=0.05,+ )+ manager._start_prewarm()+ await asyncio.sleep(0.2)++ ids = list(+ await asyncio.gather(+ *(+ manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id=f"s{i}",+ )+ for i in range(10)+ ),+ ),+ )++ self.assertListEqual(+ sorted(ids),+ [+ "ws-0",+ "ws-1",+ "ws-2",+ "ws-3",+ "ws-4",+ "ws-5",+ "ws-6",+ "ws-7",+ "ws-8",+ "ws-9",+ ],+ )+ self.assertListEqual(manager.adopted, ids)+ self.assertLessEqual(manager.peak_concurrent, 3)++ async def test_failed_build_falls_back_to_plain_id(self) -> None:+ """A starved buffer mints an ordinary id instead of raising."""+ manager = _Manager(prewarm=PrewarmConfig(size=1), fail_builds=5)+ manager._start_prewarm()+ await asyncio.sleep(0.05)++ workspace_id = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ )++ self.assertListEqual(manager.built, [])+ self.assertListEqual(manager.adopted, [])+ self.assertNotIn(workspace_id, ("", None))++ async def test_waiter_survives_a_build_that_fails_under_it(+ self,+ ) -> None:+ """A slot that fails while someone waits on it resolves rather+ than hanging, and the waiter falls back to an ordinary id."""+ manager = _Manager(+ prewarm=PrewarmConfig(size=1),+ build_delay=0.05,+ fail_builds=5,+ )+ manager._start_prewarm()++ workspace_id = await asyncio.wait_for(+ manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ ),+ timeout=2,+ )++ self.assertListEqual(manager.built, [])+ self.assertListEqual(manager.adopted, [])+ self.assertNotIn(workspace_id, ("", None))++ async def test_stop_closes_buffered_workspaces(self) -> None:+ """Shutdown drains the buffer instead of leaking sandboxes."""+ manager = _Manager(prewarm=PrewarmConfig(size=3))+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ self.assertListEqual(manager.built, ["ws-0", "ws-1", "ws-2"])++ await manager._stop_prewarm()++ self.assertListEqual(manager.built, [])+ self.assertEqual(len(manager._slots), 0)++ async def test_per_agent_reuses_the_bound_workspace(self) -> None:+ """A returning ``(user, agent)`` gets its recorded binding back,+ and only a first-time pair draws from the buffer."""+ manager = _Manager(+ prewarm=PrewarmConfig(size=1),+ isolation=IsolationPolicy.PER_AGENT,+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)++ manager.bind_storage(+ SimpleNamespace(+ list_sessions=self._sessions_returning("bound-ws"),+ ),+ )+ returning = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s2",+ )+ manager.bind_storage(+ SimpleNamespace(list_sessions=self._sessions_returning()),+ )+ first_time = await manager.assign_workspace_id(+ user_id="u",+ agent_id="b",+ session_id="s1",+ )++ self.assertEqual(returning, "bound-ws")+ self.assertEqual(first_time, "ws-0")+ self.assertListEqual(manager.adopted, ["ws-0"])++ async def test_caller_cancellation_is_not_swallowed(self) -> None:+ """Cancelling a request that waits on a build must cancel it,+ not hand back a workspace nobody is there to receive."""+ manager = _Manager(prewarm=PrewarmConfig(size=1), build_delay=0.2)+ manager._start_prewarm()+ task = asyncio.create_task(+ manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ ),+ )+ await asyncio.sleep(0.05)+ task.cancel()++ with self.assertRaises(asyncio.CancelledError):+ await task++ async def test_a_minted_id_is_held_until_storage_has_it(self) -> None:+ """The session flow persists the binding after this returns, so+ a second request in that window must not mint its own."""+ manager = _Manager(+ prewarm=PrewarmConfig(size=2),+ isolation=IsolationPolicy.PER_AGENT,+ )+ manager._start_prewarm()+ await asyncio.sleep(0.05)+ manager.bind_storage(+ SimpleNamespace(list_sessions=self._sessions_returning()),+ )++ first = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s1",+ )+ second = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s2",+ )++ self.assertListEqual([first, second], ["ws-0", "ws-0"])+ self.assertListEqual(manager.adopted, ["ws-0"])++ async def test_concurrent_first_sessions_bind_one_workspace(+ self,+ ) -> None:+ """Two first sessions racing on one ``(user, agent)`` must not+ each mint a workspace."""+ manager = _Manager(+ prewarm=PrewarmConfig(size=2),+ build_delay=0.05,+ isolation=IsolationPolicy.PER_AGENT,+ )+ manager._start_prewarm()+ await asyncio.sleep(0.2)+ bound: list[str] = []+ manager.bind_storage(+ SimpleNamespace(list_sessions=self._sessions_from(bound)),+ )++ async def create_session() -> str:+ workspace_id = await manager.assign_workspace_id(+ user_id="u",+ agent_id="a",+ session_id="s",+ )+ bound.append(workspace_id)+ return workspace_id++ ids = list(await asyncio.gather(create_session(), create_session()))++ self.assertListEqual(ids, ["ws-0", "ws-0"])+ self.assertListEqual(manager.adopted, ["ws-0"])++ @staticmethod+ def _sessions_from(bound: list[str]) -> object:+ """Build a ``list_sessions`` double reading a live binding list."""++ async def list_sessions(+ user_id: str,+ agent_id: str,+ ) -> list[SimpleNamespace]:+ del user_id, agent_id+ return [+ SimpleNamespace(+ config=SimpleNamespace(workspace_id=workspace_id),+ )+ for workspace_id in bound+ ]++ return list_sessions++ @staticmethod+ def _sessions_returning(*workspace_ids: str) -> object:+ """Build a ``list_sessions`` double yielding those bindings."""++ async def list_sessions(+ user_id: str,+ agent_id: str,+ ) -> list[SimpleNamespace]:+ del user_id, agent_id+ return [+ SimpleNamespace(+ config=SimpleNamespace(workspace_id=workspace_id),+ )+ for workspace_id in workspace_ids+ ]++ return list_sessions