Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-9188): reject canceled transition after workflow is finalized (#5605)
Aaron Perez2775f64c68cd
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 36255184f..9b36ca8f9 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -2414,6 +2414,555 @@}}}+ },+ "/v1/schedules": {+ "get": {+ "tags": [+ "Schedules"+ ],+ "summary": "List all schedules for the organization",+ "operationId": "schedules_list_all",+ "parameters": [+ {+ "name": "page",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "minimum": 1,+ "default": 1,+ "title": "Page"+ }+ },+ {+ "name": "page_size",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 100,+ "minimum": 1,+ "default": 10,+ "title": "Page Size"+ }+ },+ {+ "name": "status",+ "in": "query",+ "required": false,+ "schema": {+ "enum": [+ "active",+ "paused"+ ],+ "type": "string",+ "nullable": true,+ "description": "Filter by status: 'active' or 'paused'",+ "title": "Status"+ },+ "description": "Filter by status: 'active' or 'paused'"+ },+ {+ "name": "search",+ "in": "query",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Search by workflow title or schedule name",+ "title": "Search"+ },+ "description": "Search by workflow title or schedule name"+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OrganizationScheduleListResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "list_organization_schedules"+ }+ },+ "/v1/workflows/{workflow_permanent_id}/schedules": {+ "post": {+ "tags": [+ "Schedules"+ ],+ "summary": "Create a schedule for a workflow",+ "operationId": "schedules_create",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleUpsertRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "create_workflow_schedule"+ },+ "get": {+ "tags": [+ "Schedules"+ ],+ "summary": "List schedules for a workflow",+ "operationId": "schedules_list",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleListResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "list_workflow_schedules"+ }+ },+ "/v1/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}": {+ "get": {+ "tags": [+ "Schedules"+ ],+ "summary": "Get a schedule by ID",+ "operationId": "schedules_get",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "get_workflow_schedule"+ },+ "put": {+ "tags": [+ "Schedules"+ ],+ "summary": "Update a schedule",+ "operationId": "schedules_update",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleUpsertRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "update_workflow_schedule"+ },+ "delete": {+ "tags": [+ "Schedules"+ ],+ "summary": "Delete a schedule",+ "operationId": "schedules_delete",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "delete_workflow_schedule_route"+ }+ },+ "/v1/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}/enable": {+ "post": {+ "tags": [+ "Schedules"+ ],+ "summary": "Enable a schedule",+ "operationId": "schedules_enable",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "enable_workflow_schedule"+ }+ },+ "/v1/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}/disable": {+ "post": {+ "tags": [+ "Schedules"+ ],+ "summary": "Disable a schedule",+ "operationId": "schedules_disable",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true,+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-group-name": "agent",+ "x-fern-sdk-method-name": "disable_workflow_schedule"+ }}},"components": {@@ -3963,8 +4512,8 @@"properties": {"file": {"type": "string",- "format": "binary",- "title": "File"+ "title": "File",+ "format": "binary"}},"type": "object",@@ -10450,8 +10999,8 @@},"engine": {"$ref": "#/components/schemas/RunEngine",- "description": "\nThe engine that powers the agent task. The default value is `skyvern-2.0`, the latest Skyvern agent that performs pretty well with complex and multi-step tasks. `skyvern-1.0` is good for simple tasks like filling a form, or searching for information on Google. The `openai-cua` engine uses OpenAI's CUA model. The `anthropic-cua` uses Anthropic's Claude Sonnet 3.7 model with the computer use tool.\n",- "default": "skyvern-2.0"+ "description": "\nThe engine that powers the agent task. The default value is `skyvern-1.0`, which is good for simple tasks like filling a form, or searching for information on Google. `skyvern-2.0` is the latest Skyvern agent that performs well with complex and multi-step tasks. The `openai-cua` engine uses OpenAI's CUA model. The `anthropic-cua` uses Anthropic's Claude Sonnet 3.7 model with the computer use tool.\n",+ "default": "skyvern-1.0"},"title": {"type": "string",@@ -13715,6 +14264,280 @@"azure_vault"],"title": "CredentialType"+ },+ "DeleteScheduleResponse": {+ "properties": {+ "ok": {+ "type": "boolean",+ "title": "Ok"+ }+ },+ "type": "object",+ "required": [+ "ok"+ ],+ "title": "DeleteScheduleResponse"+ },+ "OrganizationScheduleItem": {+ "properties": {+ "workflow_schedule_id": {+ "type": "string",+ "title": "Workflow Schedule Id"+ },+ "organization_id": {+ "type": "string",+ "title": "Organization Id"+ },+ "workflow_permanent_id": {+ "type": "string",+ "title": "Workflow Permanent Id"+ },+ "workflow_title": {+ "type": "string",+ "title": "Workflow Title"+ },+ "cron_expression": {+ "type": "string",+ "title": "Cron Expression"+ },+ "timezone": {+ "type": "string",+ "title": "Timezone"+ },+ "enabled": {+ "type": "boolean",+ "title": "Enabled"+ },+ "parameters": {+ "additionalProperties": true,+ "type": "object",+ "nullable": true,+ "title": "Parameters"+ },+ "name": {+ "type": "string",+ "nullable": true,+ "title": "Name"+ },+ "description": {+ "type": "string",+ "nullable": true,+ "title": "Description"+ },+ "next_run": {+ "type": "string",+ "format": "date-time",+ "nullable": true,+ "title": "Next Run"+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ },+ "modified_at": {+ "type": "string",+ "format": "date-time",+ "title": "Modified At"+ }+ },+ "type": "object",+ "required": [+ "workflow_schedule_id",+ "organization_id",+ "workflow_permanent_id",+ "workflow_title",+ "cron_expression",+ "timezone",+ "enabled",+ "created_at",+ "modified_at"+ ],+ "title": "OrganizationScheduleItem",+ "description": "Compact schedule projection for the org-wide list endpoint."+ },+ "OrganizationScheduleListResponse": {+ "properties": {+ "schedules": {+ "items": {+ "$ref": "#/components/schemas/OrganizationScheduleItem"+ },+ "type": "array",+ "title": "Schedules"+ },+ "total_count": {+ "type": "integer",+ "title": "Total Count"+ },+ "page": {+ "type": "integer",+ "title": "Page"+ },+ "page_size": {+ "type": "integer",+ "title": "Page Size"+ }+ },+ "type": "object",+ "required": [+ "schedules",+ "total_count",+ "page",+ "page_size"+ ],+ "title": "OrganizationScheduleListResponse"+ },+ "WorkflowSchedule": {+ "properties": {+ "workflow_schedule_id": {+ "type": "string",+ "title": "Workflow Schedule Id"+ },+ "organization_id": {+ "type": "string",+ "title": "Organization Id"+ },+ "workflow_permanent_id": {+ "type": "string",+ "title": "Workflow Permanent Id"+ },+ "cron_expression": {+ "type": "string",+ "title": "Cron Expression"+ },+ "timezone": {+ "type": "string",+ "title": "Timezone"+ },+ "enabled": {+ "type": "boolean",+ "title": "Enabled"+ },+ "parameters": {+ "additionalProperties": true,+ "type": "object",+ "nullable": true,+ "title": "Parameters"+ },+ "temporal_schedule_id": {+ "type": "string",+ "nullable": true,+ "title": "Temporal Schedule Id"+ },+ "name": {+ "type": "string",+ "nullable": true,+ "title": "Name"+ },+ "description": {+ "type": "string",+ "nullable": true,+ "title": "Description"+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ },+ "modified_at": {+ "type": "string",+ "format": "date-time",+ "title": "Modified At"+ },+ "deleted_at": {+ "type": "string",+ "format": "date-time",+ "nullable": true,+ "title": "Deleted At"+ }+ },+ "type": "object",+ "required": [+ "workflow_schedule_id",+ "organization_id",+ "workflow_permanent_id",+ "cron_expression",+ "timezone",+ "enabled",+ "created_at",+ "modified_at"+ ],+ "title": "WorkflowSchedule"+ },+ "WorkflowScheduleListResponse": {+ "properties": {+ "schedules": {+ "items": {+ "$ref": "#/components/schemas/WorkflowSchedule"+ },+ "type": "array",+ "title": "Schedules"+ }+ },+ "type": "object",+ "required": [+ "schedules"+ ],+ "title": "WorkflowScheduleListResponse"+ },+ "WorkflowScheduleResponse": {+ "properties": {+ "schedule": {+ "$ref": "#/components/schemas/WorkflowSchedule"+ },+ "next_runs": {+ "items": {+ "type": "string",+ "format": "date-time"+ },+ "type": "array",+ "title": "Next Runs"+ }+ },+ "type": "object",+ "required": [+ "schedule"+ ],+ "title": "WorkflowScheduleResponse"+ },+ "WorkflowScheduleUpsertRequest": {+ "properties": {+ "cron_expression": {+ "type": "string",+ "title": "Cron Expression"+ },+ "timezone": {+ "type": "string",+ "title": "Timezone"+ },+ "enabled": {+ "type": "boolean",+ "title": "Enabled",+ "default": true+ },+ "parameters": {+ "additionalProperties": true,+ "type": "object",+ "nullable": true,+ "title": "Parameters"+ },+ "name": {+ "type": "string",+ "nullable": true,+ "title": "Name"+ },+ "description": {+ "type": "string",+ "nullable": true,+ "title": "Description"+ }+ },+ "type": "object",+ "required": [+ "cron_expression",+ "timezone"+ ],+ "title": "WorkflowScheduleUpsertRequest"}}},@@ -13729,4 +14552,4 @@"url": "http://localhost:8000"}]-}\ No newline at end of file+}diff --git a/docs/running-automations/run-a-task.mdx b/docs/running-automations/run-a-task.mdxindex fe4fdf523..4eceecadd 100644--- a/docs/running-automations/run-a-task.mdx+++ b/docs/running-automations/run-a-task.mdx@@ -271,7 +271,7 @@ The response from polling (`get_run`) and webhooks have slightly different struc"run_request": {"prompt": "Get the title of the top post","url": "https://news.ycombinator.com/",- "engine": "skyvern-2.0"+ "engine": "skyvern-1.0"}}```diff --git a/docs/running-automations/task-parameters.mdx b/docs/running-automations/task-parameters.mdxindex 24e4a04ee..6c5a67a5b 100644--- a/docs/running-automations/task-parameters.mdx+++ b/docs/running-automations/task-parameters.mdx@@ -125,14 +125,14 @@ The AI engine that powers the task. These are not iterations—they're suited fo| Engine | Description ||--------|-------------|-| `skyvern-2.0` | **Default.** Multi-objective, flexible, handles complex multi-step tasks. 85.85% on WebVoyager benchmark. Slower and more expensive. |-| `skyvern-1.0` | Single objective, precise, faster, cheaper. Best for simple tasks like form filling or single-page extraction. |+| `skyvern-1.0` | **Default.** Single objective, precise, faster, cheaper. Best for simple tasks like form filling or single-page extraction. |+| `skyvern-2.0` | Multi-objective, flexible, handles complex multi-step tasks. 85.85% on WebVoyager benchmark. Slower and more expensive. || `openai-cua` | OpenAI's Computer Use Agent || `anthropic-cua` | Anthropic Claude Sonnet with computer use || `ui-tars` | UI-TARS model (Seed1.5-VL) via Doubao API |<Tip>-Use `skyvern-1.0` when you have a clear, single goal and want faster, cheaper execution. Use `skyvern-2.0` when the task requires flexibility or multiple steps.+The default engine `skyvern-1.0` works well for clear, single-goal tasks with faster, cheaper execution. Switch to `skyvern-2.0` when the task requires flexibility or multiple steps.</Tip><CodeGroup>diff --git a/docs/snippets/core-concepts-content.mdx b/docs/snippets/core-concepts-content.mdxindex 5f0cf0e67..1847e792c 100644--- a/docs/snippets/core-concepts-content.mdx+++ b/docs/snippets/core-concepts-content.mdx@@ -360,8 +360,8 @@ Skyvern supports multiple AI engines for task execution:| Engine | Description ||--------|-------------|-| `skyvern-2.0` | Latest Skyvern model (default, recommended) |-| `skyvern-1.0` | Previous Skyvern model |+| `skyvern-1.0` | Default Skyvern model — fast, precise, ideal for simple tasks |+| `skyvern-2.0` | Latest Skyvern model — flexible, handles complex multi-step tasks || `openai-cua` | OpenAI Computer Use Agent || `anthropic-cua` | Anthropic Computer Use Agent || `ui-tars` | UI-TARS model |diff --git a/docs/ts-sdk-reference/complete-reference.mdx b/docs/ts-sdk-reference/complete-reference.mdxindex 5831db259..9cc63312b 100644--- a/docs/ts-sdk-reference/complete-reference.mdx+++ b/docs/ts-sdk-reference/complete-reference.mdx@@ -97,7 +97,7 @@ const result = await skyvern.runTask({body: {prompt: string, // Required. Natural language instructions.url?: string, // Starting page URL.- engine?: RunEngine, // "skyvern_v2" (default), "skyvern_v1", "openai_cua", "anthropic_cua", "ui_tars"+ engine?: RunEngine, // "skyvern_v1" (default), "skyvern_v2", "openai_cua", "anthropic_cua", "ui_tars"max_steps?: number, // Cap AI steps to limit cost.data_extraction_schema?: Record<string, unknown> | string, // JSON Schema for output.browser_session_id?: string, // Run in existing session.diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex ee79d1365..31535ddff 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -4015,21 +4015,39 @@ class WorkflowService:failure_category=failure_category,)- async def mark_workflow_run_as_canceled(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:+ async def mark_workflow_run_as_canceled(self, workflow_run_id: str) -> WorkflowRun:+ """Cancel a workflow run, rejecting the transition if the run has already+ reached a terminal state.++ Previously this wrote ``canceled`` unconditionally, which let a late+ cancel call (for example the extraction-block retry path in+ ``_handle_block_result_status`` racing the run's own finalization) clobber+ a prior ``completed``/``failed``/``terminated`` status and inflate the+ cancel rate. SKY-9188.+ """LOG.info(f"Marking workflow run {workflow_run_id} as canceled",workflow_run_id=workflow_run_id,workflow_status="canceled",)- # Add workflow canceled tag to trace- otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.canceled)+ updated = await self.mark_workflow_run_as_canceled_if_not_final(+ workflow_run_id=workflow_run_id,+ )+ if updated is not None:+ return updated- return await self._update_workflow_run_status(+ current = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id=workflow_run_id,- status=WorkflowRunStatus.canceled,- run_with=run_with,)+ if current is None:+ raise WorkflowRunNotFound(workflow_run_id)+ LOG.info(+ "Rejecting cancel: workflow run already in terminal state",+ workflow_run_id=workflow_run_id,+ workflow_run_status=current.status,+ )+ return currentasync def mark_workflow_run_as_canceled_if_not_final(self,@@ -4054,9 +4072,35 @@ class WorkflowService:)otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.canceled)- # Match the side effects of ``_update_workflow_run_status`` on a terminal- # transition: clear the per-run extraction cache.+ # Mirror ``_update_workflow_run_status`` side effects on a terminal transition:+ # extraction-cache clear, duration-metrics log, and task_runs write-through.extraction_cache.clear_workflow_run(workflow_run_id)++ start_time = (+ updated.started_at.replace(tzinfo=UTC) if updated.started_at else updated.created_at.replace(tzinfo=UTC)+ )+ queued_seconds = (start_time - updated.created_at.replace(tzinfo=UTC)).total_seconds()+ duration_seconds = (datetime.now(UTC) - start_time).total_seconds()+ LOG.info(+ "Workflow run duration metrics",+ workflow_run_id=workflow_run_id,+ workflow_id=updated.workflow_id,+ queued_seconds=queued_seconds,+ duration_seconds=duration_seconds,+ workflow_run_status=updated.status,+ organization_id=updated.organization_id,+ run_with=updated.run_with,+ ai_fallback=updated.ai_fallback,+ trigger_type=updated.trigger_type,+ workflow_schedule_id=updated.workflow_schedule_id,+ )++ bg = asyncio.create_task(+ self._sync_task_run_from_workflow_run(updated, workflow_run_id, WorkflowRunStatus.canceled),+ )+ self._background_tasks.add(bg)+ bg.add_done_callback(self._background_tasks.discard)+return updatedasync def mark_workflow_run_as_timed_out(diff --git a/tests/unit/test_workflow_service_cancel.py b/tests/unit/test_workflow_service_cancel.pyindex edec58410..a6d1596b7 100644--- a/tests/unit/test_workflow_service_cancel.py+++ b/tests/unit/test_workflow_service_cancel.py@@ -1,8 +1,11 @@"""Tests for cancellation / webhook-tolerance helpers on WorkflowService.- ``mark_workflow_run_as_canceled_if_not_final`` delegates to the conditional- DB update and is a no-op when the DB reports no row was affected (the row- was already in a terminal state).+ DB update and is a no-op when the DB reports no row was affected - either+ because the row was already in a terminal state or because no row with that+ id exists.+- ``mark_workflow_run_as_canceled`` rejects transitions to ``canceled`` when+ the run has already reached a terminal state (SKY-9188).- ``execute_workflow_webhook`` returns cleanly when the workflow row has beensoft-deleted mid-run — it must not raise ``WorkflowNotFound`` from thecleanup path.@@ -14,11 +17,12 @@from __future__ import annotationsimport asyncio+from datetime import UTC, datetime, timedeltafrom unittest.mock import AsyncMock, MagicMockimport pytest-from skyvern.exceptions import WorkflowNotFound+from skyvern.exceptions import WorkflowNotFound, WorkflowRunNotFoundfrom skyvern.forge import appfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus@@ -45,6 +49,135 @@ async def test_mark_canceled_if_not_final_returns_conditional_result()+def _make_updated_row() -> MagicMock:+ row = MagicMock()+ row.status = WorkflowRunStatus.canceled+ row.created_at = datetime.now(UTC) - timedelta(seconds=30)+ row.started_at = datetime.now(UTC) - timedelta(seconds=20)+ row.workflow_id = "wf_abc"+ row.organization_id = "org_abc"+ row.run_with = None+ row.ai_fallback = False+ row.trigger_type = None+ row.workflow_schedule_id = None+ return row+++async def test_mark_canceled_if_not_final_logs_duration_metrics(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Terminal-transition parity with ``_update_workflow_run_status``: a+ successful conditional cancel must emit the ``Workflow run duration metrics``+ log with the same structured fields, so the metric stays comparable across+ statuses.+ """+ from skyvern.forge.sdk.workflow import service as service_module+ from skyvern.forge.sdk.workflow.service import WorkflowService++ updated_row = _make_updated_row()+ monkeypatch.setattr(+ app.DATABASE.workflow_runs,+ "update_workflow_run_if_not_final",+ AsyncMock(return_value=updated_row),+ )+ monkeypatch.setattr(+ WorkflowService,+ "_sync_task_run_from_workflow_run",+ AsyncMock(return_value=None),+ )++ info_calls: list[tuple[str, dict]] = []++ def fake_info(event: str, **kwargs: object) -> None:+ info_calls.append((event, dict(kwargs)))++ monkeypatch.setattr(service_module.LOG, "info", fake_info)++ svc = WorkflowService()+ result = await svc.mark_workflow_run_as_canceled_if_not_final(workflow_run_id="wr_live")++ assert result is updated_row+ metrics_events = [kwargs for event, kwargs in info_calls if event == "Workflow run duration metrics"]+ assert len(metrics_events) == 1+ metrics = metrics_events[0]+ assert metrics["workflow_run_id"] == "wr_live"+ assert metrics["workflow_id"] == "wf_abc"+ assert metrics["organization_id"] == "org_abc"+ assert metrics["workflow_run_status"] == WorkflowRunStatus.canceled+ assert metrics["queued_seconds"] == pytest.approx(10.0, abs=1.0)+ assert metrics["duration_seconds"] == pytest.approx(20.0, abs=1.0)+++async def test_mark_canceled_if_not_final_syncs_task_runs(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Terminal-transition parity: a successful conditional cancel must spawn+ the ``_sync_task_run_from_workflow_run`` write-through so downstream+ consumers reading ``task_runs`` see the cancel event.+ """+ from skyvern.forge.sdk.workflow.service import WorkflowService++ updated_row = _make_updated_row()+ monkeypatch.setattr(+ app.DATABASE.workflow_runs,+ "update_workflow_run_if_not_final",+ AsyncMock(return_value=updated_row),+ )+ sync_mock = AsyncMock(return_value=None)+ monkeypatch.setattr(WorkflowService, "_sync_task_run_from_workflow_run", sync_mock)++ svc = WorkflowService()+ await svc.mark_workflow_run_as_canceled_if_not_final(workflow_run_id="wr_sync")++ # Let the fire-and-forget background task drain.+ for _ in range(3):+ await asyncio.sleep(0)++ sync_mock.assert_awaited_once()+ call_args = sync_mock.await_args+ assert call_args is not None+ assert call_args.args[0] is updated_row+ assert call_args.args[1] == "wr_sync"+ assert call_args.args[2] == WorkflowRunStatus.canceled+++async def test_mark_canceled_if_not_final_skips_side_effects_on_terminal_row(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the conditional update returns ``None`` (row already terminal),+ neither the duration-metrics log nor the task_runs sync may fire — the+ terminal status's own ``_update_workflow_run_status`` call already emitted+ them.+ """+ from skyvern.forge.sdk.workflow import service as service_module+ from skyvern.forge.sdk.workflow.service import WorkflowService++ monkeypatch.setattr(+ app.DATABASE.workflow_runs,+ "update_workflow_run_if_not_final",+ AsyncMock(return_value=None),+ )+ sync_mock = AsyncMock(side_effect=AssertionError("_sync_task_run_from_workflow_run must not run on no-op"))+ monkeypatch.setattr(WorkflowService, "_sync_task_run_from_workflow_run", sync_mock)++ info_calls: list[str] = []++ def fake_info(event: str, **kwargs: object) -> None:+ info_calls.append(event)++ monkeypatch.setattr(service_module.LOG, "info", fake_info)++ svc = WorkflowService()+ result = await svc.mark_workflow_run_as_canceled_if_not_final(workflow_run_id="wr_already_done")++ assert result is None+ assert "Workflow run duration metrics" not in info_calls+ sync_mock.assert_not_awaited()++@pytest.mark.asyncioasync def test_mark_canceled_if_not_final_is_noop_on_terminal_row(monkeypatch: pytest.MonkeyPatch,@@ -63,6 +196,102 @@ async def test_mark_canceled_if_not_final_is_noop_on_terminal_row(delegate.assert_awaited_once()+ "terminal_status",+ [+ WorkflowRunStatus.completed,+ WorkflowRunStatus.failed,+ WorkflowRunStatus.terminated,+ WorkflowRunStatus.timed_out,+ WorkflowRunStatus.canceled,+ ],+)+async def test_mark_canceled_rejects_transition_on_terminal_row(+ monkeypatch: pytest.MonkeyPatch,+ terminal_status: WorkflowRunStatus,+) -> None:+ """SKY-9188: ``mark_workflow_run_as_canceled`` must not overwrite a+ finalized status. The underlying conditional update returns ``None`` for+ terminal rows; the service helper must propagate the existing row back to+ callers without writing ``canceled``.+ """+ from skyvern.forge.sdk.workflow.service import WorkflowService++ existing_row = MagicMock()+ existing_row.status = terminal_status++ conditional_update = AsyncMock(return_value=None)+ monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", conditional_update)+ get_workflow_run = AsyncMock(return_value=existing_row)+ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run", get_workflow_run)+ # A guard that accidentally falls through to the unconditional write would+ # call ``update_workflow_run`` — fail loudly if that happens.+ unconditional_update = AsyncMock(side_effect=AssertionError("unconditional update_workflow_run must not be called"))+ monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run", unconditional_update)++ svc = WorkflowService()+ result = await svc.mark_workflow_run_as_canceled(workflow_run_id="wr_final")++ assert result is existing_row+ assert result.status == terminal_status+ conditional_update.assert_awaited_once_with(+ workflow_run_id="wr_final",+ status=WorkflowRunStatus.canceled,+ )+ unconditional_update.assert_not_called()+++async def test_mark_canceled_writes_when_row_is_non_terminal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """SKY-9188: a non-terminal run still transitions to ``canceled`` through+ the conditional update path.+ """+ from skyvern.forge.sdk.workflow.service import WorkflowService++ canceled_row = MagicMock()+ canceled_row.status = WorkflowRunStatus.canceled++ conditional_update = AsyncMock(return_value=canceled_row)+ monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", conditional_update)+ get_workflow_run = AsyncMock(side_effect=AssertionError("get_workflow_run must not be called on the happy path"))+ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run", get_workflow_run)++ svc = WorkflowService()+ result = await svc.mark_workflow_run_as_canceled(workflow_run_id="wr_running")++ assert result is canceled_row+ conditional_update.assert_awaited_once_with(+ workflow_run_id="wr_running",+ status=WorkflowRunStatus.canceled,+ )+ get_workflow_run.assert_not_called()+++async def test_mark_canceled_raises_when_row_missing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the conditional update rejects (returns ``None``) AND the row no+ longer exists, there is no sensible ``WorkflowRun`` to return — raise+ ``WorkflowRunNotFound`` rather than silently pretending the cancel+ succeeded.+ """+ from skyvern.forge.sdk.workflow.service import WorkflowService++ conditional_update = AsyncMock(return_value=None)+ monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", conditional_update)+ get_workflow_run = AsyncMock(return_value=None)+ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run", get_workflow_run)++ svc = WorkflowService()++ with pytest.raises(WorkflowRunNotFound):+ await svc.mark_workflow_run_as_canceled(workflow_run_id="wr_missing")++@pytest.mark.asyncioasync def test_execute_workflow_webhook_tolerates_soft_deleted_workflow(monkeypatch: pytest.MonkeyPatch,