Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix failure_category gaps: UNKNOWN fallback, workflow inheritance, observability (SKY-8469) (#5290)
LawyZhengc4251ff70cdc
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.jsonindex 897c7054b..d263724df 100644--- a/fern/openapi/skyvern_openapi.json+++ b/fern/openapi/skyvern_openapi.json@@ -2444,6 +2444,24 @@},"description": "Number of items per page"},+ {+ "name": "vault_type",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/CredentialVaultType"+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter credentials by vault type (e.g. 'custom', 'bitwarden', 'azure_vault')",+ "title": "Vault Type"+ },+ "description": "Filter credentials by vault type (e.g. 'custom', 'bitwarden', 'azure_vault')"+ },{"name": "x-api-key","in": "header",@@ -13751,7 +13769,7 @@}],"title": "Run With",- "description": "Whether to run the task with agent or code.",+ "description": "Whether to run the task with agent or code. Null means use the default.","examples": ["agent","code"@@ -16076,15 +16094,9 @@"title": "Extra Http Headers"},"run_with": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "Run With"+ "type": "string",+ "title": "Run With",+ "default": "agent"},"ai_fallback": {"type": "boolean",@@ -16327,15 +16339,9 @@"default": "published"},"run_with": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "Run With"+ "type": "string",+ "title": "Run With",+ "default": "agent"},"ai_fallback": {"type": "boolean",@@ -17133,6 +17139,21 @@],"title": "Failure Reason"},+ "failure_category": {+ "anyOf": [+ {+ "items": {+ "additionalProperties": true,+ "type": "object"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Failure Category"+ },"parent_workflow_run_id": {"anyOf": [{@@ -17964,7 +17985,7 @@}],"title": "Run With",- "description": "Whether to run the workflow with agent or code.",+ "description": "Whether to run the workflow with agent or code. Null inherits from the workflow setting.","examples": ["agent","code"@@ -18238,16 +18259,10 @@"description": "Type of run - always workflow_run for workflow runs"},"run_with": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],+ "type": "string","title": "Run With","description": "Whether the workflow run was executed with agent or code",+ "default": "agent","examples": ["agent","code"diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 0b8fe7b7b..e9fce9db3 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -894,7 +894,18 @@ class ForgeAgent:)# Update task status first- failure_category = classify_from_failure_reason(reason, exception=exception)+ failure_category = classify_from_failure_reason(reason, exception=exception, fallback_to_unknown=True)+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="code_level",+ failure_category_path="exception",+ )await self.update_task(task,status=TaskStatus.failed,@@ -4068,6 +4079,17 @@ class ForgeAgent:if persisted_action.errors:failure_reason = "; ".join(error.reasoning for error in persisted_action.errors)failure_category = persisted_action.failure_categories or classify_from_failure_reason(failure_reason)+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="terminated",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="llm" if persisted_action.failure_categories else "code_level",+ failure_category_path="terminate_check_goal",+ )await self.update_task(task,status=TaskStatus.terminated,@@ -4163,7 +4185,18 @@ class ForgeAgent:error.model_dump() for error in generated_failure_reason.errors]failure_category = generated_failure_reason.failure_categories or classify_from_failure_reason(- failure_reason+ failure_reason, fallback_to_unknown=True+ )+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="llm" if generated_failure_reason.failure_categories else "code_level",+ failure_category_path="max_steps",)await self._cancel_speculative_step(next_step)@@ -4232,7 +4265,20 @@ class ForgeAgent:f"Max retries per step ({max_retries_per_step}) exceeded."f" Possible failure reasons: {failure_response.reasoning}")- failure_category = failure_response.failure_categories or classify_from_failure_reason(failure_reason)+ failure_category = failure_response.failure_categories or classify_from_failure_reason(+ failure_reason, fallback_to_unknown=True+ )+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="llm" if failure_response.failure_categories else "code_level",+ failure_category_path="max_retries",+ )await self.update_task(task,TaskStatus.failed,@@ -4581,6 +4627,17 @@ class ForgeAgent:last_step = await self.update_step(step, is_last=True)failure_reason = await self.get_failure_reason_for_task(task)failure_category = classify_from_failure_reason(failure_reason)+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="terminated",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="code_level",+ failure_category_path="terminate_extract_action",+ )await self.update_task(task,status=TaskStatus.terminated,@@ -4633,7 +4690,18 @@ class ForgeAgent:error.model_dump() for error in generated_failure_reason.errors]failure_category = generated_failure_reason.failure_categories or classify_from_failure_reason(- failure_reason+ failure_reason, fallback_to_unknown=True+ )+ LOG.info(+ "Task failure classified",+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=task.organization_id,+ task_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="llm" if generated_failure_reason.failure_categories else "code_level",+ failure_category_path="max_steps",)await self.update_task(diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.pyindex 2a5e40b27..a8dbd6a21 100644--- a/skyvern/forge/failure_classifier.py+++ b/skyvern/forge/failure_classifier.py@@ -4,11 +4,18 @@ from __future__ import annotationsdef classify_from_failure_reason(failure_reason: str | None,exception: Exception | None = None,+ fallback_to_unknown: bool = False,) -> list[dict] | None:"""Classify failure from failure_reason text and/or exception type.Returns list of categories sorted by confidence, or None if no classification.+ When ``fallback_to_unknown`` is True and no keywords match, returns a single+ UNKNOWN category instead of None. Use True for paths that are *always* failures+ (exception, max_steps, max_retries). Use False (the default) for terminate paths+ where the absence of a classification may simply mean the termination was+ user-guided / expected.+Categories:ANTI_BOT_DETECTION, BROWSER_ERROR, NAVIGATION_FAILURE, PAGE_LOAD_TIMEOUT,AUTH_FAILURE, LLM_ERROR, CREDENTIAL_ERROR, DATA_EXTRACTION_FAILURE,@@ -161,6 +168,8 @@ def classify_from_failure_reason()if not categories:+ if fallback_to_unknown:+ return [{"category": "UNKNOWN", "confidence_float": 0.5, "reasoning": "No keyword match found"}]return None# Sort by confidence descendingdiff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.pyindex e80d26559..584cde0b7 100644--- a/skyvern/forge/sdk/schemas/tasks.py+++ b/skyvern/forge/sdk/schemas/tasks.py@@ -401,6 +401,7 @@ class TaskOutput(BaseModel):extracted_information: list | dict[str, Any] | str | None = Nonefailure_reason: str | None = Noneerrors: list[dict[str, Any]] = []+ failure_category: list[dict[str, Any]] | None = Nonedownloaded_files: list[FileInfo] | None = Nonedownloaded_file_urls: list[str] | None = None # For backward compatibilitytask_screenshots: list[str] | None = None@@ -424,6 +425,7 @@ class TaskOutput(BaseModel):extracted_information=task.extracted_information,failure_reason=task.failure_reason,errors=task.errors,+ failure_category=task.failure_category,downloaded_files=downloaded_files,downloaded_file_urls=downloaded_file_urls,task_screenshot_artifact_ids=task_screenshot_artifact_ids,diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 7a6af26fb..444babdbb 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -4638,6 +4638,7 @@ class TaskV2Block(Block):"summary": task_v2.summary,"extracted_information": result_dict,"failure_reason": failure_reason,+ "failure_category": task_v2.failure_category,"downloaded_files": [fi.model_dump() for fi in downloaded_files],"downloaded_file_urls": [fi.url for fi in downloaded_files],"task_screenshot_artifact_ids": [a.artifact_id for a in task_screenshot_artifacts],@@ -4647,7 +4648,7 @@ class TaskV2Block(Block):return await self.build_block_result(success=success or self.continue_on_failure,failure_reason=failure_reason,- output_parameter_value=result_dict,+ output_parameter_value=task_v2_output,status=block_status,workflow_run_block_id=workflow_run_block_id,organization_id=organization_id,diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 5e1f41189..5e423de6f 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -2530,8 +2530,15 @@ class WorkflowService:)if not block.continue_on_failure:failure_reason = f"{block.block_type} block failed. failure reason: {block_result.failure_reason}"+ task_failure_category = (+ block_result.output_parameter_value.get("failure_category")+ if isinstance(block_result.output_parameter_value, dict)+ else None+ )workflow_run = await self.mark_workflow_run_as_failed(- workflow_run_id=workflow_run_id, failure_reason=failure_reason+ workflow_run_id=workflow_run_id,+ failure_reason=failure_reason,+ failure_category=task_failure_category,)return workflow_run, True@@ -2560,8 +2567,15 @@ class WorkflowService:if not block.continue_on_failure:failure_reason = f"{block.block_type} block terminated. Reason: {block_result.failure_reason}"+ task_failure_category = (+ block_result.output_parameter_value.get("failure_category")+ if isinstance(block_result.output_parameter_value, dict)+ else None+ )workflow_run = await self.mark_workflow_run_as_terminated(- workflow_run_id=workflow_run_id, failure_reason=failure_reason+ workflow_run_id=workflow_run_id,+ failure_reason=failure_reason,+ failure_category=task_failure_category,)return workflow_run, True@@ -2590,8 +2604,15 @@ class WorkflowService:if not block.continue_on_failure:failure_reason = f"{block.block_type} block timed out. Reason: {block_result.failure_reason}"+ task_failure_category = (+ block_result.output_parameter_value.get("failure_category")+ if isinstance(block_result.output_parameter_value, dict)+ else None+ )workflow_run = await self.mark_workflow_run_as_failed(- workflow_run_id=workflow_run_id, failure_reason=failure_reason+ workflow_run_id=workflow_run_id,+ failure_reason=failure_reason,+ failure_category=task_failure_category,)return workflow_run, True@@ -3667,8 +3688,18 @@ class WorkflowService:otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.failed)# Auto-classify if no explicit category provided+ failure_category_source = "inherited_from_task" if failure_category is not None else "code_level"if failure_category is None:- failure_category = classify_from_failure_reason(failure_reason)+ failure_category = classify_from_failure_reason(failure_reason, fallback_to_unknown=True)++ LOG.info(+ "Workflow run failure classified",+ workflow_run_id=workflow_run_id,+ workflow_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source=failure_category_source,+ )return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,@@ -3716,10 +3747,22 @@ class WorkflowService:# Add workflow terminated tag to traceotel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.terminated)- # Auto-classify if no explicit category provided+ # Auto-classify if no explicit category provided.+ # Intentionally uses fallback_to_unknown=False (the default) — terminated workflows+ # may be user-guided (e.g. terminate_criterion matched), so None is acceptable.+ failure_category_source = "inherited_from_task" if failure_category is not None else "code_level"if failure_category is None:failure_category = classify_from_failure_reason(failure_reason)+ LOG.info(+ "Workflow run failure classified",+ workflow_run_id=workflow_run_id,+ workflow_status="terminated",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source=failure_category_source,+ )+return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,status=WorkflowRunStatus.terminated,@@ -3759,7 +3802,15 @@ class WorkflowService:# Add workflow timed out tag to traceotel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.timed_out)- failure_category = classify_from_failure_reason(failure_reason)+ failure_category = classify_from_failure_reason(failure_reason, fallback_to_unknown=True)+ LOG.info(+ "Workflow run failure classified",+ workflow_run_id=workflow_run_id,+ workflow_status="timed_out",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="code_level",+ )return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.pyindex d7f16a31a..3f275bc14 100644--- a/skyvern/services/task_v2_service.py+++ b/skyvern/services/task_v2_service.py@@ -215,6 +215,17 @@ async def _handle_task_v2_termination()resolved_failure_category = failure_category or classify_from_failure_reason(termination_reason)+ LOG.info(+ "Task failure classified",+ task_v2_id=task_v2_id,+ workflow_run_id=workflow_run_id,+ organization_id=organization_id,+ task_status="terminated",+ failure_category=resolved_failure_category,+ primary_failure_category=resolved_failure_category[0].get("category") if resolved_failure_category else None,+ failure_category_source="llm" if failure_category else "code_level",+ failure_category_path="v2_terminate",+ )task_v2 = await mark_task_v2_as_terminated(task_v2_id=task_v2_id,workflow_run_id=workflow_run_id,@@ -1124,7 +1135,20 @@ async def run_task_v2_helper(f' "x-max-steps-override" header with your desired number'f" of steps in the API request.")- failure_category = llm_failure_categories or classify_from_failure_reason(full_failure_reason)+ failure_category = llm_failure_categories or classify_from_failure_reason(+ full_failure_reason, fallback_to_unknown=True+ )+ LOG.info(+ "Task failure classified",+ task_v2_id=task_v2_id,+ workflow_run_id=workflow_run_id,+ organization_id=organization_id,+ task_status="failed",+ failure_category=failure_category,+ primary_failure_category=failure_category[0].get("category") if failure_category else None,+ failure_category_source="llm" if llm_failure_categories else "code_level",+ failure_category_path="v2_max_steps",+ )task_v2 = await mark_task_v2_as_failed(task_v2_id=task_v2_id,workflow_run_id=workflow_run_id,@@ -1135,16 +1159,34 @@ async def run_task_v2_helper(return workflow, workflow_run, task_v2else:# Loop completed without early exit - task exceeded max iterations+ max_iterations_failure_reason = f"Task exceeded maximum of {DEFAULT_MAX_ITERATIONS} planning iterations. Consider simplifying the task or breaking it into smaller steps."+ max_iterations_failure_category = classify_from_failure_reason(+ max_iterations_failure_reason, fallback_to_unknown=True+ )LOG.info("Task v2 failed - exceeded maximum iterations",max_iterations=DEFAULT_MAX_ITERATIONS,workflow_run_id=workflow_run_id,)+ LOG.info(+ "Task failure classified",+ task_v2_id=task_v2_id,+ workflow_run_id=workflow_run_id,+ organization_id=organization_id,+ task_status="failed",+ failure_category=max_iterations_failure_category,+ primary_failure_category=max_iterations_failure_category[0].get("category")+ if max_iterations_failure_category+ else None,+ failure_category_source="code_level",+ failure_category_path="v2_max_iterations",+ )task_v2 = await mark_task_v2_as_failed(task_v2_id=task_v2_id,workflow_run_id=workflow_run_id,- failure_reason=f"Task exceeded maximum of {DEFAULT_MAX_ITERATIONS} planning iterations. Consider simplifying the task or breaking it into smaller steps.",+ failure_reason=max_iterations_failure_reason,organization_id=organization_id,+ failure_category=max_iterations_failure_category,)return workflow, workflow_run, task_v2diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pyindex 714b2edaf..642383e33 100644--- a/tests/unit/test_failure_classifier.py+++ b/tests/unit/test_failure_classifier.py@@ -280,3 +280,36 @@ class TestExceptionOnlyClassification:result = classify_from_failure_reason(None, exception=BrowserCrashError())assert result is not Noneassert result[0]["category"] == "BROWSER_ERROR"+++class TestFallbackToUnknown:+ def test_unrecognized_with_fallback_returns_unknown(self) -> None:+ """When fallback_to_unknown=True and no keywords match, return UNKNOWN."""+ result = classify_from_failure_reason("The Resume/CV field is required but empty", fallback_to_unknown=True)+ assert result is not None+ assert len(result) == 1+ assert result[0]["category"] == "UNKNOWN"+ assert result[0]["confidence_float"] == 0.5++ def test_unrecognized_without_fallback_returns_none(self) -> None:+ """Default fallback_to_unknown=False preserves existing None behavior."""+ result = classify_from_failure_reason("The Resume/CV field is required but empty")+ assert result is None++ def test_none_input_with_fallback_returns_none(self) -> None:+ """None input returns None even with fallback_to_unknown=True (no data = no classification)."""+ result = classify_from_failure_reason(None, fallback_to_unknown=True)+ assert result is None++ def test_empty_input_with_fallback_returns_none(self) -> None:+ """Empty string returns None even with fallback_to_unknown=True."""+ result = classify_from_failure_reason("", fallback_to_unknown=True)+ assert result is None++ def test_keyword_match_ignores_fallback(self) -> None:+ """When keywords match, fallback_to_unknown has no effect on the result."""+ result_with = classify_from_failure_reason("browser crash detected", fallback_to_unknown=True)+ result_without = classify_from_failure_reason("browser crash detected", fallback_to_unknown=False)+ assert result_with is not None+ assert result_without is not None+ assert result_with[0]["category"] == result_without[0]["category"] == "BROWSER_ERROR"