Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix: cascade child tasks and prevent workflow_run resurrection on cleanup-cron timeout (#6047)
Marc Kelechava7ad2b02d79c8
diff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.pyindex fc21c91c4..6424b75e4 100644--- a/skyvern/forge/sdk/db/repositories/tasks.py+++ b/skyvern/forge/sdk/db/repositories/tasks.py@@ -666,6 +666,40 @@ class TasksRepository(BaseRepository):await session.execute(update_stmt)await session.commit()+ @db_operation("bulk_update_tasks_by_workflow_run_ids")+ async def bulk_update_tasks_by_workflow_run_ids(+ self,+ workflow_run_ids: list[str],+ new_status: TaskStatus,+ only_if_status_in: list[TaskStatus],+ failure_reason: str | None = None,+ ) -> int:+ """Cascade-update child tasks of the given workflow_runs.++ The standalone-task cleanup cron skips rows with workflow_run_id set;+ this method sweeps their children when a parent is finalized. Stamps+ ``finished_at`` via COALESCE on terminal transitions. Returns row count.+ """+ if not workflow_run_ids or not only_if_status_in:+ return 0++ async with self.Session() as session:+ update_values: dict[str, Any] = {"status": new_status.value}+ if new_status.is_final():+ update_values["finished_at"] = func.coalesce(TaskModel.finished_at, datetime.now(timezone.utc))+ if failure_reason is not None:+ update_values["failure_reason"] = failure_reason++ update_stmt = (+ update(TaskModel)+ .where(TaskModel.workflow_run_id.in_(workflow_run_ids))+ .where(TaskModel.status.in_([s.value for s in only_if_status_in]))+ .values(**update_values)+ )+ result = await session.execute(update_stmt)+ await session.commit()+ return result.rowcount or 0+@db_operation("get_tasks")async def get_tasks(self,diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.pyindex b158980e6..1bad412e0 100644--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py@@ -327,19 +327,30 @@ class WorkflowRunsRepository(BaseRepository):workflow_run_id: str,status: WorkflowRunStatus,failure_reason: str | None = None,+ run_with: str | None = None,) -> WorkflowRun | None:"""Transition a workflow run to ``status`` only if it is not already in aterminal state. Returns the updated row, or ``None`` when the row wasalready terminal (or missing). Implemented as a single conditional``UPDATE ... WHERE status IN (<non-terminal>)`` so a concurrentfinalization write cannot be clobbered by a late cancel.++ Mirrors the timestamp side effects of :meth:`update_workflow_run`:+ ``finished_at`` is stamped on terminal transitions and ``started_at``+ is stamped on the first ``running`` transition (preserving any+ existing value via ``COALESCE``)."""non_terminal = [s.value for s in WorkflowRunStatus if not s.is_final()]+ now = datetime.now(timezone.utc)values: dict[str, Any] = {"status": status}if status.is_final():- values["finished_at"] = datetime.now(timezone.utc)+ values["finished_at"] = now+ if status == WorkflowRunStatus.running:+ values["started_at"] = func.coalesce(WorkflowRunModel.started_at, now)if failure_reason is not None:values["failure_reason"] = failure_reason+ if run_with is not None:+ values["run_with"] = run_withasync with self.Session() as session:result = await session.execute(diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 2f77b7398..16c4ae9f6 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -1357,6 +1357,16 @@ class WorkflowService:# Set workflow run status to running, create workflow run parametersworkflow_run = await self.mark_workflow_run_as_running(workflow_run_id=workflow_run_id)+ # Short-circuit when the conditional transition was refused (cron beat us+ # to finalization). Falling through would otherwise hit the finally-block+ # path below, which writes ``running`` again and emits orphan children.+ if workflow_run.status.is_final():+ LOG.info(+ "execute_workflow aborting — workflow_run already in final state",+ workflow_run_id=workflow_run_id,+ current_status=workflow_run.status,+ )+ return workflow_run# Get all context parameters from the workflow definitioncontext_parameters = [@@ -2355,20 +2365,11 @@ class WorkflowService:organization_id=organization_id,):workflow_run = refreshed_workflow_run- if workflow_run.status == WorkflowRunStatus.canceled:- LOG.info(- "Workflow run is canceled, stopping execution inside workflow execution loop",- workflow_run_id=workflow_run_id,- block_idx=block_idx,- block_type=block.block_type,- block_label=block.label,- )- return workflow_run, blocks_to_update, workflow_run_block_result, True, branch_metadata-- if workflow_run.status == WorkflowRunStatus.timed_out:+ if workflow_run.status.is_final():LOG.info(- "Workflow run is timed out, stopping execution inside workflow execution loop",+ "Workflow run is in a final state, stopping execution inside workflow execution loop",workflow_run_id=workflow_run_id,+ workflow_run_status=workflow_run.status,block_idx=block_idx,block_type=block.block_type,block_label=block.label,@@ -4485,11 +4486,35 @@ class WorkflowService:)async def mark_workflow_run_as_running(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:- workflow_run = await self._update_workflow_run_status(+ # Conditional UPDATE refuses to resurrect a finalized wr — prevents the+ # cleanup cron from racing with re-entry paths and stomping timed_out+ # back to running.+ workflow_run = await app.DATABASE.workflow_runs.update_workflow_run_if_not_final(workflow_run_id=workflow_run_id,status=WorkflowRunStatus.running,run_with=run_with,)+ if workflow_run is None:+ existing = await app.DATABASE.workflow_runs.get_workflow_run(+ workflow_run_id=workflow_run_id, organization_id=None+ )+ if existing is None:+ raise WorkflowRunNotFound(workflow_run_id)+ LOG.info(+ "Refusing to mark workflow_run as running — already in final state",+ workflow_run_id=workflow_run_id,+ current_status=existing.status,+ run_with=run_with,+ )+ return existing++ # Best-effort fire-and-forget write-through to task_runs table, matching+ # the side effect that _update_workflow_run_status would have triggered.+ bg = asyncio.create_task(+ self._sync_task_run_from_workflow_run(workflow_run, workflow_run_id, WorkflowRunStatus.running),+ )+ self._background_tasks.add(bg)+ bg.add_done_callback(self._background_tasks.discard)start_time = (workflow_run.started_at.replace(tzinfo=UTC)if workflow_run.started_at