Skip to content

Build and run agents you can see, understand and trust.

fix(scheduler): bind a real workspace to scheduled sessions (#2410)

DavdGao09a0071a72db
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index dc5f73e18..6623f1471 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -90,6 +90,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
SchedulerManager(
storage=storage,
message_bus=message_bus,
+ workspace_manager=workspace_manager,
),
)
app.state.scheduler_manager = scheduler
diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
index 68f8e5854..f22a68fca 100644
--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
@@ -10,8 +10,10 @@ from ....permission import PermissionContext
from ....state import AgentState
from ....tool import ToolBase
from ...._logging import logger
+from ...._utils._common import _generate_id
from ._tools import ScheduleCreate, ScheduleDelete, ScheduleList, ScheduleView
from ...message_bus import MessageBus
+from ...workspace_manager import WorkspaceManagerBase
from ..._bus_ops import deliver_to_inbox
from ...storage import (
StorageBase,
@@ -39,6 +41,7 @@ class SchedulerManager:
self,
storage: StorageBase,
message_bus: MessageBus,
+ workspace_manager: WorkspaceManagerBase,
) -> None:
"""Initialize the scheduler manager.
@@ -50,11 +53,15 @@ class SchedulerManager:
The application message bus. Each scheduled fire pushes
a :class:`HintBlock` to the target session's inbox and
enqueues a wakeup via this bus.
+ workspace_manager (`WorkspaceManagerBase`):
+ Binds a workspace to the sessions this manager creates,
+ under the application's isolation policy.
"""
from apscheduler.schedulers.asyncio import AsyncIOScheduler
self._storage = storage
self._message_bus = message_bus
+ self._workspace_manager = workspace_manager
self._scheduler = AsyncIOScheduler()
# ------------------------------------------------------------------
@@ -121,6 +128,7 @@ class SchedulerManager:
# re-look these up on every fire.
storage = self._storage
message_bus = self._message_bus
+ workspace_manager = self._workspace_manager
async def _trigger() -> None:
logger.info(
@@ -164,7 +172,13 @@ class SchedulerManager:
mode=record.data.permission_mode,
)
session_config = SessionConfig(
- workspace_id="",
+ workspace_id=(
+ await workspace_manager.assign_workspace_id(
+ user_id=record.user_id,
+ agent_id=record.agent_id,
+ session_id=stateful_session_id,
+ )
+ ),
chat_model_config=record.data.chat_model_config,
)
session = await storage.upsert_session(
@@ -199,7 +213,13 @@ class SchedulerManager:
user_id=record.user_id,
agent_id=record.agent_id,
config=SessionConfig(
- workspace_id="",
+ workspace_id=(
+ await workspace_manager.assign_workspace_id(
+ user_id=record.user_id,
+ agent_id=record.agent_id,
+ session_id=_generate_id(),
+ )
+ ),
chat_model_config=record.data.chat_model_config,
),
state=state,
diff --git a/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py
index 6987779d6..11c09901a 100644
--- a/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py
@@ -165,7 +165,7 @@ class AppleContainerWorkspaceManager(WorkspaceManagerBase):
not used here).
workspace_id (`str | None`, optional):
Stable workspace identifier — used as the cache key
- and container name suffix. When ``None`` the manager
+ and container name suffix. When unset the manager
falls back to :meth:`assign_workspace_id`.
Returns:
@@ -174,7 +174,7 @@ class AppleContainerWorkspaceManager(WorkspaceManagerBase):
"""
del session_id # accepted for interface parity; not used here
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_base.py b/src/agentscope/app/workspace_manager/_base.py
index a0b03693f..dcee5198b 100644
--- a/src/agentscope/app/workspace_manager/_base.py
+++ b/src/agentscope/app/workspace_manager/_base.py
@@ -178,9 +178,9 @@ class WorkspaceManagerBase(ABC):
session_id (`str`):
The session id.
workspace_id (`str | None`, optional):
- Explicit workspace binding. ``None`` triggers
- :meth:`assign_workspace_id` fallback — expected only
- for callers without a persisted binding.
+ Explicit workspace binding. An empty id or ``None``
+ triggers the :meth:`assign_workspace_id` fallback —
+ expected only for callers without a persisted binding.
"""
@abstractmethod
diff --git a/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py
index e6e34d406..d09f6583c 100644
--- a/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py
@@ -148,7 +148,7 @@ class BubblewrapWorkspaceManager(WorkspaceManagerBase):
workspace_id: str | None = None,
) -> BubblewrapWorkspace:
"""Return an initialized workspace, creating it on cache miss."""
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py
index 7049cba15..b25ed671d 100644
--- a/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py
@@ -198,7 +198,7 @@ class DaytonaWorkspaceManager(WorkspaceManagerBase):
Session identifier (unused; sessions partition under
``sessions/<session_id>/`` inside a workspace).
workspace_id (`str | None`, optional):
- Stable workspace identifier and cache key. When ``None``,
+ Stable workspace identifier and cache key. When unset,
the manager falls back to :meth:`assign_workspace_id`.
Returns:
@@ -207,7 +207,7 @@ class DaytonaWorkspaceManager(WorkspaceManagerBase):
"""
del session_id # accepted for interface parity; not used here
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py b/src/agentscope/app/workspace_manager/_docker_workspace_manager.py
index ed5784a0d..c0f9af04e 100644
--- a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_docker_workspace_manager.py
@@ -264,7 +264,7 @@ class DockerWorkspaceManager(
``sessions/<session_id>/``).
workspace_id (`str | None`, optional):
Stable workspace identifier — used both as the cache
- key and the container name suffix. When ``None`` the
+ key and the container name suffix. When unset the
manager falls back to :meth:`assign_workspace_id`;
the session flow should pre-resolve this so container
names stay stable across restarts.
@@ -275,7 +275,7 @@ class DockerWorkspaceManager(
"""
del session_id # accepted for interface parity; not used here
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py
index b3745867c..53122cfd8 100644
--- a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py
@@ -292,7 +292,7 @@ class E2BWorkspaceManager(
workspace_id (`str | None`, optional):
Stable workspace identifier — the cache key and the
value stored in the sandbox's
- ``agentscope.workspace.id`` metadata. When ``None``
+ ``agentscope.workspace.id`` metadata. When unset
the manager falls back to
:meth:`assign_workspace_id`.
@@ -302,7 +302,7 @@ class E2BWorkspaceManager(
"""
del session_id # accepted for interface parity; not used here
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py
index bdf550792..c8dcd8cc4 100644
--- a/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py
@@ -188,7 +188,7 @@ class K8sWorkspaceManager(WorkspaceManagerBase):
Session identifier (unused; Pods are per-workspace).
workspace_id (`str | None`, optional):
Stable workspace identifier — the cache key. When
- ``None`` the manager falls back to
+ unset the manager falls back to
:meth:`assign_workspace_id`.
Returns:
@@ -197,7 +197,7 @@ class K8sWorkspaceManager(WorkspaceManagerBase):
"""
del session_id
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/src/agentscope/app/workspace_manager/_local_workspace_manager.py b/src/agentscope/app/workspace_manager/_local_workspace_manager.py
index e5a7907e3..07ec50711 100644
--- a/src/agentscope/app/workspace_manager/_local_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_local_workspace_manager.py
@@ -85,11 +85,9 @@ class LocalWorkspaceManager(WorkspaceManagerBase):
cache misses for the same ``workspace_id`` cannot create two
workspaces.
"""
- del user_id # accepted for interface parity; not used here
-
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
- user_id="",
+ user_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.py
index f7f45e0f2..377d7ef00 100644
--- a/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py
+++ b/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py
@@ -167,8 +167,8 @@ class OpenSandboxWorkspaceManager(WorkspaceManagerBase):
"""Construct an OpenSandbox workspace and run full initialize.
``workspace_id`` is always concrete here — :meth:`get_workspace`
- resolves ``None`` via :meth:`assign_workspace_id` before calling
- — and is forwarded so metadata-based reattachment works on the
+ resolves an unset id via :meth:`assign_workspace_id` first —
+ and is forwarded so metadata-based reattachment works on the
next cache miss.
"""
ws = OpenSandboxWorkspace(
@@ -227,7 +227,7 @@ class OpenSandboxWorkspaceManager(WorkspaceManagerBase):
workspace_id (`str | None`, optional):
Stable workspace identifier — the cache key and the
value stored in the sandbox's ``agentscope.workspace.id``
- metadata. When ``None`` the manager falls back to
+ metadata. When unset the manager falls back to
:meth:`assign_workspace_id` under its isolation policy.
Returns:
@@ -236,7 +236,7 @@ class OpenSandboxWorkspaceManager(WorkspaceManagerBase):
"""
del session_id # accepted for interface parity; not used here
- if workspace_id is None:
+ if not workspace_id:
workspace_id = await self.assign_workspace_id(
user_id=user_id,
agent_id=agent_id,
diff --git a/tests/service_scheduler_test.py b/tests/service_scheduler_test.py
index de81a181f..d0e6a24e7 100644
--- a/tests/service_scheduler_test.py
+++ b/tests/service_scheduler_test.py
@@ -21,7 +21,7 @@ from unittest import IsolatedAsyncioTestCase
import fakeredis.aioredis
-from utils import AnyString
+from utils import AnyString, FakeWorkspaceManager
from agentscope.app._manager import SchedulerManager
from agentscope.app.message_bus import RedisMessageBus
@@ -115,6 +115,7 @@ class _SchedulerFireTestBase(IsolatedAsyncioTestCase):
self.manager = SchedulerManager(
storage=self.storage,
message_bus=self.bus,
+ workspace_manager=FakeWorkspaceManager(),
)
async def asyncTearDown(self) -> None:
@@ -267,3 +268,41 @@ class TestSchedulerFireNonStatefulMode(_SchedulerFireTestBase):
)
self.assertEqual(len(sessions), 2)
self.assertNotEqual(sessions[0].id, sessions[1].id)
+
+
+class TestSchedulerFireWorkspaceBinding(_SchedulerFireTestBase):
+ """A fired session binds a workspace under the isolation policy.
+
+ The ids below are the PER_AGENT BLAKE2b digests of ``<user>::a``.
+ """
+
+ async def test_two_users_do_not_share_one_workspace(self) -> None:
+ """Two users scheduling the same agent land on distinct
+ workspaces — an unbound session would pool them into one."""
+ await self.manager._build_trigger(_make_record(user_id="alice"))()
+ await self.manager._build_trigger(_make_record(user_id="bob"))()
+
+ self.assertListEqual(
+ [
+ *(
+ s.config.workspace_id
+ for s in await self.storage.list_sessions("alice", "a")
+ ),
+ *(
+ s.config.workspace_id
+ for s in await self.storage.list_sessions("bob", "a")
+ ),
+ ],
+ ["ca79105d522eba6f", "ecbe3dbe754c96ee"],
+ )
+
+ async def test_both_trigger_branches_bind_a_workspace(self) -> None:
+ """The stateful and the fresh-session branch both resolve an id."""
+ await self.manager._build_trigger(_make_record(stateful=True))()
+ await self.manager._build_trigger(_make_record(stateful=False))()
+
+ sessions = await self.storage.list_sessions("u", "a")
+ self.assertListEqual(
+ [s.config.workspace_id for s in sessions],
+ ["77377d7bd2f7a1fc", "77377d7bd2f7a1fc"],
+ )
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 6d0f41e3d..5ad3cd219 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -212,6 +212,7 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
scheduler_manager=SchedulerManager(
storage=_NoOpStorage(), # type: ignore[arg-type]
message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
),
background_task_manager=BackgroundTaskManager(
message_bus=_NullBus(), # type: ignore[arg-type]
@@ -271,6 +272,7 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
scheduler_manager=SchedulerManager(
storage=_NoOpStorage(), # type: ignore[arg-type]
message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
),
background_task_manager=BackgroundTaskManager(
message_bus=_NullBus(), # type: ignore[arg-type]
@@ -316,6 +318,7 @@ class TestGetToolkitSchedulingGuard(IsolatedAsyncioTestCase):
scheduler_manager=SchedulerManager(
storage=_NoOpStorage(), # type: ignore[arg-type]
message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
),
background_task_manager=BackgroundTaskManager(
message_bus=_NullBus(), # type: ignore[arg-type]
@@ -374,6 +377,7 @@ class TestGetToolkitExtraFactory(IsolatedAsyncioTestCase):
scheduler_manager=SchedulerManager(
storage=_NoOpStorage(), # type: ignore[arg-type]
message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
),
background_task_manager=BackgroundTaskManager(
message_bus=_NullBus(), # type: ignore[arg-type]
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
index 5b888e395..c5c08d484 100644
--- a/tests/workspace_daytona_test.py
+++ b/tests/workspace_daytona_test.py
@@ -1684,6 +1684,9 @@ class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
scheduler_manager=SchedulerManager(
storage=_NoOpStorage(), # type: ignore[arg-type]
message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=(
+ _NoOpWorkspaceManager() # type: ignore[arg-type]
+ ),
),
background_task_manager=BackgroundTaskManager(
message_bus=_NullBus(), # type: ignore[arg-type]
diff --git a/tests/workspace_manager_daytona_test.py b/tests/workspace_manager_daytona_test.py
index 265397135..0e7408e52 100644
--- a/tests/workspace_manager_daytona_test.py
+++ b/tests/workspace_manager_daytona_test.py
@@ -127,6 +127,21 @@ class TestDaytonaWorkspaceManager(IsolatedAsyncioTestCase):
),
)
+ async def test_an_empty_workspace_id_is_not_a_binding(self) -> None:
+ """Sessions persisted with ``workspace_id=""`` fall back to the
+ isolation policy instead of pooling every user into one
+ workspace keyed on the empty string."""
+ manager = DaytonaWorkspaceManager()
+
+ alice = await manager.get_workspace("alice", "a", "s", "")
+ bob = await manager.get_workspace("bob", "a", "s", "")
+
+ self.assertIsNot(alice, bob)
+ self.assertListEqual(
+ [alice.kwargs["workspace_id"], bob.kwargs["workspace_id"]],
+ ["ca79105d522eba6f", "ecbe3dbe754c96ee"],
+ )
+
async def test_concurrent_get_workspace_creates_one_instance(self) -> None:
"""Concurrent requests for one id share the initialized workspace."""
manager = DaytonaWorkspaceManager()
diff --git a/tests/workspace_manager_local_test.py b/tests/workspace_manager_local_test.py
new file mode 100644
index 000000000..4397405e8
--- /dev/null
+++ b/tests/workspace_manager_local_test.py
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+"""Test cases for :class:`LocalWorkspaceManager`."""
+
+from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
+
+from agentscope.app.workspace_manager import (
+ IsolationPolicy,
+ LocalWorkspaceManager,
+)
+
+
+class _FakeWorkspace:
+ """Workspace double used by manager tests."""
+
+ def __init__(self, **kwargs: object) -> None:
+ self.kwargs = kwargs
+ self.workspace_id = str(kwargs.get("workspace_id") or "new-id")
+
+ async def initialize(self) -> None:
+ """No-op — the manager only needs the object back."""
+
+ async def close(self) -> None:
+ """No-op."""
+
+
+class TestLocalWorkspaceManager(IsolatedAsyncioTestCase):
+ """The unbound-id fallback honours the isolation policy."""
+
+ async def asyncSetUp(self) -> None:
+ """Patch the workspace class used by the manager."""
+ self.workspace_patch = patch(
+ "agentscope.app.workspace_manager."
+ "_local_workspace_manager.LocalWorkspace",
+ _FakeWorkspace,
+ )
+ self.workspace_patch.start()
+
+ async def asyncTearDown(self) -> None:
+ """Undo patches."""
+ self.workspace_patch.stop()
+
+ async def test_an_empty_workspace_id_stays_per_user(self) -> None:
+ """Sessions persisted with ``workspace_id=""`` derive a binding
+ from their own user, not from a blank one — under ``PER_USER``
+ a blank owner would pool every user onto a single id."""
+ manager = LocalWorkspaceManager(
+ "/tmp/local-manager-test",
+ isolation=IsolationPolicy.PER_USER,
+ )
+
+ alice = await manager.get_workspace("alice", "a1", "s", "")
+ bob = await manager.get_workspace("bob", "a2", "s", "")
+
+ self.assertIsNot(alice, bob)
+ self.assertListEqual(
+ [alice.kwargs["workspace_id"], bob.kwargs["workspace_id"]],
+ ["982aa9b33217069a", "883053c3e4594c5b"],
+ )