Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Enable OSS workflow schedules (#6344)
Suchintan60b5728dc6c5
diff --git a/skyvern/config.py b/skyvern/config.pyindex 116149ea7..93838f335 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -592,6 +592,14 @@ class Settings(BaseSettings):CLEANUP_STALE_TASK_THRESHOLD_HOURS: int = 24"""Tasks/workflows not updated for this many hours are considered stale (stuck)."""+ # Workflow Schedule Settings+ ENABLE_WORKFLOW_SCHEDULES: bool = True+ """Enable recurring workflow schedules in the OSS/local server."""+ WORKFLOW_SCHEDULE_POLL_INTERVAL_SECONDS: float = 60.0+ """How often the OSS/local scheduler scans for due workflow schedules."""+ WORKFLOW_SCHEDULE_MAX_CONCURRENT_RUNS: int = 1+ """Maximum number of scheduled workflow runs dispatched concurrently by one OSS server process."""+# OpenTelemetry SettingsOTEL_ENABLED: bool = FalseOTEL_SERVICE_NAME: str = "skyvern"diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 03783476f..4b903618b 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -464,12 +464,16 @@ async def _convert_css_shape_to_string(class AgentFunction:- workflow_schedules_enabled: bool = False+ workflow_schedules_enabled: bool = settings.ENABLE_WORKFLOW_SCHEDULES"""Whether the workflow scheduler routes should serve traffic on this build.- OSS Skyvern has no scheduling backend wired up by default, so the routes return 501.- Cloud overrides this to True and provides the Temporal-backed implementations below.+ OSS Skyvern uses a local background scheduler by default. Set+ ENABLE_WORKFLOW_SCHEDULES=false to disable the routes and scheduler.+ Cloud overrides the local scheduler flag and provides the Temporal-backed+ implementations below."""+ workflow_schedules_use_local_scheduler: bool = settings.ENABLE_WORKFLOW_SCHEDULES+ """Whether the API process should run the built-in local scheduler loop."""def get_flex_llm_key(self, llm_key: str | None) -> str | None:"""Return a flex-tier router key for the given LLM key, or None if no flex twin exists.@@ -776,10 +780,10 @@ class AgentFunction:def build_workflow_schedule_id(self, workflow_schedule_id: str) -> str | None:"""Return the backend-specific schedule id used by the execution engine.- OSS has no execution backend, so this returns None and the schedule simply- lives in the database. Cloud overrides this to derive a Temporal schedule id.+ OSS uses a deterministic local backend id. Cloud overrides this to derive+ a Temporal schedule id."""- return None+ return f"local-wf-sched-{workflow_schedule_id}"async def upsert_workflow_schedule(self,@@ -794,7 +798,7 @@ class AgentFunction:) -> None:"""Upsert a recurring schedule with the execution backend (e.g. Temporal).- OSS base is a no-op so the route layer can stay backend-agnostic.+ OSS base is a no-op because the local scheduler scans the database.Cloud overrides this to register the schedule with Temporal.Implementations must be idempotent."""diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.pyindex 967fb4b00..c3d44f8dd 100644--- a/skyvern/forge/api_app.py+++ b/skyvern/forge/api_app.py@@ -45,6 +45,10 @@ from skyvern.forge.sdk.services.local_org_auth_token_service import (regenerate_local_api_key,)from skyvern.services.cleanup_service import start_cleanup_scheduler, stop_cleanup_scheduler+from skyvern.services.workflow_schedule_service import (+ start_workflow_schedule_scheduler,+ stop_workflow_schedule_scheduler,+)LOG = structlog.get_logger()@@ -180,6 +184,10 @@ async def lifespan(fastapi_app: FastAPI) -> AsyncGenerator[None, Any]:if cleanup_task:LOG.info("Cleanup scheduler started")+ workflow_schedule_task = start_workflow_schedule_scheduler()+ if workflow_schedule_task:+ LOG.info("Workflow schedule scheduler started")+# Start MCP sub-application lifespan if mounted. Starlette Mount does NOT# forward lifespan events to sub-apps, so we must enter the MCP app's# lifespan here. This initializes the streamable-http session manager's@@ -194,6 +202,7 @@ async def lifespan(fastapi_app: FastAPI) -> AsyncGenerator[None, Any]:yield# Stop cleanup scheduler+ await stop_workflow_schedule_scheduler()await stop_cleanup_scheduler()if forge_app.api_app_shutdown_event:diff --git a/skyvern/services/workflow_schedule_service.py b/skyvern/services/workflow_schedule_service.pynew file mode 100644index 000000000..5bddcae8e--- /dev/null+++ b/skyvern/services/workflow_schedule_service.py@@ -0,0 +1,287 @@+"""Local OSS workflow scheduler.++Cloud registers schedules with Temporal. OSS runs this lightweight scanner in+the API process and launches due workflow runs directly through the shared+workflow service.+"""++from __future__ import annotations++import asyncio+import hashlib+from collections.abc import Callable+from dataclasses import dataclass+from datetime import UTC, datetime++import structlog+from sqlalchemy.exc import IntegrityError, SQLAlchemyError++from skyvern.config import settings+from skyvern.forge import app+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody+from skyvern.forge.sdk.workflow.schedules import compute_previous_fire_time+from skyvern.services.workflow_service import prepare_workflow+from skyvern.utils.files import initialize_skyvern_state_file++LOG = structlog.get_logger(__name__)++FireKey = tuple[str, datetime]+++@dataclass(frozen=True)+class DueWorkflowSchedule:+ schedule: WorkflowSchedule+ previous_fire_time: datetime+++def build_scheduled_workflow_run_id(workflow_schedule_id: str, fire_time: datetime) -> str:+ normalized_fire_time = _as_utc(fire_time)+ digest = hashlib.sha256(f"{workflow_schedule_id}:{normalized_fire_time.isoformat()}".encode()).hexdigest()[:32]+ return f"wr_sched_{digest}"+++def _as_utc(value: datetime) -> datetime:+ if value.tzinfo is None:+ return value.replace(tzinfo=UTC)+ return value.astimezone(UTC)+++class LocalWorkflowScheduleScheduler:+ def __init__(self, *, poll_interval_seconds: float, max_concurrent_runs: int) -> None:+ self.poll_interval_seconds = poll_interval_seconds+ self.max_concurrent_runs = max(1, max_concurrent_runs)+ self._dispatch_lock = asyncio.Lock()+ self._running_tasks: set[asyncio.Task[None]] = set()+ self._pending_fire_keys: set[FireKey] = set()++ async def run_forever(self) -> None:+ LOG.info(+ "Workflow schedule scheduler started",+ poll_interval_seconds=self.poll_interval_seconds,+ max_concurrent_runs=self.max_concurrent_runs,+ )++ while True:+ try:+ await self.dispatch_due_schedules()+ await asyncio.sleep(self.poll_interval_seconds)+ except asyncio.CancelledError:+ LOG.info("Workflow schedule scheduler cancelled")+ break+ except Exception:+ LOG.exception("Error in workflow schedule scheduler")+ await asyncio.sleep(self.poll_interval_seconds)++ async def dispatch_due_schedules(self) -> list[asyncio.Task[None]]:+ if self._dispatch_lock.locked():+ LOG.debug("Workflow schedule dispatch already in progress")+ return []++ async with self._dispatch_lock:+ self._reap_finished_tasks()+ open_slots = self.max_concurrent_runs - len(self._running_tasks)+ if open_slots <= 0:+ LOG.debug(+ "Workflow schedule dispatch skipped; concurrency limit reached",+ running=len(self._running_tasks),+ max_concurrent_runs=self.max_concurrent_runs,+ )+ return []++ schedules = await app.DATABASE.schedules.get_all_enabled_schedules()+ dispatched: list[asyncio.Task[None]] = []+ for schedule in schedules:+ if len(dispatched) >= open_slots:+ break++ due = await self._get_due_schedule(schedule)+ if due is None:+ continue++ fire_key = (schedule.workflow_schedule_id, due.previous_fire_time)+ if fire_key in self._pending_fire_keys:+ continue++ self._pending_fire_keys.add(fire_key)+ task = asyncio.create_task(+ self._run_schedule(due),+ name=f"workflow-schedule-{schedule.workflow_schedule_id}",+ )+ self._running_tasks.add(task)+ task.add_done_callback(self._release_callback(fire_key))+ dispatched.append(task)++ return dispatched++ async def shutdown(self) -> None:+ for task in list(self._running_tasks):+ task.cancel()+ if self._running_tasks:+ await asyncio.gather(*self._running_tasks, return_exceptions=True)+ self._running_tasks.clear()+ self._pending_fire_keys.clear()++ def _reap_finished_tasks(self) -> None:+ for task in list(self._running_tasks):+ if task.done():+ self._running_tasks.discard(task)++ def _release_callback(self, fire_key: FireKey) -> Callable[[asyncio.Task[None]], None]:+ def _callback(task: asyncio.Task[None]) -> None:+ self._release_task(task, fire_key)++ return _callback++ def _release_task(self, task: asyncio.Task[None], fire_key: FireKey) -> None:+ self._running_tasks.discard(task)+ self._pending_fire_keys.discard(fire_key)+ try:+ task.result()+ except asyncio.CancelledError:+ pass+ except Exception:+ LOG.exception("Scheduled workflow task failed")++ async def _get_due_schedule(self, schedule: WorkflowSchedule) -> DueWorkflowSchedule | None:+ try:+ previous_fire_time = _as_utc(compute_previous_fire_time(schedule.cron_expression, schedule.timezone))+ except Exception:+ LOG.warning(+ "Failed to compute previous fire time for workflow schedule",+ workflow_schedule_id=schedule.workflow_schedule_id,+ cron_expression=schedule.cron_expression,+ timezone=schedule.timezone,+ exc_info=True,+ )+ return None++ modified_at = _as_utc(schedule.modified_at)+ if previous_fire_time < modified_at:+ return None++ if await app.DATABASE.schedules.has_schedule_fired_since(+ schedule.workflow_schedule_id,+ previous_fire_time,+ ):+ return None++ return DueWorkflowSchedule(schedule=schedule, previous_fire_time=previous_fire_time)++ async def _run_schedule(self, due: DueWorkflowSchedule) -> None:+ schedule = due.schedule+ workflow_run_id = build_scheduled_workflow_run_id(schedule.workflow_schedule_id, due.previous_fire_time)+ LOG.info(+ "Dispatching scheduled workflow",+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_permanent_id=schedule.workflow_permanent_id,+ organization_id=schedule.organization_id,+ previous_fire_time=due.previous_fire_time.isoformat(),+ workflow_run_id=workflow_run_id,+ )++ organization = await app.DATABASE.organizations.get_organization(schedule.organization_id)+ if organization is None:+ LOG.warning(+ "Skipping workflow schedule with missing organization",+ workflow_schedule_id=schedule.workflow_schedule_id,+ organization_id=schedule.organization_id,+ )+ return++ try:+ workflow_run = await prepare_workflow(+ workflow_id=schedule.workflow_permanent_id,+ organization=organization,+ workflow_request=WorkflowRequestBody(data=schedule.parameters),+ request_id=f"schedule:{schedule.workflow_schedule_id}:{due.previous_fire_time.isoformat()}",+ trigger_type=WorkflowRunTriggerType.scheduled,+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_run_id=workflow_run_id,+ )+ except IntegrityError:+ LOG.info(+ "Scheduled workflow run already exists; skipping duplicate fire",+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_run_id=workflow_run_id,+ )+ return+ except SQLAlchemyError:+ if await app.DATABASE.schedules.has_schedule_fired_since(+ schedule.workflow_schedule_id,+ due.previous_fire_time,+ ):+ LOG.info(+ "Scheduled workflow run already persisted; skipping duplicate fire",+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_run_id=workflow_run_id,+ )+ return+ raise++ await initialize_skyvern_state_file(+ workflow_run_id=workflow_run.workflow_run_id,+ organization_id=organization.organization_id,+ )+ await app.WORKFLOW_SERVICE.execute_workflow(+ workflow_run_id=workflow_run.workflow_run_id,+ api_key=None,+ organization=organization,+ browser_session_id=workflow_run.browser_session_id,+ )+++_workflow_schedule_scheduler: LocalWorkflowScheduleScheduler | None = None+_workflow_schedule_task: asyncio.Task[None] | None = None+++def start_workflow_schedule_scheduler() -> asyncio.Task[None] | None:+ global _workflow_schedule_scheduler, _workflow_schedule_task++ if not app.AGENT_FUNCTION.workflow_schedules_enabled:+ LOG.debug("Workflow schedules are disabled")+ return None++ if not app.AGENT_FUNCTION.workflow_schedules_use_local_scheduler:+ LOG.debug("Local workflow schedule scheduler is disabled for this backend")+ return None++ if settings.WORKFLOW_SCHEDULE_POLL_INTERVAL_SECONDS <= 0:+ LOG.warning(+ "Workflow schedule scheduler disabled because WORKFLOW_SCHEDULE_POLL_INTERVAL_SECONDS is not positive",+ poll_interval_seconds=settings.WORKFLOW_SCHEDULE_POLL_INTERVAL_SECONDS,+ )+ return None++ if _workflow_schedule_task is not None and not _workflow_schedule_task.done():+ LOG.warning("Workflow schedule scheduler is already running")+ return _workflow_schedule_task++ _workflow_schedule_scheduler = LocalWorkflowScheduleScheduler(+ poll_interval_seconds=settings.WORKFLOW_SCHEDULE_POLL_INTERVAL_SECONDS,+ max_concurrent_runs=settings.WORKFLOW_SCHEDULE_MAX_CONCURRENT_RUNS,+ )+ _workflow_schedule_task = asyncio.create_task(_workflow_schedule_scheduler.run_forever())+ return _workflow_schedule_task+++async def stop_workflow_schedule_scheduler() -> None:+ global _workflow_schedule_scheduler, _workflow_schedule_task++ was_running = _workflow_schedule_scheduler is not None or _workflow_schedule_task is not None++ if _workflow_schedule_task is not None and not _workflow_schedule_task.done():+ _workflow_schedule_task.cancel()+ try:+ await _workflow_schedule_task+ except asyncio.CancelledError:+ pass++ if _workflow_schedule_scheduler is not None:+ await _workflow_schedule_scheduler.shutdown()++ _workflow_schedule_scheduler = None+ _workflow_schedule_task = None+ if was_running:+ LOG.info("Workflow schedule scheduler stopped")diff --git a/skyvern/services/workflow_service.py b/skyvern/services/workflow_service.pyindex 0a95d62bf..299b1a445 100644--- a/skyvern/services/workflow_service.py+++ b/skyvern/services/workflow_service.py@@ -27,6 +27,8 @@ async def prepare_workflow(code_gen: bool | None = None,parent_workflow_run_id: str | None = None,trigger_type: WorkflowRunTriggerType | None = None,+ workflow_schedule_id: str | None = None,+ workflow_run_id: str | None = None,ignore_inherited_workflow_system_prompt: bool = False,copilot_session_id: str | None = None,) -> WorkflowRun:@@ -47,8 +49,10 @@ async def prepare_workflow(is_template_workflow=template,debug_session_id=debug_session_id,code_gen=code_gen,+ workflow_run_id=workflow_run_id,parent_workflow_run_id=parent_workflow_run_id,trigger_type=trigger_type,+ workflow_schedule_id=workflow_schedule_id,ignore_inherited_workflow_system_prompt=ignore_inherited_workflow_system_prompt,copilot_session_id=copilot_session_id,)@@ -91,6 +95,7 @@ async def run_workflow(block_outputs: dict[str, t.Any] | None = None,parent_workflow_run_id: str | None = None,trigger_type: WorkflowRunTriggerType | None = None,+ workflow_schedule_id: str | None = None,ignore_inherited_workflow_system_prompt: bool = False,) -> WorkflowRun:workflow_run = await prepare_workflow(@@ -103,6 +108,7 @@ async def run_workflow(request_id=request_id,parent_workflow_run_id=parent_workflow_run_id,trigger_type=trigger_type,+ workflow_schedule_id=workflow_schedule_id,ignore_inherited_workflow_system_prompt=ignore_inherited_workflow_system_prompt,)diff --git a/tests/unit/forge/sdk/test_workflow_schedules_routes.py b/tests/unit/forge/sdk/test_workflow_schedules_routes.pyindex a0c5fa669..04d88302f 100644--- a/tests/unit/forge/sdk/test_workflow_schedules_routes.py+++ b/tests/unit/forge/sdk/test_workflow_schedules_routes.py@@ -1,18 +1,11 @@-"""OSS-side tests for the workflow schedules route module.--The OSS Skyvern build ships these routes wired into the OpenAPI spec so the-auto-generated SDKs include the schedules namespace, but the underlying-execution backend is not implemented in OSS. The route handlers must therefore-return HTTP 501 unless the AgentFunction override flips-``workflow_schedules_enabled`` on (which Skyvern Cloud does).-"""+"""OSS-side tests for the workflow schedules route module."""from __future__ import annotationsfrom types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest-from fastapi import HTTPExceptionimport skyvern.forge.sdk.routes.workflow_schedules as workflow_schedule_routesfrom skyvern.forge.agent_functions import AgentFunction@@ -21,7 +14,15 @@ from skyvern.forge.agent_functions import AgentFunction@pytest.fixture(autouse=True)def _install_oss_agent_function(monkeypatch: pytest.MonkeyPatch) -> AgentFunction:agent = AgentFunction()- monkeypatch.setattr(workflow_schedule_routes.app, "AGENT_FUNCTION", agent)+ fake_app = SimpleNamespace(+ AGENT_FUNCTION=agent,+ DATABASE=SimpleNamespace(+ schedules=SimpleNamespace(+ list_organization_schedules=AsyncMock(return_value=([], 0)),+ )+ ),+ )+ monkeypatch.setattr(workflow_schedule_routes, "app", fake_app)return agent@@ -29,19 +30,18 @@ def _organization() -> SimpleNamespace:return SimpleNamespace(organization_id="org_oss")-def test_oss_agent_function_disables_workflow_schedules() -> None:- assert AgentFunction().workflow_schedules_enabled is False+def test_oss_agent_function_enables_workflow_schedules() -> None:+ agent = AgentFunction()+ assert agent.workflow_schedules_enabled is True+ assert agent.workflow_schedules_use_local_scheduler is True-def test_require_schedules_enabled_raises_501_in_oss() -> None:- with pytest.raises(HTTPException) as exc_info:- workflow_schedule_routes._require_schedules_enabled()- assert exc_info.value.status_code == 501- assert "disabled" in exc_info.value.detail.lower()+def test_require_schedules_enabled_allows_oss() -> None:+ assert workflow_schedule_routes._require_schedules_enabled() is None-def test_oss_build_workflow_schedule_id_returns_none() -> None:- assert AgentFunction().build_workflow_schedule_id("ws_123") is None+def test_oss_build_workflow_schedule_id_returns_local_backend_id() -> None:+ assert AgentFunction().build_workflow_schedule_id("wfs_123") == "local-wf-sched-wfs_123"@pytest.mark.asyncio@@ -73,9 +73,9 @@ async def test_oss_delete_workflow_schedule_is_noop() -> None:"prefix,router_name",[("/v1", "base_router"), ("/api/v1", "legacy_base_router")],)-def test_oss_route_returns_501_via_testclient(prefix: str, router_name: str) -> None:- """End-to-end: route resolves through the FastAPI dependency chain and returns 501- on both the public `/v1` mount and the legacy `/api/v1` alias."""+def test_oss_route_returns_schedule_list_via_testclient(prefix: str, router_name: str) -> None:+ """End-to-end: route resolves through the FastAPI dependency chain on both+ the public `/v1` mount and the legacy `/api/v1` alias."""from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -91,5 +91,5 @@ def test_oss_route_returns_501_via_testclient(prefix: str, router_name: str) ->client = TestClient(fastapi_app)response = client.get(f"{prefix}/schedules")- assert response.status_code == 501- assert "disabled" in response.json()["detail"].lower()+ assert response.status_code == 200+ assert response.json() == {"schedules": [], "total_count": 0, "page": 1, "page_size": 10}diff --git a/tests/unit/test_workflow_schedule_service.py b/tests/unit/test_workflow_schedule_service.pynew file mode 100644index 000000000..574aa60d0--- /dev/null+++ b/tests/unit/test_workflow_schedule_service.py@@ -0,0 +1,135 @@+from __future__ import annotations++import asyncio+from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++import skyvern.services.workflow_schedule_service as schedule_service+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule+++def _schedule(*, modified_at: datetime | None = None) -> WorkflowSchedule:+ created_at = datetime(2026, 6, 2, 9, 0, tzinfo=UTC)+ return WorkflowSchedule(+ workflow_schedule_id="wfs_test",+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ cron_expression="0 * * * *",+ timezone="UTC",+ enabled=True,+ parameters={"city": "Toronto"},+ backend_schedule_id="local-wf-sched-wfs_test",+ created_at=created_at,+ modified_at=modified_at or created_at,+ )+++def test_build_scheduled_workflow_run_id_is_deterministic() -> None:+ fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)++ first = schedule_service.build_scheduled_workflow_run_id("wfs_test", fire_time)+ second = schedule_service.build_scheduled_workflow_run_id("wfs_test", fire_time)++ assert first == second+ assert first.startswith("wr_sched_")+++async def test_get_due_schedule_skips_backfill_after_modified_at(monkeypatch: pytest.MonkeyPatch) -> None:+ previous_fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)+ schedule = _schedule(modified_at=datetime(2026, 6, 2, 10, 1, tzinfo=UTC))+ has_schedule_fired_since = AsyncMock(return_value=False)+ monkeypatch.setattr(+ schedule_service,+ "app",+ SimpleNamespace(+ DATABASE=SimpleNamespace(schedules=SimpleNamespace(has_schedule_fired_since=has_schedule_fired_since))+ ),+ )+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)++ scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)++ assert await scheduler._get_due_schedule(schedule) is None+ has_schedule_fired_since.assert_not_awaited()+++async def test_get_due_schedule_skips_when_fire_already_has_run(monkeypatch: pytest.MonkeyPatch) -> None:+ previous_fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)+ schedule = _schedule(modified_at=datetime(2026, 6, 2, 9, 30, tzinfo=UTC))+ has_schedule_fired_since = AsyncMock(return_value=True)+ monkeypatch.setattr(+ schedule_service,+ "app",+ SimpleNamespace(+ DATABASE=SimpleNamespace(schedules=SimpleNamespace(has_schedule_fired_since=has_schedule_fired_since))+ ),+ )+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)++ scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)++ assert await scheduler._get_due_schedule(schedule) is None+ has_schedule_fired_since.assert_awaited_once_with("wfs_test", previous_fire_time)+++async def test_dispatch_due_schedules_launches_scheduled_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ previous_fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)+ schedule = _schedule(modified_at=datetime(2026, 6, 2, 9, 30, tzinfo=UTC))+ expected_workflow_run_id = schedule_service.build_scheduled_workflow_run_id(+ schedule.workflow_schedule_id,+ previous_fire_time,+ )++ fake_org = SimpleNamespace(organization_id="org_test")+ fake_workflow_run = SimpleNamespace(+ workflow_run_id=expected_workflow_run_id,+ workflow_id="w_test",+ workflow_permanent_id="wpid_test",+ browser_session_id=None,+ )+ prepare_workflow = AsyncMock(return_value=fake_workflow_run)+ initialize_state = AsyncMock()+ execute_workflow = AsyncMock()+ fake_app = SimpleNamespace(+ DATABASE=SimpleNamespace(+ schedules=SimpleNamespace(+ get_all_enabled_schedules=AsyncMock(return_value=[schedule]),+ has_schedule_fired_since=AsyncMock(return_value=False),+ ),+ organizations=SimpleNamespace(get_organization=AsyncMock(return_value=fake_org)),+ ),+ WORKFLOW_SERVICE=SimpleNamespace(execute_workflow=execute_workflow),+ )+ monkeypatch.setattr(schedule_service, "app", fake_app)+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)+ monkeypatch.setattr(schedule_service, "prepare_workflow", prepare_workflow)+ monkeypatch.setattr(schedule_service, "initialize_skyvern_state_file", initialize_state)++ scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)+ tasks = await scheduler.dispatch_due_schedules()+ await asyncio.gather(*tasks)++ assert len(tasks) == 1+ prepare_workflow.assert_awaited_once()+ prepare_kwargs = prepare_workflow.await_args.kwargs+ assert prepare_kwargs["trigger_type"] == WorkflowRunTriggerType.scheduled+ assert prepare_kwargs["workflow_schedule_id"] == "wfs_test"+ assert prepare_kwargs["workflow_run_id"] == expected_workflow_run_id+ assert prepare_kwargs["workflow_request"].data == {"city": "Toronto"}+ initialize_state.assert_awaited_once_with(+ workflow_run_id=expected_workflow_run_id,+ organization_id="org_test",+ )+ execute_workflow.assert_awaited_once_with(+ workflow_run_id=expected_workflow_run_id,+ api_key=None,+ organization=fake_org,+ browser_session_id=None,+ )