Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add workflow schedules support (DB model, API routes, Temporal integration) (#SKY-8182) (#5144)
Aaron Perez1c68fbd40feb
diff --git a/pyproject.toml b/pyproject.tomlindex a6b3df6cf..e52f8d749 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,6 +72,7 @@ dependencies = ["zstandard>=0.25.0","sse-starlette>=3.0.3,<4","opentelemetry-api>=1.39.0,<2",+ "croniter>=1.3.8,<4",][dependency-groups]diff --git a/skyvern/forge/sdk/core/permissions/schedule_limit_checker.py b/skyvern/forge/sdk/core/permissions/schedule_limit_checker.pynew file mode 100644index 000000000..073cb9495--- /dev/null+++ b/skyvern/forge/sdk/core/permissions/schedule_limit_checker.py@@ -0,0 +1,35 @@+import abc++from skyvern.forge.sdk.schemas.organizations import Organization+++class ScheduleLimitChecker(abc.ABC):+ @abc.abstractmethod+ async def check_schedule_limit(+ self, organization: Organization, workflow_permanent_id: str, current_count: int+ ) -> None: ...++ @abc.abstractmethod+ async def get_schedule_limit(self, organization: Organization, workflow_permanent_id: str) -> int | None: ...+++class NoopScheduleLimitChecker(ScheduleLimitChecker):+ async def check_schedule_limit(+ self, organization: Organization, workflow_permanent_id: str, current_count: int+ ) -> None:+ return # unlimited in OSS++ async def get_schedule_limit(self, organization: Organization, workflow_permanent_id: str) -> int | None:+ return None # unlimited in OSS+++class ScheduleLimitCheckerFactory:+ __instance: ScheduleLimitChecker = NoopScheduleLimitChecker()++ @staticmethod+ def get_instance() -> ScheduleLimitChecker:+ return ScheduleLimitCheckerFactory.__instance++ @staticmethod+ def set_instance(checker: ScheduleLimitChecker) -> None:+ ScheduleLimitCheckerFactory.__instance = checkerdiff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex abe7865be..a384fd64a 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -1,6 +1,6 @@import jsonimport uuid-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltafrom typing import Any, List, Literal, Sequence, overloadimport structlog@@ -18,6 +18,7 @@ from sqlalchemy import (or_,pool,select,+ text,tuple_,update,)@@ -32,7 +33,7 @@ from skyvern.constants import DEFAULT_SCRIPT_RUN_IDfrom skyvern.exceptions import BrowserProfileNotFound, WorkflowParameterNotFound, WorkflowRunNotFoundfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactTypefrom skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB, read_retry-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, TaskType+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, TaskType, WorkflowRunTriggerTypefrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.db.models import (ActionModel,@@ -76,6 +77,7 @@ from skyvern.forge.sdk.db.models import (WorkflowRunModel,WorkflowRunOutputParameterModel,WorkflowRunParameterModel,+ WorkflowScheduleModel,WorkflowScriptModel,WorkflowTemplateModel,)@@ -99,6 +101,7 @@ from skyvern.forge.sdk.db.utils import (convert_to_workflow_run_block,convert_to_workflow_run_output_parameter,convert_to_workflow_run_parameter,+ convert_to_workflow_schedule,hydrate_action,)from skyvern.forge.sdk.encrypt import encryptor@@ -132,6 +135,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatSender,)from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.forge.sdk.schemas.workflow_schedules import OrganizationScheduleItem, WorkflowSchedulefrom skyvern.forge.sdk.utils.sanitization import sanitize_postgres_textfrom skyvern.forge.sdk.workflow.models.parameter import (PARAMETER_TYPE,@@ -154,6 +158,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (WorkflowRunParameter,WorkflowRunStatus,)+from skyvern.forge.sdk.workflow.schedules import compute_next_runfrom skyvern.schemas.runs import GeoTarget, ProxyLocation, ProxyLocationInput, RunEngine, RunTypefrom skyvern.schemas.scripts import (Script,@@ -238,6 +243,17 @@ def _build_engine(database_string: str) -> Any:)+class ScheduleLimitExceededError(Exception):+ """Raised when attempting to create a schedule that would exceed the per-workflow limit."""++ def __init__(self, organization_id: str, workflow_permanent_id: str, current_count: int, max_allowed: int):+ self.organization_id = organization_id+ self.workflow_permanent_id = workflow_permanent_id+ self.current_count = current_count+ self.max_allowed = max_allowed+ super().__init__(f"Schedule limit {max_allowed} reached (current: {current_count})")++class AgentDB(BaseAlchemyDB):def __init__(self, database_string: str, debug_enabled: bool = False, db_engine: AsyncEngine | None = None) -> None:super().__init__(db_engine or _build_engine(database_string))@@ -1972,6 +1988,515 @@ class AgentDB(BaseAlchemyDB):LOG.error("SQLAlchemyError", exc_info=True)raise+ async def create_workflow_schedule(+ self,+ organization_id: str,+ workflow_permanent_id: str,+ cron_expression: str,+ timezone: str,+ enabled: bool,+ parameters: dict[str, Any] | None = None,+ temporal_schedule_id: str | None = None,+ name: str | None = None,+ description: str | None = None,+ ) -> WorkflowSchedule:+ try:+ async with self.Session() as session:+ workflow_schedule = WorkflowScheduleModel(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ cron_expression=cron_expression,+ timezone=timezone,+ enabled=enabled,+ parameters=parameters,+ temporal_schedule_id=temporal_schedule_id,+ name=name,+ description=description,+ )+ session.add(workflow_schedule)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def create_workflow_schedule_with_limit(+ self,+ organization_id: str,+ workflow_permanent_id: str,+ max_schedules: int | None,+ cron_expression: str,+ timezone: str,+ enabled: bool,+ parameters: dict[str, Any] | None = None,+ name: str | None = None,+ description: str | None = None,+ ) -> tuple[WorkflowSchedule, int]:+ """Create a schedule atomically with limit enforcement.++ Uses a PostgreSQL advisory lock to serialize concurrent creates for the+ same workflow, preventing TOCTOU races on the schedule count.++ Returns (created_schedule, count_before_insert).+ Raises ScheduleLimitExceededError if count >= max_schedules.+ """+ try:+ async with self.Session() as session:+ lock_key = f"schedule:{organization_id}:{workflow_permanent_id}"+ await session.execute(+ text("SELECT pg_advisory_xact_lock(hashtext(:key))"),+ {"key": lock_key},+ )++ count = (+ await session.execute(+ select(func.count()).where(+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.workflow_permanent_id == workflow_permanent_id,+ WorkflowScheduleModel.deleted_at.is_(None),+ )+ )+ ).scalar_one()++ if max_schedules is not None and count >= max_schedules:+ raise ScheduleLimitExceededError(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ current_count=count,+ max_allowed=max_schedules,+ )++ workflow_schedule = WorkflowScheduleModel(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ cron_expression=cron_expression,+ timezone=timezone,+ enabled=enabled,+ parameters=parameters,+ name=name,+ description=description,+ )+ session.add(workflow_schedule)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled), count+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def set_temporal_schedule_id(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ temporal_schedule_id: str,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).first()++ if not workflow_schedule:+ return None++ workflow_schedule.temporal_schedule_id = temporal_schedule_id+ workflow_schedule.modified_at = datetime.now(UTC)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def update_workflow_schedule(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ cron_expression: str,+ timezone: str,+ enabled: bool,+ parameters: dict[str, Any] | None = None,+ temporal_schedule_id: str | None | object = _UNSET,+ name: str | None | object = _UNSET,+ description: str | None | object = _UNSET,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).first()++ if not workflow_schedule:+ return None++ workflow_schedule.cron_expression = cron_expression+ workflow_schedule.timezone = timezone+ workflow_schedule.enabled = enabled+ workflow_schedule.parameters = parameters+ if temporal_schedule_id is not _UNSET:+ workflow_schedule.temporal_schedule_id = temporal_schedule_id+ if name is not _UNSET:+ workflow_schedule.name = name+ if description is not _UNSET:+ workflow_schedule.description = description+ workflow_schedule.modified_at = datetime.now(UTC)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def get_workflow_schedule_by_id(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).first()+ if not workflow_schedule:+ return None+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def get_workflow_schedules(+ self,+ workflow_permanent_id: str,+ organization_id: str,+ ) -> list[WorkflowSchedule]:+ try:+ async with self.Session() as session:+ rows = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).all()+ return [convert_to_workflow_schedule(r, self.debug_enabled) for r in rows]+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def get_all_enabled_schedules(+ self,+ organization_id: str | None = None,+ ) -> list[WorkflowSchedule]:+ """Fetch all enabled, non-deleted schedules, optionally filtered by org."""+ try:+ async with self.Session() as session:+ stmt = select(WorkflowScheduleModel).where(+ WorkflowScheduleModel.enabled.is_(True),+ WorkflowScheduleModel.deleted_at.is_(None),+ )+ if organization_id:+ stmt = stmt.where(WorkflowScheduleModel.organization_id == organization_id)+ rows = (await session.scalars(stmt)).all()+ return [convert_to_workflow_schedule(r, self.debug_enabled) for r in rows]+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def has_schedule_fired_since(+ self,+ workflow_schedule_id: str,+ since: datetime,+ ) -> bool:+ """Check if a workflow_run exists for the given schedule since a timestamp."""+ try:+ async with self.Session() as session:+ row = (+ await session.execute(+ select(+ exists().where(+ WorkflowRunModel.workflow_schedule_id == workflow_schedule_id,+ WorkflowRunModel.created_at >= since,+ )+ )+ )+ ).scalar()+ return bool(row)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def update_workflow_schedule_enabled(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ enabled: bool,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).first()+ if not workflow_schedule:+ return None+ workflow_schedule.enabled = enabled+ workflow_schedule.modified_at = datetime.now(UTC)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def delete_workflow_schedule(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ deleted_at=None,+ )+ )+ ).first()+ if not workflow_schedule:+ return None++ workflow_schedule.deleted_at = datetime.now(UTC)+ workflow_schedule.modified_at = datetime.now(UTC)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def restore_workflow_schedule(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ ) -> WorkflowSchedule | None:+ try:+ async with self.Session() as session:+ workflow_schedule = (+ await session.scalars(+ select(WorkflowScheduleModel)+ .filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ )+ .filter(WorkflowScheduleModel.deleted_at.isnot(None))+ )+ ).first()+ if not workflow_schedule:+ return None++ workflow_schedule.deleted_at = None+ workflow_schedule.modified_at = datetime.now(UTC)+ await session.commit()+ await session.refresh(workflow_schedule)+ return convert_to_workflow_schedule(workflow_schedule, self.debug_enabled)+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def count_workflow_schedules(+ self,+ organization_id: str,+ workflow_permanent_id: str,+ ) -> int:+ try:+ async with self.Session() as session:+ result = await session.execute(+ select(func.count()).where(+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.workflow_permanent_id == workflow_permanent_id,+ WorkflowScheduleModel.deleted_at.is_(None),+ )+ )+ return result.scalar_one()+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise++ async def list_organization_schedules(+ self,+ organization_id: str,+ page: int = 1,+ page_size: int = 10,+ enabled_filter: bool | None = None,+ search: str | None = None,+ ) -> tuple[list[OrganizationScheduleItem], int]:+ """+ List all schedules for an organization, joined with workflow titles.+ Returns (schedules, total_count).+ """+ if page < 1:+ raise ValueError(f"Page must be greater than 0, got {page}")+ db_page = page - 1+ try:+ async with self.Session() as session:+ # Subquery to get the latest version title per workflow_permanent_id+ latest_version_sq = (+ select(+ WorkflowModel.workflow_permanent_id,+ func.max(WorkflowModel.version).label("max_version"),+ )+ .where(WorkflowModel.organization_id == organization_id)+ .where(WorkflowModel.deleted_at.is_(None))+ .group_by(WorkflowModel.workflow_permanent_id)+ .subquery()+ )++ workflow_title_sq = (+ select(+ WorkflowModel.workflow_permanent_id,+ WorkflowModel.title,+ )+ .join(+ latest_version_sq,+ (WorkflowModel.workflow_permanent_id == latest_version_sq.c.workflow_permanent_id)+ & (WorkflowModel.version == latest_version_sq.c.max_version),+ )+ .subquery()+ )++ # Base query: schedules joined with workflow titles+ base_filter = (+ select(WorkflowScheduleModel, workflow_title_sq.c.title.label("workflow_title"))+ .outerjoin(+ workflow_title_sq,+ WorkflowScheduleModel.workflow_permanent_id == workflow_title_sq.c.workflow_permanent_id,+ )+ .where(WorkflowScheduleModel.organization_id == organization_id)+ .where(WorkflowScheduleModel.deleted_at.is_(None))+ )++ if enabled_filter is not None:+ base_filter = base_filter.where(WorkflowScheduleModel.enabled == enabled_filter)++ if search:+ base_filter = base_filter.where(+ or_(+ workflow_title_sq.c.title.icontains(search, autoescape=True),+ WorkflowScheduleModel.name.icontains(search, autoescape=True),+ )+ )++ # Count query+ count_query = select(func.count()).select_from(base_filter.subquery())+ total_count = (await session.execute(count_query)).scalar_one()++ # Data query with pagination+ data_query = (+ base_filter.order_by(WorkflowScheduleModel.created_at.desc())+ .limit(page_size)+ .offset(db_page * page_size)+ )+ rows = (await session.execute(data_query)).all()++ # Materialize row data while session is open+ raw_schedules = []+ for row in rows:+ schedule_model = row[0]+ raw_schedules.append(+ (+ schedule_model.workflow_schedule_id,+ schedule_model.organization_id,+ schedule_model.workflow_permanent_id,+ row[1] or "Untitled Workflow",+ schedule_model.cron_expression,+ schedule_model.timezone,+ schedule_model.enabled,+ schedule_model.parameters,+ schedule_model.name,+ schedule_model.description,+ schedule_model.created_at,+ schedule_model.modified_at,+ )+ )++ # Compute next_run outside session scope (pure CPU, no DB needed)+ schedules: list[OrganizationScheduleItem] = []+ for (+ ws_id,+ org_id,+ wpid,+ title,+ cron_expr,+ tz,+ enabled,+ params,+ name,+ description,+ created,+ modified,+ ) in raw_schedules:+ next_run = None+ if enabled:+ try:+ next_run = compute_next_run(cron_expr, tz)+ except Exception:+ LOG.warning(+ "Failed to compute next_run for schedule",+ workflow_schedule_id=ws_id,+ exc_info=True,+ )++ schedules.append(+ OrganizationScheduleItem(+ workflow_schedule_id=ws_id,+ organization_id=org_id,+ workflow_permanent_id=wpid,+ workflow_title=title,+ cron_expression=cron_expr,+ timezone=tz,+ enabled=enabled,+ parameters=params,+ name=name,+ description=description,+ next_run=next_run,+ created_at=created,+ modified_at=modified,+ )+ )++ return schedules, total_count+ except SQLAlchemyError:+ LOG.error("SQLAlchemyError", exc_info=True)+ raise+async def get_workflow_for_workflow_run(self,workflow_run_id: str,@@ -2883,9 +3408,15 @@ class AgentDB(BaseAlchemyDB):debug_session_id: str | None = None,ai_fallback: bool | None = None,code_gen: bool | None = None,+ workflow_run_id: str | None = None,+ trigger_type: WorkflowRunTriggerType | None = None,+ workflow_schedule_id: str | None = None,) -> WorkflowRun:try:async with self.Session() as session:+ kwargs: dict[str, Any] = {}+ if workflow_run_id is not None:+ kwargs["workflow_run_id"] = workflow_run_idworkflow_run = WorkflowRunModel(workflow_permanent_id=workflow_permanent_id,workflow_id=workflow_id,@@ -2906,6 +3437,9 @@ class AgentDB(BaseAlchemyDB):debug_session_id=debug_session_id,ai_fallback=ai_fallback,code_gen=code_gen,+ trigger_type=trigger_type.value if trigger_type else None,+ workflow_schedule_id=workflow_schedule_id,+ **kwargs,)session.add(workflow_run)await session.commit()diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex 32586c623..82eec84c2 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -5,7 +5,7 @@ import pydantic.jsonimport structlogfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactType-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, WorkflowRunTriggerTypefrom skyvern.forge.sdk.db.models import (ActionModel,ArtifactModel,@@ -93,6 +93,16 @@ from skyvern.webeye.actions.actions import (LOG = structlog.get_logger()+def _safe_trigger_type(raw: str | None) -> WorkflowRunTriggerType | None:+ if not raw:+ return None+ try:+ return WorkflowRunTriggerType(raw)+ except ValueError:+ LOG.warning("Unknown trigger_type in DB, defaulting to None", trigger_type=raw)+ return None++def _deserialize_proxy_location(value: str | None) -> ProxyLocationInput:"""Deserialize proxy_location from database storage.@@ -428,6 +438,8 @@ def convert_to_workflow_run(run_with=workflow_run_model.run_with,code_gen=workflow_run_model.code_gen,ai_fallback=workflow_run_model.ai_fallback,+ trigger_type=_safe_trigger_type(workflow_run_model.trigger_type),+ workflow_schedule_id=workflow_run_model.workflow_schedule_id,)diff --git a/skyvern/forge/sdk/workflow/schedules.py b/skyvern/forge/sdk/workflow/schedules.pynew file mode 100644index 000000000..177116b04--- /dev/null+++ b/skyvern/forge/sdk/workflow/schedules.py@@ -0,0 +1,50 @@+from __future__ import annotations++from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import structlog+from croniter import croniter # type: ignore[import-untyped]++LOG = structlog.get_logger()++MIN_CRON_INTERVAL_SECONDS = 5 * 60+++def validate_timezone_name(timezone: str) -> None:+ try:+ ZoneInfo(timezone)+ except Exception as e: # ZoneInfoNotFoundError derives from KeyError+ raise ValueError(f"Invalid timezone '{timezone}'") from e+++def validate_cron_expression(cron_expression: str, minimum_interval_seconds: int = MIN_CRON_INTERVAL_SECONDS) -> None:+ if not croniter.is_valid(cron_expression):+ raise ValueError("Invalid cron expression")++ now = datetime.now(UTC)+ cron = croniter(cron_expression, now)+ first = cron.get_next(datetime)+ second = cron.get_next(datetime)+ if (second - first).total_seconds() < minimum_interval_seconds:+ raise ValueError(f"Cron interval must be at least {minimum_interval_seconds // 60} minutes")+++def calculate_next_runs(cron_expression: str, timezone: str, count: int) -> list[datetime]:+ now = datetime.now(ZoneInfo(timezone))+ itr = croniter(cron_expression, now)+ return [itr.get_next(datetime).astimezone(UTC) for _ in range(count)]+++def compute_next_run(cron_expression: str, timezone: str) -> datetime:+ """Compute the single next run time. Caller must ensure inputs are valid (e.g. from DB)."""+ now = datetime.now(ZoneInfo(timezone))+ itr = croniter(cron_expression, now)+ return itr.get_next(datetime).astimezone(UTC)+++def compute_previous_fire_time(cron_expression: str, timezone: str) -> datetime:+ """Compute the most recent scheduled fire time. Caller must ensure inputs are valid (e.g. from DB)."""+ now = datetime.now(ZoneInfo(timezone))+ itr = croniter(cron_expression, now)+ return itr.get_prev(datetime).astimezone(UTC)diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 89f979833..c29b90c17 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -55,6 +55,7 @@ from skyvern.forge.sdk.cache.factory import CacheFactoryfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.security import generate_skyvern_webhook_signaturefrom skyvern.forge.sdk.core.skyvern_context import SkyvernContext+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.organizations import Organization@@ -577,6 +578,63 @@ class WorkflowService:if credential is None:raise InvalidCredentialId(credential_id)+ async def validate_schedule_parameters(+ self,+ workflow: Workflow,+ organization: Organization,+ request_data: dict[str, Any] | None,+ ) -> None:+ all_workflow_parameters = await self.get_workflow_parameters(workflow_id=workflow.workflow_id)+ schedule_parameters = [+ cast(WorkflowParameter, workflow_parameter)+ for workflow_parameter in all_workflow_parameters+ if self._is_schedule_input_parameter(workflow_parameter)+ ]+ request_data = request_data or {}++ defined_keys = {workflow_parameter.key for workflow_parameter in schedule_parameters}+ unknown_keys = sorted(set(request_data) - defined_keys)+ if unknown_keys:+ unknown_keys_str = ", ".join(unknown_keys)+ raise SkyvernHTTPException(+ message=(+ f"Unknown schedule parameters for workflow {workflow.workflow_permanent_id}: {unknown_keys_str}"+ )+ )++ missing_parameters: list[str] = []+ for workflow_parameter in schedule_parameters:+ if workflow_parameter.key in request_data:+ request_value = request_data[workflow_parameter.key]+ # Treat explicit None as "use the default at execution time". Validate the+ # default value instead so the check matches what actually runs.+ if request_value is None and workflow_parameter.default_value is not None:+ request_value = workflow_parameter.default_value+ if self._is_missing_required_value(workflow_parameter, request_value):+ missing_parameters.append(workflow_parameter.key)+ continue+ if workflow_parameter.workflow_parameter_type == WorkflowParameterType.CREDENTIAL_ID:+ if not isinstance(request_value, str):+ raise InvalidCredentialId(f"Credential ID must be a string, got {type(request_value).__name__}")+ await self._validate_credential_id(request_value, organization)+ elif workflow_parameter.default_value is not None:+ if workflow_parameter.workflow_parameter_type == WorkflowParameterType.CREDENTIAL_ID:+ if not isinstance(workflow_parameter.default_value, str):+ raise InvalidCredentialId(+ f"Credential ID must be a string, got {type(workflow_parameter.default_value).__name__}"+ )+ await self._validate_credential_id(workflow_parameter.default_value, organization)+ else:+ missing_parameters.append(workflow_parameter.key)++ if missing_parameters:+ missing_keys_str = ", ".join(sorted(missing_parameters))+ raise SkyvernHTTPException(+ message=(+ f"Missing schedule parameters for workflow {workflow.workflow_permanent_id}: {missing_keys_str}"+ )+ )+async def setup_workflow_run(self,request_id: str | None,@@ -589,6 +647,9 @@ class WorkflowService:parent_workflow_run_id: str | None = None,debug_session_id: str | None = None,code_gen: bool | None = None,+ workflow_run_id: str | None = None,+ trigger_type: WorkflowRunTriggerType | None = None,+ workflow_schedule_id: str | None = None,) -> WorkflowRun:"""Create a workflow run and its parameters. Validate the workflow and the organization. If there are missing@@ -625,6 +686,9 @@ class WorkflowService:sequential_key=workflow.sequential_key,debug_session_id=debug_session_id,code_gen=code_gen,+ workflow_run_id=workflow_run_id,+ trigger_type=trigger_type,+ workflow_schedule_id=workflow_schedule_id,)LOG.info(f"Created workflow run {workflow_run.workflow_run_id} for workflow {workflow.workflow_id}",@@ -741,6 +805,19 @@ class WorkflowService:return "value cannot be null"return "database error while saving parameter value"+ @staticmethod+ def _is_schedule_input_parameter(workflow_parameter: Any) -> bool:+ """Check whether a parameter is user-configurable input for scheduled runs.++ Filters to WorkflowParameter instances only — excludes ContextParameter,+ OutputParameter, and CredentialParameter (the model class, whose credentials+ are resolved at runtime). Note that a WorkflowParameter whose+ workflow_parameter_type is CREDENTIAL_ID *is* included here because the+ user supplies the credential ID string at schedule time; only the actual+ CredentialParameter objects are excluded.+ """+ return isinstance(workflow_parameter, WorkflowParameter)+@staticmethoddef _is_missing_required_value(workflow_parameter: WorkflowParameter, value: Any) -> bool:"""@@ -3176,6 +3253,9 @@ class WorkflowService:sequential_key: str | None = None,debug_session_id: str | None = None,code_gen: bool | None = None,+ workflow_run_id: str | None = None,+ trigger_type: WorkflowRunTriggerType | None = None,+ workflow_schedule_id: str | None = None,) -> WorkflowRun:# validate the browser session or profile idbrowser_profile_id = workflow_request.browser_profile_id@@ -3263,6 +3343,9 @@ class WorkflowService:debug_session_id=debug_session_id,ai_fallback=workflow_request.ai_fallback,code_gen=code_gen,+ workflow_run_id=workflow_run_id,+ trigger_type=trigger_type,+ workflow_schedule_id=workflow_schedule_id,)async def _update_workflow_run_status(diff --git a/tests/unit/test_temporal_v2_workflow_activities.py b/tests/unit/test_temporal_v2_workflow_activities.pynew file mode 100644index 000000000..f83b85f24--- /dev/null+++ b/tests/unit/test_temporal_v2_workflow_activities.py@@ -0,0 +1,238 @@+import importlib+import sys+from types import ModuleType, SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus++# Skip the entire module when the cloud-only workers package is not available+pytest.importorskip("workers.temporal_v2_worker.activities")+++def _import_activities_module(monkeypatch: pytest.MonkeyPatch):+ # activities.py imports cloud-only modules at import time, so these tests+ # stub them and re-import the module for each test case.+ from dataclasses import dataclass+ from typing import Optional++ cloud_package = ModuleType("cloud")+ cloud_package.__path__ = []+ cloud_services = ModuleType("cloud.services")+ data_scrubber_module = ModuleType("cloud.services.data_scrubber_service")+ workers_package = ModuleType("workers")+ workers_package.__path__ = []+ worker_utils_module = ModuleType("workers.worker_utils")+ run_parameters_module = ModuleType("workers.run_parameters")++ class DataScrubber:+ pass++ async def activity_teardown() -> None:+ return None++ @dataclass+ class RunSkyvernWorkflowParams:+ organization_id: str+ workflow_run_id: str+ is_scheduled_run: bool = False+ workflow_permanent_id: Optional[str] = None+ workflow_schedule_id: Optional[str] = None++ data_scrubber_module.DataScrubber = DataScrubber+ worker_utils_module.activity_teardown = activity_teardown+ run_parameters_module.RunSkyvernWorkflowParams = RunSkyvernWorkflowParams+ monkeypatch.setitem(sys.modules, "cloud", cloud_package)+ monkeypatch.setitem(sys.modules, "cloud.services", cloud_services)+ monkeypatch.setitem(sys.modules, "cloud.services.data_scrubber_service", data_scrubber_module)+ temporal_v2_worker_package = ModuleType("workers.temporal_v2_worker")+ temporal_v2_worker_package.__path__ = []+ monkeypatch.setitem(sys.modules, "workers", workers_package)+ monkeypatch.setitem(sys.modules, "workers.worker_utils", worker_utils_module)+ monkeypatch.setitem(sys.modules, "workers.run_parameters", run_parameters_module)+ monkeypatch.setitem(sys.modules, "workers.temporal_v2_worker", temporal_v2_worker_package)+ sys.modules.pop("workers.temporal_v2_worker.activities", None)+ activities = importlib.import_module("workers.temporal_v2_worker.activities")+ return activities, RunSkyvernWorkflowParams+++async def test_setup_scheduled_workflow_run_sets_trigger_metadata(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ activities, RunSkyvernWorkflowParams = _import_activities_module(monkeypatch)+ created_workflow_run = SimpleNamespace(workflow_run_id="wr_sched_123", status=WorkflowRunStatus.created)+ queued_workflow_run = SimpleNamespace(workflow_run_id="wr_sched_123", status=WorkflowRunStatus.queued)+ organization = SimpleNamespace(organization_id="org_123")+ workflow = SimpleNamespace(title="Scheduled Workflow")++ fake_db = SimpleNamespace(+ get_workflow_run=AsyncMock(return_value=None),+ get_organization=AsyncMock(return_value=organization),+ update_workflow_run=AsyncMock(return_value=queued_workflow_run),+ get_run=AsyncMock(return_value=None),+ create_task_run=AsyncMock(),+ )+ fake_workflow_service = SimpleNamespace(+ setup_workflow_run=AsyncMock(return_value=created_workflow_run),+ get_workflow_by_permanent_id=AsyncMock(return_value=workflow),+ )++ monkeypatch.setattr(activities.app, "DATABASE", fake_db)+ monkeypatch.setattr(activities.app, "WORKFLOW_SERVICE", fake_workflow_service)++ result = await activities.setup_scheduled_workflow_run(+ organization_id="org_123",+ workflow_permanent_id="wpid_123",+ workflow_schedule_id="ws_123",+ temporal_workflow_id="temporal_sched_123",+ parameters={"key": "value"},+ workflow_run_id="wr_sched_123",+ )++ assert result == "wr_sched_123"+ assert (+ fake_workflow_service.setup_workflow_run.await_args.kwargs["trigger_type"] == WorkflowRunTriggerType.scheduled+ )+ assert fake_workflow_service.setup_workflow_run.await_args.kwargs["workflow_schedule_id"] == "ws_123"+ fake_db.update_workflow_run.assert_awaited_once_with(+ workflow_run_id="wr_sched_123",+ status=WorkflowRunStatus.queued,+ job_id="temporal_sched_123",+ )+ fake_db.create_task_run.assert_awaited_once()+++async def test_setup_scheduled_workflow_run_reuses_existing_run_without_duplicate_task_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ activities, RunSkyvernWorkflowParams = _import_activities_module(monkeypatch)+ existing_workflow_run = SimpleNamespace(workflow_run_id="wr_sched_123", status=WorkflowRunStatus.queued)+ organization = SimpleNamespace(organization_id="org_123")++ fake_db = SimpleNamespace(+ get_workflow_run=AsyncMock(return_value=existing_workflow_run),+ get_organization=AsyncMock(return_value=organization),+ update_workflow_run=AsyncMock(),+ get_run=AsyncMock(return_value=SimpleNamespace(run_id="wr_sched_123")),+ create_task_run=AsyncMock(),+ )+ fake_workflow_service = SimpleNamespace(+ setup_workflow_run=AsyncMock(),+ get_workflow_by_permanent_id=AsyncMock(return_value=SimpleNamespace(title="Scheduled Workflow")),+ )++ monkeypatch.setattr(activities.app, "DATABASE", fake_db)+ monkeypatch.setattr(activities.app, "WORKFLOW_SERVICE", fake_workflow_service)++ result = await activities.setup_scheduled_workflow_run(+ organization_id="org_123",+ workflow_permanent_id="wpid_123",+ workflow_schedule_id="ws_123",+ temporal_workflow_id="temporal_sched_123",+ parameters={"key": "value"},+ workflow_run_id="wr_sched_123",+ )++ assert result == "wr_sched_123"+ fake_workflow_service.setup_workflow_run.assert_not_awaited()+ fake_db.update_workflow_run.assert_not_awaited()+ fake_db.create_task_run.assert_not_awaited()+++async def test_setup_scheduled_workflow_run_requeues_existing_created_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ activities, RunSkyvernWorkflowParams = _import_activities_module(monkeypatch)+ existing_workflow_run = SimpleNamespace(workflow_run_id="wr_sched_123", status=WorkflowRunStatus.created)+ queued_workflow_run = SimpleNamespace(workflow_run_id="wr_sched_123", status=WorkflowRunStatus.queued)+ organization = SimpleNamespace(organization_id="org_123")++ fake_db = SimpleNamespace(+ get_workflow_run=AsyncMock(return_value=existing_workflow_run),+ get_organization=AsyncMock(return_value=organization),+ update_workflow_run=AsyncMock(return_value=queued_workflow_run),+ get_run=AsyncMock(return_value=None),+ create_task_run=AsyncMock(),+ )+ fake_workflow_service = SimpleNamespace(+ setup_workflow_run=AsyncMock(),+ get_workflow_by_permanent_id=AsyncMock(return_value=SimpleNamespace(title="Scheduled Workflow")),+ )++ monkeypatch.setattr(activities.app, "DATABASE", fake_db)+ monkeypatch.setattr(activities.app, "WORKFLOW_SERVICE", fake_workflow_service)++ result = await activities.setup_scheduled_workflow_run(+ organization_id="org_123",+ workflow_permanent_id="wpid_123",+ workflow_schedule_id="ws_123",+ temporal_workflow_id="temporal_sched_123",+ parameters={"key": "value"},+ workflow_run_id="wr_sched_123",+ )++ assert result == "wr_sched_123"+ fake_workflow_service.setup_workflow_run.assert_not_awaited()+ fake_db.update_workflow_run.assert_awaited_once_with(+ workflow_run_id="wr_sched_123",+ status=WorkflowRunStatus.queued,+ job_id="temporal_sched_123",+ )+ fake_db.create_task_run.assert_awaited_once()+++async def test_run_workflow_activity_rejects_scheduled_runs_without_workflow_permanent_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ activities, RunSkyvernWorkflowParams = _import_activities_module(monkeypatch)+ run_workflow_module = ModuleType("scripts.run_workflow")+ run_workflow_module.execute_workflow = AsyncMock()+ monkeypatch.setitem(sys.modules, "scripts.run_workflow", run_workflow_module)+ monkeypatch.setattr(+ activities.otel_trace,+ "get_current_span",+ lambda: SimpleNamespace(set_attribute=lambda *args, **kwargs: None),+ )+ monkeypatch.setattr(activities.os, "makedirs", lambda *args, **kwargs: None)++ with pytest.raises(RuntimeError, match="workflow_permanent_id"):+ await activities.run_workflow_activity(+ RunSkyvernWorkflowParams(+ organization_id="org_123",+ workflow_run_id="",+ is_scheduled_run=True,+ workflow_schedule_id="ws_123",+ )+ )+++async def test_run_workflow_activity_rejects_scheduled_runs_without_schedule_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ activities, RunSkyvernWorkflowParams = _import_activities_module(monkeypatch)+ run_workflow_module = ModuleType("scripts.run_workflow")+ run_workflow_module.execute_workflow = AsyncMock()+ monkeypatch.setitem(sys.modules, "scripts.run_workflow", run_workflow_module)+ monkeypatch.setattr(+ activities.otel_trace,+ "get_current_span",+ lambda: SimpleNamespace(set_attribute=lambda *args, **kwargs: None),+ )+ monkeypatch.setattr(activities.os, "makedirs", lambda *args, **kwargs: None)++ with pytest.raises(RuntimeError, match="workflow_schedule_id"):+ await activities.run_workflow_activity(+ RunSkyvernWorkflowParams(+ organization_id="org_123",+ workflow_run_id="",+ workflow_permanent_id="wpid_123",+ is_scheduled_run=True,+ )+ )diff --git a/uv.lock b/uv.lockindex 8de120fa4..37987ad11 100644--- a/uv.lock+++ b/uv.lock@@ -868,6 +868,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" },]+[[package]]+name = "croniter"+version = "3.0.4"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "python-dateutil" },+ { name = "pytz" },+]+sdist = { url = "https://files.pythonhosted.org/packages/07/ea/98665cd116af6d3c4e79c8dc91bbd9a13746cb3c7d72efbfdef5b720c43b/croniter-3.0.4.tar.gz", hash = "sha256:f9dcd4bdb6c97abedb6f09d6ed3495b13ede4d4544503fa580b6372a56a0c520", size = 54500, upload-time = "2024-10-25T12:22:33.14Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/63/f5/135d0e57e5bdd2f978388d77ee818f1ac5ac584eb48034362770001f4cad/croniter-3.0.4-py2.py3-none-any.whl", hash = "sha256:96e14cdd5dcb479dd48d7db14b53d8434b188dfb9210448bef6f65663524a6f0", size = 23220, upload-time = "2024-10-25T12:22:30.75Z" },+]+[[package]]name = "cryptography"version = "46.0.5"@@ -5521,6 +5534,7 @@ dependencies = [{ name = "azure-keyvault-secrets" },{ name = "azure-storage-blob" },{ name = "cachetools" },+ { name = "croniter" },{ name = "curlparser" },{ name = "email-validator" },{ name = "fastapi" },@@ -5638,6 +5652,7 @@ requires-dist = [{ name = "azure-keyvault-secrets", specifier = ">=4.2.0,<5" },{ name = "azure-storage-blob", specifier = ">=12.26.0" },{ name = "cachetools", specifier = ">=5.3.2,<6" },+ { name = "croniter", specifier = ">=1.3.8,<4" },{ name = "curlparser", specifier = ">=0.1.0,<0.2" },{ name = "email-validator", specifier = ">=2.2.0,<3" },{ name = "fastapi", specifier = ">=0.121.0,<0.129" },