Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(scheduler): validate cron before persistence (#2442)
red_sunde163b34b909
diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.pyindex 8962b6a47..8ff3639e7 100644--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py@@ -4,8 +4,9 @@ import asyncioimport jsonfrom collections.abc import Callable, Coroutinefrom datetime import datetime+from zoneinfo import ZoneInfoNotFoundError-from typing import Self+from typing import Self, TYPE_CHECKINGfrom ....message import HintBlockfrom ....permission import PermissionContext@@ -25,6 +26,9 @@ from ...storage import (SessionSource,)+if TYPE_CHECKING:+ from apscheduler.triggers.cron import CronTrigger+class SchedulerManager:"""The cron scheduler manager, responsible for managing scheduled-task@@ -326,6 +330,73 @@ class SchedulerManager:# Schedule management# ------------------------------------------------------------------+ @staticmethod+ def validate_schedule(record: ScheduleRecord) -> "CronTrigger":+ """Build the record's cron trigger, rejecting a bad schedule.++ Writers call this before persisting so an invalid schedule never+ reaches storage, and :meth:`_add_job` reuses what it returns+ rather than parsing the expression a second time.++ ``CronTrigger.from_crontab`` is not usable here: it forwards only+ the 5 parsed fields and ``timezone``, with no parameter for+ ``start_date`` / ``end_date``, so the configured activation+ window would be dropped.++ Args:+ record (`ScheduleRecord`):+ The schedule to check.++ Returns:+ `CronTrigger`:+ The trigger the job would fire on.++ Raises:+ `ValueError`:+ The cron expression, the timezone, or the activation+ window is invalid.+ """+ from apscheduler.triggers.cron import CronTrigger++ fields = record.data.cron_expression.split()+ if len(fields) != 5:+ raise ValueError(+ "Expected a 5-field cron expression, got "+ f"{record.data.cron_expression!r}",+ )+ minute, hour, day, month, day_of_week = fields++ if not record.data.timezone:+ # An empty one resolves to the server's local zone rather+ # than raising, which is not what the caller asked for.+ raise ValueError("timezone must be a non-empty IANA name")++ try:+ trigger = CronTrigger(+ minute=minute,+ hour=hour,+ day=day,+ month=month,+ day_of_week=day_of_week,+ timezone=record.data.timezone,+ start_date=record.data.started_at,+ end_date=record.data.ended_at,+ )+ except (ValueError, ZoneInfoNotFoundError) as exc:+ # Field ranges, expression syntax and the timezone are all+ # checked by the constructor.+ raise ValueError(str(exc)) from exc++ # The window is the one thing it does not check: an inverted one+ # is accepted and simply never fires.+ if (+ trigger.end_date is not None+ and trigger.end_date <= trigger.start_date+ ):+ raise ValueError("ended_at must be later than started_at")++ return trigger+async def notify_changed(self, schedule_id: str) -> None:"""Tell the timer-owning node that a schedule was written.@@ -425,9 +496,6 @@ class SchedulerManager:record (`ScheduleRecord`):An enabled schedule record."""-- from apscheduler.triggers.cron import CronTrigger-logger.info("Registering schedule %s(%s) cron=%s tz=%s",record.id,@@ -435,32 +503,9 @@ class SchedulerManager:record.data.cron_expression,record.data.timezone,)-- # ``CronTrigger.from_crontab`` is a thin helper that only forwards- # the 5 parsed fields and ``timezone`` — it has no parameter for- # ``start_date`` / ``end_date``. Parse the expression ourselves so- # the configured activation window is honoured.- fields = record.data.cron_expression.split()- if len(fields) != 5:- raise ValueError(- "Expected a 5-field cron expression, got "- f"{record.data.cron_expression!r}",- )- minute, hour, day, month, day_of_week = fields-- trigger = self._build_trigger(record)job = self._scheduler.add_job(- trigger,- trigger=CronTrigger(- minute=minute,- hour=hour,- day=day,- month=month,- day_of_week=day_of_week,- timezone=record.data.timezone,- start_date=record.data.started_at,- end_date=record.data.ended_at,- ),+ self._build_trigger(record),+ trigger=self.validate_schedule(record),id=record.id,name=record.data.name,misfire_grace_time=300,diff --git a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.pyindex e5d81f856..b211ad944 100644--- a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py+++ b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py@@ -233,6 +233,7 @@ to complete the task independently.),)+ self._scheduler_manager.validate_schedule(record)await self._storage.upsert_schedule(self._user_id, record)await self._scheduler_manager.notify_changed(record.id)diff --git a/src/agentscope/app/_router/_schedule.py b/src/agentscope/app/_router/_schedule.pyindex b1295ca7a..ea2e026ce 100644--- a/src/agentscope/app/_router/_schedule.py+++ b/src/agentscope/app/_router/_schedule.py@@ -91,7 +91,8 @@ async def create_schedule(Raises:`HTTPException`: 404 if the specified agent or the credentialreferenced by ``chat_model_config`` is not visible to the- caller.+ caller; 422 if the cron expression, timezone or activation+ window is invalid."""# Visibility checks — raise 404 when neither owned nor shared. The# schedule fires under the owner's user_id, so re-validating the@@ -120,6 +121,15 @@ async def create_schedule(started_at=datetime.now(),),)++ try:+ scheduler.validate_schedule(record)+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail=str(exc),+ ) from exc+await storage.upsert_schedule(user_id, record)await scheduler.notify_changed(record.id)@@ -157,7 +167,9 @@ async def update_schedule(The updated schedule record.Raises:- `HTTPException`: 404 if the schedule does not exist.+ `HTTPException`: 404 if the schedule does not exist; 422 if the+ update leaves an invalid cron expression, timezone or+ activation window."""existing = await storage.get_schedule(user_id, schedule_id)if existing is None:@@ -171,6 +183,15 @@ async def update_schedule(updated_record = existing.model_copy(update={"data": updated_data, "updated_at": datetime.now()},)++ try:+ scheduler.validate_schedule(updated_record)+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail=str(exc),+ ) from exc+await storage.upsert_schedule(user_id, updated_record)await scheduler.notify_changed(schedule_id)diff --git a/tests/schedule_router_test.py b/tests/schedule_router_test.pynew file mode 100644index 000000000..fb410985f--- /dev/null+++ b/tests/schedule_router_test.py@@ -0,0 +1,312 @@+# -*- coding: utf-8 -*-+"""Tests for schedule validation before persistence and registration."""+from datetime import datetime+from unittest import IsolatedAsyncioTestCase++from fastapi import HTTPException++from agentscope.app._manager import SchedulerManager+from agentscope.app._manager._scheduler._tools._schedule_create import (+ ScheduleCreate,+)+from agentscope.app._router._schedule import create_schedule, update_schedule+from agentscope.app._router._schema._schedule import (+ CreateScheduleRequest,+ UpdateScheduleRequest,+)+from agentscope.app.storage import (+ ChatModelConfig,+ ScheduleData,+ ScheduleRecord,+)+from agentscope.permission import PermissionMode+++class _Access:+ """Allow all resources used by the route under test."""++ async def resolve_agent(self, user_id: str, agent_id: str) -> None:+ """Accept the requested agent."""++ async def get_resource(+ self,+ user_id: str,+ kind: object,+ resource_id: str,+ ) -> None:+ """Accept the requested credential."""+++class _Storage:+ """Record schedule writes without requiring Redis or SQL."""++ def __init__(self, existing: ScheduleRecord | None = None) -> None:+ self.existing = existing+ self.upserted: list[ScheduleRecord] = []++ async def get_schedule(+ self,+ user_id: str,+ schedule_id: str,+ ) -> ScheduleRecord | None:+ """Return the one fixture record."""+ _ = user_id, schedule_id+ return self.existing++ async def upsert_schedule(+ self,+ user_id: str,+ record: ScheduleRecord,+ ) -> str:+ """Record the write."""+ _ = user_id+ self.upserted.append(record)+ return record.id+++class _Scheduler(SchedulerManager):+ """Track what the owner would be told, keeping real validation."""++ def __init__(self) -> None:+ super().__init__(+ storage=None,+ message_bus=None,+ workspace_manager=None,+ )+ self.notified: list[str] = []++ async def notify_changed(self, schedule_id: str) -> None:+ """Record the nudge without touching the message bus."""+ self.notified.append(schedule_id)+++def _request(+ cron_expression: str,+ timezone: str = "UTC",+) -> CreateScheduleRequest:+ """Build a minimal schedule request."""+ return CreateScheduleRequest(+ name="test schedule",+ cron_expression=cron_expression,+ timezone=timezone,+ agent_id="agent-1",+ chat_model_config=ChatModelConfig(+ type="test",+ credential_id="credential-1",+ model="model-1",+ parameters={},+ ),+ )+++def _record() -> ScheduleRecord:+ """Build a valid existing schedule record."""+ return ScheduleRecord(+ id="schedule-1",+ user_id="user-1",+ agent_id="agent-1",+ data=ScheduleData(+ name="existing",+ cron_expression="0 9 * * *",+ timezone="UTC",+ started_at=datetime(2026, 1, 1),+ chat_model_config=ChatModelConfig(+ type="test",+ credential_id="credential-1",+ model="model-1",+ parameters={},+ ),+ permission_mode=PermissionMode.DONT_ASK,+ ),+ )+++class ScheduleValidationTest(IsolatedAsyncioTestCase):+ """Invalid schedules must fail before any state mutation."""++ async def test_create_valid_schedule_persists_and_notifies(self) -> None:+ """The rejections below only mean something if this passes."""+ storage = _Storage()+ scheduler = _Scheduler()++ response = await create_schedule(+ _request("0 9 * * *"),+ user_id="user-1",+ storage=storage,+ access=_Access(),+ scheduler=scheduler,+ )++ self.assertEqual(len(storage.upserted), 1)+ self.assertEqual(storage.upserted[0].id, response.schedule_id)+ self.assertListEqual(scheduler.notified, [response.schedule_id])++ async def test_create_empty_timezone_does_not_persist(self) -> None:+ """An empty timezone must not silently mean server-local."""+ storage = _Storage()+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await create_schedule(+ _request("0 9 * * *", timezone=""),+ user_id="user-1",+ storage=storage,+ access=_Access(),+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_create_invalid_cron_does_not_persist(self) -> None:+ """Create rejects invalid cron before writing the schedule."""+ storage = _Storage()+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await create_schedule(+ _request("not a cron"),+ user_id="user-1",+ storage=storage,+ access=_Access(),+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_create_out_of_range_cron_does_not_persist(self) -> None:+ """Cron field ranges are checked without constructing a trigger."""+ storage = _Storage()+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await create_schedule(+ _request("61 9 * * *"),+ user_id="user-1",+ storage=storage,+ access=_Access(),+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_create_invalid_timezone_does_not_persist(self) -> None:+ """Create rejects an unknown timezone before writing the schedule."""+ storage = _Storage()+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await create_schedule(+ _request("0 9 * * *", timezone="Mars/Olympus_Mons"),+ user_id="user-1",+ storage=storage,+ access=_Access(),+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_update_invalid_cron_keeps_existing_state(self) -> None:+ """Update rejects invalid cron before persisting or notifying."""+ existing = _record()+ storage = _Storage(existing)+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await update_schedule(+ "schedule-1",+ UpdateScheduleRequest(cron_expression="not a cron"),+ user_id="user-1",+ storage=storage,+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_update_invalid_timezone_keeps_existing_state(self) -> None:+ """Update rejects an unknown timezone before changing state."""+ existing = _record()+ storage = _Storage(existing)+ scheduler = _Scheduler()++ with self.assertRaises(HTTPException) as ctx:+ await update_schedule(+ "schedule-1",+ UpdateScheduleRequest(timezone="Mars/Olympus_Mons"),+ user_id="user-1",+ storage=storage,+ scheduler=scheduler,+ )++ self.assertEqual(ctx.exception.status_code, 422)+ self.assertEqual(storage.upserted, [])+ self.assertEqual(scheduler.notified, [])++ async def test_tool_invalid_cron_does_not_persist(self) -> None:+ """The agent-facing create tool validates before writing too."""+ storage = _Storage()+ scheduler = _Scheduler()+ tool = ScheduleCreate(+ user_id="user-1",+ agent_id="agent-1",+ chat_model_config=_request("0 9 * * *").chat_model_config,+ storage=storage,+ scheduler_manager=scheduler,+ )++ with self.assertRaises(ValueError):+ await tool(name="bad", cron_expression="not a cron")++ self.assertEqual(storage.upserted, [])++ async def test_tool_invalid_timezone_does_not_persist(self) -> None:+ """The agent-facing tool rejects an unknown timezone before writing."""+ storage = _Storage()+ scheduler = _Scheduler()+ tool = ScheduleCreate(+ user_id="user-1",+ agent_id="agent-1",+ chat_model_config=_request("0 9 * * *").chat_model_config,+ storage=storage,+ scheduler_manager=scheduler,+ )++ with self.assertRaises(ValueError):+ await tool(+ name="bad timezone",+ cron_expression="0 9 * * *",+ timezone="Mars/Olympus_Mons",+ )++ self.assertEqual(storage.upserted, [])++ async def test_tool_invalid_time_window_does_not_persist(self) -> None:+ """The agent-facing tool rejects a reversed activation window."""+ storage = _Storage()+ scheduler = _Scheduler()+ tool = ScheduleCreate(+ user_id="user-1",+ agent_id="agent-1",+ chat_model_config=_request("0 9 * * *").chat_model_config,+ storage=storage,+ scheduler_manager=scheduler,+ )++ with self.assertRaises(ValueError):+ await tool(+ name="bad window",+ cron_expression="0 9 * * *",+ started_at=datetime(2026, 1, 2),+ ended_at=datetime(2026, 1, 1),+ )++ self.assertEqual(storage.upserted, [])