Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(scheduler): let one node own the timers (#2477)
DavdGaobb7c85e8d4f0
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex 9a7216abc..4b4d5ea03 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -88,6 +88,7 @@ def create_app(skill_hubs: list[SkillHubBase] | None = None,*,enable_channel_worker: bool = True,+ enable_scheduler: bool = True,extra_credentials: list[Type[CredentialBase]] | None = None,extra_middlewares: list[FastAPIMiddleware] | None = None,extra_agent_middlewares: AgentMiddlewareFactory | None = None,@@ -199,6 +200,13 @@ def create_app(connections or duplicate messages. The channel API, theclient factory and webhook delivery stay available eitherway — only the connections move.+ enable_scheduler (`bool`, defaults to ``True``):+ Whether this process owns the schedule timers. APScheduler's+ jobstore is in-memory, so every process holding them fires+ every cron tick and a schedule runs once per replica — set+ ``False`` on all but one. The schedule API and the agent's+ schedule tools stay available either way; those processes+ persist the record and notify the owner over the bus.extra_credentials (`list[Type[CredentialBase]] | None`, optional):Additional :class:`~agentscope.credential.CredentialBase`subclasses to register before the app starts. Equivalent to@@ -359,6 +367,7 @@ def create_app(enable_index_worker and knowledge_base_manager is not None)app.state.enable_channel_worker = enable_channel_worker+ app.state.enable_scheduler = enable_scheduler# Validate custom sub-agent templates for duplicate types and store in# app.statediff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex 6623f1471..94023df8b 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -50,6 +50,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:blob_store = app.state.blob_storeenable_index_worker = app.state.enable_index_workerenable_channel_worker = app.state.enable_channel_worker+ enable_scheduler = app.state.enable_schedulerresource_access_policy = app.state.resource_access_policyasync with AsyncExitStack() as stack:@@ -91,6 +92,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:storage=storage,message_bus=message_bus,workspace_manager=workspace_manager,+ enabled=enable_scheduler,),)app.state.scheduler_manager = schedulerdiff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.pyindex f22a68fca..8962b6a47 100644--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py@@ -1,7 +1,9 @@# -*- coding: utf-8 -*-"""The cron scheduler manager class."""+import asyncioimport jsonfrom collections.abc import Callable, Coroutine+from datetime import datetimefrom typing import Self@@ -12,7 +14,7 @@ from ....tool import ToolBasefrom ...._logging import loggerfrom ...._utils._common import _generate_idfrom ._tools import ScheduleCreate, ScheduleDelete, ScheduleList, ScheduleView-from ...message_bus import MessageBus+from ...message_bus import MessageBus, MessageBusKeysfrom ...workspace_manager import WorkspaceManagerBasefrom ..._bus_ops import deliver_to_inboxfrom ...storage import (@@ -35,13 +37,27 @@ class SchedulerManager::class:`WakeupDispatcher` (running on any process) picks up the work.This keeps the scheduler decoupled from ``ChatService`` and makes thefire path consistent with team / background-tool result delivery.++ The timers themselves are held by **one** node — APScheduler's+ jobstore is in-memory, so every node holding them fires every cron+ tick, and a schedule runs once per replica. Which node owns them is+ a deployment choice (``create_app(enable_scheduler=...)``), so+ writers cannot register a job in-process: they persist the record+ and call :meth:`notify_changed`, and the owner reconciles its jobs+ against storage. Storage is the source of truth; the notification+ only makes the owner look sooner than its periodic reconcile would."""+ RECONCILE_INTERVAL_SECS = 60+ """How often the owner re-reads storage regardless of+ notifications, so a dropped one costs at most one interval."""+def __init__(self,storage: StorageBase,message_bus: MessageBus,workspace_manager: WorkspaceManagerBase,+ enabled: bool = True,) -> None:"""Initialize the scheduler manager.@@ -56,42 +72,71 @@ class SchedulerManager:workspace_manager (`WorkspaceManagerBase`):Binds a workspace to the sessions this manager creates,under the application's isolation policy.+ enabled (`bool`, defaults to ``True``):+ Whether this node owns the timers. Exactly one node in a+ deployment should enable them; the rest still create,+ edit and delete schedules — they just do not fire them."""from apscheduler.schedulers.asyncio import AsyncIOSchedulerself._storage = storageself._message_bus = message_busself._workspace_manager = workspace_manager+ self._enabled = enabledself._scheduler = AsyncIOScheduler()+ # ``updated_at`` of each registered job, so a reconcile can tell+ # an edited schedule from an unchanged one.+ self._versions: dict[str, datetime] = {}+ self._tasks: list[asyncio.Task] = []# ------------------------------------------------------------------# Lifecycle# ------------------------------------------------------------------async def __aenter__(self) -> Self:- """Start APScheduler and re-register persisted schedules.+ """Take ownership of the timers, unless this node is disabled.- Reading all schedules from storage and restoring them is the- only thing a caller would ever do right after starting this- manager, so the work lives inside the context entry — the- lifespan does not need to remember to call :meth:`restore`.+ A disabled manager holds no jobs and runs no loops; it stays+ usable for :meth:`notify_changed` and :meth:`list_tools`, which+ every node needs.Returns:`Self`: This manager instance."""+ if not self._enabled:+ logger.info(+ "SchedulerManager disabled on this node; schedules are "+ "owned elsewhere.",+ )+ return self+logger.info("SchedulerManager starting APScheduler")self._scheduler.start()+ # Subscribe before the first reconcile, and wait for it: a+ # notification published in between would otherwise be lost, and+ # the schedule behind it would wait for the periodic pass.+ ready = asyncio.Event()+ self._tasks = [+ asyncio.create_task(+ self._listen(ready),+ name="schedule-lifecycle",+ ),+ asyncio.create_task(self._periodic(), name="schedule-reconcile"),+ ]+ await ready.wait()+ await self.reconcile()logger.info("SchedulerManager APScheduler started")-- records = await self._storage.list_all_schedules()- if records:- await self.restore(records)-return selfasync def __aexit__(self, *exc: object) -> None:- """Shut down the underlying APScheduler on context exit."""+ """Stop the loops and shut down APScheduler, if it was started."""+ if not self._enabled:+ return+logger.info("SchedulerManager shutting down APScheduler")+ for task in self._tasks:+ task.cancel()+ await asyncio.gather(*self._tasks, return_exceptions=True)self._scheduler.shutdown()logger.info("SchedulerManager APScheduler shut down")@@ -281,20 +326,104 @@ class SchedulerManager:# Schedule management# ------------------------------------------------------------------- async def register_schedule(self, record: ScheduleRecord) -> str:- """Persist-and-register a schedule record with APScheduler.+ async def notify_changed(self, schedule_id: str) -> None:+ """Tell the timer-owning node that a schedule was written.- Builds the trigger coroutine via :meth:`_build_trigger` and adds the- job to APScheduler. This is the single entry point used by both the- HTTP API and the :class:`ScheduleCreate` agent tool.+ Call after persisting a create / update / delete. Best-effort:+ reconcile re-reads storage, so the payload is only a nudge and a+ lost notification costs at most one reconcile interval.Args:- record (`ScheduleRecord`):- The fully-populated record (already persisted to storage).+ schedule_id (`str`):+ The changed schedule, for logging on the owner's side.+ """+ try:+ await self._message_bus.publish(+ MessageBusKeys.schedule_lifecycle(),+ {"schedule_id": schedule_id},+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "Failed to publish schedule change %s; the periodic "+ "reconcile will pick it up.",+ schedule_id,+ )- Returns:- `str`:- The APScheduler job ID (equal to ``record.id``).+ async def reconcile(self) -> None:+ """Drive the local job set to match the enabled records.++ Adds jobs that are missing, drops jobs whose record is gone or+ no longer enabled, and re-registers those whose ``updated_at``+ moved. Safe to call repeatedly — that is how a dropped+ notification heals.+ """+ try:+ records = await self._storage.list_all_schedules()+ except Exception: # pylint: disable=broad-except+ logger.exception("Schedule reconcile: failed to list schedules")+ return++ desired = {r.id: r for r in records if r.data.enabled}++ for schedule_id in set(self._versions) - set(desired):+ self._remove_job(schedule_id)++ for schedule_id, record in desired.items():+ if self._versions.get(schedule_id) == record.updated_at:+ continue+ if schedule_id in self._versions:+ self._remove_job(schedule_id)+ try:+ self._add_job(record)+ except Exception: # pylint: disable=broad-except+ # A record with an unparseable cron would otherwise take+ # every schedule after it down with it.+ logger.exception(+ "Schedule reconcile: cannot register %s",+ schedule_id,+ )++ # -- Loops --++ async def _listen(self, ready: asyncio.Event) -> None:+ """Reconcile on each lifecycle notification (reconnect on drop).++ Args:+ ready (`asyncio.Event`):+ Signalled once the SUBSCRIBE has landed, so+ :meth:`__aenter__` can order its first reconcile after+ it.+ """+ backoff = 1.0+ while True:+ try:+ async for _ in self._message_bus.subscribe(+ MessageBusKeys.schedule_lifecycle(),+ on_ready=ready.set,+ ):+ backoff = 1.0+ await self.reconcile()+ except asyncio.CancelledError: # pylint: disable=try-except-raise+ raise+ except Exception: # pylint: disable=broad-except+ logger.warning("schedule lifecycle subscription lost")+ await asyncio.sleep(backoff)+ backoff = min(backoff * 2, 30.0)++ async def _periodic(self) -> None:+ """Reconcile on a fixed interval, self-healing lost events."""+ while True:+ await asyncio.sleep(self.RECONCILE_INTERVAL_SECS)+ await self.reconcile()++ # -- Job set --++ def _add_job(self, record: ScheduleRecord) -> None:+ """Add one APScheduler job from its record.++ Args:+ record (`ScheduleRecord`):+ An enabled schedule record."""from apscheduler.triggers.cron import CronTrigger@@ -336,48 +465,33 @@ class SchedulerManager:name=record.data.name,misfire_grace_time=300,)+ self._versions[record.id] = record.updated_atlogger.info("Schedule %s(%s) registered, next_run=%s",record.id,record.data.name,job.next_run_time,)- return job.id- async def remove_schedule(self, job_id: str) -> None:- """Remove a job from APScheduler.+ def _remove_job(self, schedule_id: str) -> None:+ """Drop one APScheduler job.Args:- job_id (`str`):- The APScheduler job ID to remove.+ schedule_id (`str`):+ The schedule whose job should go; it doubles as the+ APScheduler job id."""from apscheduler.jobstores.base import JobLookupError- logger.info("Removing schedule job %s", job_id)+ self._versions.pop(schedule_id, None)try:- self._scheduler.remove_job(job_id)- logger.info("Schedule job %s removed", job_id)+ self._scheduler.remove_job(schedule_id)+ logger.info("Schedule job %s removed", schedule_id)except JobLookupError:- logger.warning("Schedule job %s not found in APScheduler", job_id)-- async def restore(self, records: list[ScheduleRecord]) -> None:- """Re-register persisted schedules on service startup.-- Only enabled schedules are restored.-- Args:- records (`list[ScheduleRecord]`):- All schedule records loaded from storage on startup.- """- enabled = [r for r in records if r.data.enabled]- logger.info(- "Restoring schedules: %d total, %d enabled",- len(records),- len(enabled),- )- for record in enabled:- await self.register_schedule(record)- logger.info("Schedule restore complete")+ logger.warning(+ "Schedule job %s not found in APScheduler",+ schedule_id,+ )async def list_tasks(self) -> list[dict]:"""Return a summary of all currently registered APScheduler jobs.diff --git a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.pyindex 36c773ff0..e5d81f856 100644--- a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py+++ b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py@@ -140,8 +140,9 @@ to complete the task independently.storage (`Any`):The storage backend used to persist the schedule record.scheduler_manager (`Any`):- The scheduler manager used to register the APScheduler job.- Must expose a ``register_schedule(record)`` coroutine.+ The scheduler manager, used to tell the timer-owning node+ that a schedule changed. Must expose a+ ``notify_changed(schedule_id)`` coroutine."""self._user_id = user_idself._agent_id = agent_id@@ -233,7 +234,7 @@ to complete the task independently.)await self._storage.upsert_schedule(self._user_id, record)- await self._scheduler_manager.register_schedule(record)+ await self._scheduler_manager.notify_changed(record.id)return ToolChunk(content=[diff --git a/src/agentscope/app/_router/_schedule.py b/src/agentscope/app/_router/_schedule.pyindex aab4a8123..b1295ca7a 100644--- a/src/agentscope/app/_router/_schedule.py+++ b/src/agentscope/app/_router/_schedule.py@@ -71,7 +71,7 @@ async def create_schedule(access: ResourceAccessService = Depends(get_resource_access_service),scheduler: SchedulerManager = Depends(get_scheduler_manager),) -> CreateScheduleResponse:- """Create a new schedule and register it with the scheduler.+ """Create a new schedule and hand it to the scheduler.The referenced agent may be either the viewer's own or one sharedto them through :class:`ResourceAccessPolicyBase`; the schedule@@ -121,9 +121,7 @@ async def create_schedule(),)await storage.upsert_schedule(user_id, record)-- if record.data.enabled:- await scheduler.register_schedule(record)+ await scheduler.notify_changed(record.id)return CreateScheduleResponse(schedule_id=record.id)@@ -143,9 +141,9 @@ async def update_schedule("""Partially update a schedule.Fields omitted from the request body keep their current values.- Changing ``cron_expression`` or ``timezone`` immediately reschedules the- APScheduler job. Setting ``enable=False`` removes the job from the- scheduler without deleting the record.+ Changing ``cron_expression`` or ``timezone`` reschedules the job, and+ ``enable=False`` stops it firing without deleting the record — both+ take effect once the timer-owning node reconciles.Args:schedule_id (`str`): ID of the schedule to update.@@ -174,11 +172,7 @@ async def update_schedule(update={"data": updated_data, "updated_at": datetime.now()},)await storage.upsert_schedule(user_id, updated_record)-- # Always remove the existing job first; re-register only if still enabled.- await scheduler.remove_schedule(schedule_id)- if updated_record.data.enabled:- await scheduler.register_schedule(updated_record)+ await scheduler.notify_changed(schedule_id)return updated_record@@ -197,8 +191,8 @@ async def delete_schedule("""Permanently delete a schedule.Cancels any in-flight chat run for sessions this schedule has- triggered, removes their records via the session service, and- finally unregisters the APScheduler job.+ triggered, removes their records via the session service, and tells+ the timer-owning node to drop the job.Args:schedule_id (`str`): ID of the schedule to delete.@@ -215,7 +209,7 @@ async def delete_schedule(status_code=status.HTTP_404_NOT_FOUND,detail=f"Schedule '{schedule_id}' not found.",)- await scheduler.remove_schedule(schedule_id)+ await scheduler.notify_changed(schedule_id)@schedule_router.get(diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pyindex 3c20e524e..ff7ebcefc 100644--- a/src/agentscope/app/message_bus/_keys.py+++ b/src/agentscope/app/message_bus/_keys.py@@ -287,6 +287,19 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods"""return cls._INDEX_TASKS_SIGNAL+ # ------------------------------------------------------------------+ # Schedules. Only the node that owns the timers reconciles them;+ # every node publishes here after writing a schedule to storage.+ # ------------------------------------------------------------------++ _SCHEDULE_LIFECYCLE = "agentscope:schedule:lifecycle"++ @classmethod+ def schedule_lifecycle(cls) -> str:+ """Pub/sub channel that nudges the timer-owning node to+ reconcile its schedule jobs against storage."""+ return cls._SCHEDULE_LIFECYCLE+# ------------------------------------------------------------------# Channels. A reply never travels through the bus: delivery is plain# REST, so the node running the agent sends it directly. What doesdiff --git a/tests/service_scheduler_test.py b/tests/service_scheduler_test.pyindex d0e6a24e7..f75dd1863 100644--- a/tests/service_scheduler_test.py+++ b/tests/service_scheduler_test.py@@ -1,6 +1,6 @@# -*- coding: utf-8 -*-# pylint: disable=protected-access-"""Tests for :meth:`SchedulerManager._build_trigger`.+"""Tests for :class:`SchedulerManager`'s trigger and job ownership.We don't drive APScheduler here — we ask the manager to build a triggercoroutine for a record and invoke it directly. The trigger's contract is:@@ -13,16 +13,24 @@ coroutine for a record and invoke it directly. The trigger's contract is:In stateful mode the session id is deterministic (``{record_id}_stateful``)and reused across fires; in non-stateful mode a fresh session id iscreated every fire.++The second half covers ownership: only an enabled node holds jobs, and+it learns about writes by reconciling against storage rather than by+being called in-process."""+import asyncioimport json+import tempfilefrom contextlib import AsyncExitStackfrom datetime import datetime-from unittest import IsolatedAsyncioTestCase+from unittest import IsolatedAsyncioTestCase, TestCaseimport fakeredis.aioredis+from fastapi.testclient import TestClientfrom utils import AnyString, FakeWorkspaceManager+from agentscope.app import create_appfrom agentscope.app._manager import SchedulerManagerfrom agentscope.app.message_bus import RedisMessageBusfrom agentscope.app.storage import (@@ -32,6 +40,7 @@ from agentscope.app.storage import (ScheduleRecord,SessionSource,)+from agentscope.app.workspace_manager import LocalWorkspaceManagerfrom agentscope.permission import PermissionMode@@ -306,3 +315,168 @@ class TestSchedulerFireWorkspaceBinding(_SchedulerFireTestBase):[s.config.workspace_id for s in sessions],["77377d7bd2f7a1fc", "77377d7bd2f7a1fc"],)+++class _SchedulerOwnershipTestBase(_SchedulerFireTestBase):+ """Adds job-set inspection to the shared fixture."""++ def job_ids(self, manager: SchedulerManager | None = None) -> list[str]:+ """Return the schedule ids this node currently holds timers for.++ Args:+ manager (`SchedulerManager | None`, optional):+ Which manager to inspect; defaults to the fixture's.++ Returns:+ `list[str]`: Sorted job ids.+ """+ scheduler = (manager or self.manager)._scheduler+ return sorted(job.id for job in scheduler.get_jobs())+++class TestSchedulerReconcile(_SchedulerOwnershipTestBase):+ """The owner's job set follows storage, not in-process calls."""++ async def test_reconcile_holds_enabled_records_only(self) -> None:+ """A disabled record is persisted but never given a timer."""+ live = _make_record()+ await self.storage.upsert_schedule("u", live)+ await self.storage.upsert_schedule("u", _make_record(enabled=False))++ await self.manager.reconcile()++ self.assertListEqual(self.job_ids(), [live.id])++ async def test_reconcile_drops_a_deleted_record(self) -> None:+ """Deleting the record takes the timer with it."""+ record = _make_record()+ await self.storage.upsert_schedule("u", record)+ await self.manager.reconcile()++ await self.storage.delete_schedule("u", record.id)+ await self.manager.reconcile()++ self.assertListEqual(self.job_ids(), [])++ async def test_reconcile_drops_a_disabled_record(self) -> None:+ """Disabling stops the firing without deleting the record."""+ record = _make_record()+ await self.storage.upsert_schedule("u", record)+ await self.manager.reconcile()++ record.data.enabled = False+ record.updated_at = datetime(2025, 6, 1)+ await self.storage.upsert_schedule("u", record)+ await self.manager.reconcile()++ self.assertListEqual(self.job_ids(), [])++ async def test_reconcile_reregisters_an_edited_record(self) -> None:+ """A changed ``updated_at`` replaces the job; an unchanged one+ leaves it alone."""+ record = _make_record()+ await self.storage.upsert_schedule("u", record)+ await self.manager.reconcile()+ first = self.manager._scheduler.get_job(record.id)++ await self.manager.reconcile()+ self.assertIs(self.manager._scheduler.get_job(record.id), first)++ record.data.cron_expression = "30 3 * * *"+ record.updated_at = datetime(2025, 6, 1)+ await self.storage.upsert_schedule("u", record)+ await self.manager.reconcile()++ self.assertListEqual(self.job_ids(), [record.id])+ self.assertIsNot(self.manager._scheduler.get_job(record.id), first)++ async def test_reconcile_survives_an_unparseable_cron(self) -> None:+ """One bad record must not cost every schedule after it."""+ broken = _make_record()+ broken.data.cron_expression = "not a cron"+ good = _make_record()+ await self.storage.upsert_schedule("u", broken)+ await self.storage.upsert_schedule("u", good)++ await self.manager.reconcile()++ self.assertListEqual(self.job_ids(), [good.id])+++class TestSchedulerOwnership(_SchedulerOwnershipTestBase):+ """Only the enabled node holds timers; every node can notify."""++ async def test_disabled_node_holds_no_timers(self) -> None:+ """Entering a disabled manager starts nothing, however many+ enabled schedules are persisted."""+ await self.storage.upsert_schedule("u", _make_record())++ disabled = SchedulerManager(+ storage=self.storage,+ message_bus=self.bus,+ workspace_manager=FakeWorkspaceManager(),+ enabled=False,+ )+ async with disabled:+ self.assertListEqual(self.job_ids(disabled), [])+ self.assertFalse(disabled._scheduler.running)++ async def test_a_write_on_one_node_reaches_the_owner(self) -> None:+ """The owner picks up a schedule written by another node, having+ never been called in-process."""+ owner = SchedulerManager(+ storage=self.storage,+ message_bus=self.bus,+ workspace_manager=FakeWorkspaceManager(),+ )+ async with owner:+ self.assertListEqual(self.job_ids(owner), [])++ record = _make_record()+ await self.storage.upsert_schedule("u", record)+ # ``self.manager`` stands in for an API node with no timers.+ await self.manager.notify_changed(record.id)++ for _ in range(50):+ await asyncio.sleep(0.02)+ if self.job_ids(owner):+ break+ self.assertListEqual(self.job_ids(owner), [record.id])+++class TestSchedulerFlag(TestCase):+ """``enable_scheduler`` decides whether a process owns the timers."""++ def _boot(self, enabled: bool) -> SchedulerManager:+ """Run an app's lifespan and hand back its scheduler manager.++ Args:+ enabled (`bool`): The ``enable_scheduler`` value to pass.++ Returns:+ `SchedulerManager`: The manager the lifespan built.+ """+ # pylint: disable=consider-using-with+ workdir = self.enterContext(tempfile.TemporaryDirectory())+ fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ app = create_app(+ storage=_make_storage(fr),+ message_bus=_make_bus(fr),+ workspace_manager=LocalWorkspaceManager(workdir),+ enable_index_worker=False,+ enable_scheduler=enabled,+ )+ self.enterContext(TestClient(app))+ return app.state.scheduler_manager++ def test_disabled_process_starts_no_scheduler(self) -> None:+ """The manager is still there for the API and the agent tools,+ it just runs nothing."""+ manager = self._boot(False)++ self.assertFalse(manager._scheduler.running)+ self.assertListEqual(list(manager._scheduler.get_jobs()), [])++ def test_enabled_process_starts_the_scheduler(self) -> None:+ """The default keeps a single-process deployment working."""+ self.assertTrue(self._boot(True)._scheduler.running)