Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add failure_category to tasks and workflow runs (SKY-8469) (#5254)
LawyZheng9d9ae67fe4ad
diff --git a/alembic/versions/2026_03_26_1805-6904dea5f7de_add_failure_category_to_tasks_workflow_.py b/alembic/versions/2026_03_26_1805-6904dea5f7de_add_failure_category_to_tasks_workflow_.pynew file mode 100644index 000000000..aac97e044--- /dev/null+++ b/alembic/versions/2026_03_26_1805-6904dea5f7de_add_failure_category_to_tasks_workflow_.py@@ -0,0 +1,35 @@+"""add_failure_category_to_tasks_workflow_runs_and_observer_cruises++Revision ID: 6904dea5f7de+Revises: 787109c06571+Create Date: 2026-03-26 18:05:11.582091+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "6904dea5f7de"+down_revision: Union[str, None] = "787109c06571"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.add_column("observer_cruises", sa.Column("failure_category", sa.JSON(), nullable=True))+ op.add_column("tasks", sa.Column("failure_category", sa.JSON(), nullable=True))+ op.add_column("workflow_runs", sa.Column("failure_category", sa.JSON(), nullable=True))+ # ### end Alembic commands ###+++def downgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.drop_column("workflow_runs", "failure_category")+ op.drop_column("tasks", "failure_category")+ op.drop_column("observer_cruises", "failure_category")+ # ### end Alembic commands ###diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 5eb78e324..0b8fe7b7b 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -66,6 +66,7 @@ from skyvern.exceptions import ()from skyvern.forge import appfrom skyvern.forge.async_operations import AgentPhase, AsyncOperationPool+from skyvern.forge.failure_classifier import classify_from_failure_reasonfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.aws import get_aws_clientfrom skyvern.forge.sdk.api.files import (@@ -734,7 +735,7 @@ class ForgeAgent:"Step cannot be executed, marking task as failed",exc_info=True,)- is_task_marked_as_failed = await self.fail_task(task, step, e.message, browser_state)+ is_task_marked_as_failed = await self.fail_task(task, step, e.message, browser_state, exception=e)if is_task_marked_as_failed:await self.clean_up_task(task=task,@@ -760,7 +761,7 @@ class ForgeAgent:url=e.url,)failure_reason = f"Failed to navigate to URL. URL:{e.url}, Error:{e.error_message}"- is_task_marked_as_failed = await self.fail_task(task, step, failure_reason, browser_state)+ is_task_marked_as_failed = await self.fail_task(task, step, failure_reason, browser_state, exception=e)if is_task_marked_as_failed:await self.clean_up_task(task=task,@@ -805,7 +806,7 @@ class ForgeAgent:step_order=step.order,step_retry=step.retry_index,)- await self.fail_task(task, step, e.message, browser_state)+ await self.fail_task(task, step, e.message, browser_state, exception=e)await self.clean_up_task(task=task,last_step=step,@@ -827,6 +828,7 @@ class ForgeAgent:sfe.reasonor "Skyvern failed to load the website. The page may have navigated unexpectedly or become unresponsive during analysis.",browser_state,+ exception=sfe,)await self.clean_up_task(task=task,@@ -836,13 +838,14 @@ class ForgeAgent:browser_session_id=browser_session_id,)return step, detailed_output, None- except MissingBrowserStatePage:+ except MissingBrowserStatePage as e:LOG.warning("Missing browser state page, marking the task as failed")await self.fail_task(task,step,"The browser does not have a valid page for skyvern to operate. This may be due to the website being empty or the browser crashing.",browser_state,+ exception=e,)await self.clean_up_task(task=task,@@ -857,7 +860,7 @@ class ForgeAgent:failure_reason = get_user_facing_exception_message(e)- is_task_marked_as_failed = await self.fail_task(task, step, failure_reason, browser_state)+ is_task_marked_as_failed = await self.fail_task(task, step, failure_reason, browser_state, exception=e)if is_task_marked_as_failed:await self.clean_up_task(task=task,@@ -876,7 +879,12 @@ class ForgeAgent:context.task_id = Noneasync def fail_task(- self, task: Task, step: Step | None, reason: str | None, browser_state: BrowserState | None = None+ self,+ task: Task,+ step: Step | None,+ reason: str | None,+ browser_state: BrowserState | None = None,+ exception: Exception | None = None,) -> bool:try:if step is not None:@@ -886,10 +894,12 @@ class ForgeAgent:)# Update task status first+ failure_category = classify_from_failure_reason(reason, exception=exception)await self.update_task(task,status=TaskStatus.failed,failure_reason=reason,+ failure_category=failure_category,)# Detect user-defined errors if error_code_mapping is provided@@ -2297,6 +2307,7 @@ class ForgeAgent:)return TerminateAction(reasoning=verification_result.thoughts,+ failure_categories=verification_result.failure_categories or [],)# We don't want to return a complete action if the user goal is not achieved since we're checking at every step@@ -3875,6 +3886,7 @@ class ForgeAgent:failure_reason: str | None = None,webhook_failure_reason: str | None = None,errors: list[dict[str, Any]] | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> Task:# refresh task from db to get the latest statustask_from_db = await app.DATABASE.get_task(task_id=task.task_id, organization_id=task.organization_id)@@ -3891,6 +3903,8 @@ class ForgeAgent:updates["failure_reason"] = failure_reasonif errors is not None:updates["errors"] = errors+ if failure_category is not None:+ updates["failure_category"] = failure_categoryupdate_comparison = {key: {"old": getattr(task, key), "new": value}for key, value in updates.items()@@ -4053,11 +4067,13 @@ class ForgeAgent:failure_reason = persisted_action.reasoningif 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)await self.update_task(task,status=TaskStatus.terminated,failure_reason=failure_reason,errors=task_errors,+ failure_category=failure_category,)return True, last_step, None@@ -4146,6 +4162,9 @@ class ForgeAgent:errors = [ReachMaxStepsError().model_dump()] + [error.model_dump() for error in generated_failure_reason.errors]+ failure_category = generated_failure_reason.failure_categories or classify_from_failure_reason(+ failure_reason+ )await self._cancel_speculative_step(next_step)@@ -4154,6 +4173,7 @@ class ForgeAgent:status=TaskStatus.failed,failure_reason=failure_reason,errors=errors,+ failure_category=failure_category,)return False, last_step, None@@ -4208,13 +4228,17 @@ class ForgeAgent:error_codes=[e.error_code for e in failure_response.errors],)+ failure_reason = (+ 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)await self.update_task(task,TaskStatus.failed,- failure_reason=(- f"Max retries per step ({max_retries_per_step}) exceeded. Possible failure reasons: {failure_response.reasoning}"- ),+ failure_reason=failure_reason,errors=new_errors,+ failure_category=failure_category,)return Noneelse:@@ -4556,7 +4580,13 @@ class ForgeAgent:)last_step = await self.update_step(step, is_last=True)failure_reason = await self.get_failure_reason_for_task(task)- await self.update_task(task, status=TaskStatus.terminated, failure_reason=failure_reason)+ failure_category = classify_from_failure_reason(failure_reason)+ await self.update_task(+ task,+ status=TaskStatus.terminated,+ failure_reason=failure_reason,+ failure_category=failure_category,+ )return False, last_step, None# If the max steps are exceeded, mark the current step as the last step and conclude the taskcontext = skyvern_context.current()@@ -4602,12 +4632,16 @@ class ForgeAgent:errors = [ReachMaxStepsError().model_dump()] + [error.model_dump() for error in generated_failure_reason.errors]+ failure_category = generated_failure_reason.failure_categories or classify_from_failure_reason(+ failure_reason+ )await self.update_task(task,status=TaskStatus.failed,failure_reason=failure_reason,errors=errors,+ failure_category=failure_category,)return False, last_step, Noneelse:diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.pynew file mode 100644index 000000000..2a5e40b27--- /dev/null+++ b/skyvern/forge/failure_classifier.py@@ -0,0 +1,168 @@+from __future__ import annotations+++def classify_from_failure_reason(+ failure_reason: str | None,+ exception: Exception | None = None,+) -> 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.++ Categories:+ ANTI_BOT_DETECTION, BROWSER_ERROR, NAVIGATION_FAILURE, PAGE_LOAD_TIMEOUT,+ AUTH_FAILURE, LLM_ERROR, CREDENTIAL_ERROR, DATA_EXTRACTION_FAILURE,+ ELEMENT_NOT_FOUND, WRONG_PAGE_STATE, MAX_STEPS_EXCEEDED,+ INFRASTRUCTURE_ERROR, UNKNOWN+ """+ if not failure_reason and not exception:+ return None++ reason = (failure_reason or "").lower()+ exc_name = type(exception).__name__ if exception else ""++ categories: list[dict] = []++ # Bot detection / CAPTCHA — use specific phrases to avoid false positives+ if any(+ kw in reason+ for kw in [+ "captcha",+ "cloudflare",+ "bot detect",+ "bot block",+ "ip block",+ "request block",+ "access denied by",+ "anti-bot",+ "human verification",+ ]+ ):+ categories.append(+ {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.7,+ "reasoning": "Keywords matched in failure reason",+ }+ )++ # Browser errors+ if any(kw in exc_name for kw in ["Browser", "CDP", "TargetClosed"]) or any(+ kw in reason for kw in ["browser context closed", "page closed", "browser crash"]+ ):+ categories.append(+ {+ "category": "BROWSER_ERROR",+ "confidence_float": 0.9,+ "reasoning": f"Exception: {exc_name}" if exc_name else "Keywords matched",+ }+ )++ # Navigation failure+ if "FailedToNavigateToUrl" in exc_name or any(+ kw in reason for kw in ["failed to navigate", "404", "redirect loop"]+ ):+ categories.append(+ {+ "category": "NAVIGATION_FAILURE",+ "confidence_float": 0.9,+ "reasoning": f"Exception: {exc_name}" if "FailedToNavigate" in exc_name else "Keywords matched",+ }+ )++ # Page load timeout+ if "Timeout" in exc_name or "timeout" in reason:+ categories.append(+ {+ "category": "PAGE_LOAD_TIMEOUT",+ "confidence_float": 0.8,+ "reasoning": f"Exception: {exc_name}" if "Timeout" in exc_name else "Timeout in failure reason",+ }+ )++ # Auth failure+ if any(kw in reason for kw in ["login fail", "authentication fail", "auth fail", "mfa", "password"]):+ categories.append(+ {+ "category": "AUTH_FAILURE",+ "confidence_float": 0.7,+ "reasoning": "Keywords matched",+ }+ )++ # Credential error+ if "Bitwarden" in exc_name or any(kw in reason for kw in ["credential not found", "missing credential"]):+ categories.append(+ {+ "category": "CREDENTIAL_ERROR",+ "confidence_float": 0.8,+ "reasoning": f"Exception: {exc_name}" if "Bitwarden" in exc_name else "Keywords matched",+ }+ )++ # LLM error+ if any(kw in exc_name for kw in ["LLM", "APIError", "RateLimit"]) or "rate limit" in reason:+ categories.append(+ {+ "category": "LLM_ERROR",+ "confidence_float": 0.9,+ "reasoning": f"Exception: {exc_name}" if exc_name else "Keywords matched",+ }+ )++ # Scraping / data extraction failure+ if "ScrapingFailed" in exc_name or any(kw in reason for kw in ["scraping", "extraction fail", "empty extraction"]):+ categories.append(+ {+ "category": "DATA_EXTRACTION_FAILURE",+ "confidence_float": 0.7,+ "reasoning": f"Exception: {exc_name}" if "Scraping" in exc_name else "Keywords matched",+ }+ )++ # Element not found+ if "ElementNotFound" in exc_name or any(kw in reason for kw in ["element not found", "no matching element"]):+ categories.append(+ {+ "category": "ELEMENT_NOT_FOUND",+ "confidence_float": 0.8,+ "reasoning": f"Exception: {exc_name}" if "ElementNotFound" in exc_name else "Keywords matched",+ }+ )++ # Wrong page state+ if any(kw in reason for kw in ["unexpected page", "wrong page", "blank page"]):+ categories.append(+ {+ "category": "WRONG_PAGE_STATE",+ "confidence_float": 0.6,+ "reasoning": "Keywords matched",+ }+ )++ # Max steps exceeded+ if any(kw in reason for kw in ["max steps", "maximum steps", "max number of", "step limit"]):+ categories.append(+ {+ "category": "MAX_STEPS_EXCEEDED",+ "confidence_float": 0.9,+ "reasoning": "Keywords matched",+ }+ )++ # LLM reasoning error (wrong action, hallucination)+ if any(kw in reason for kw in ["wrong action", "invalid action", "hallucin"]):+ categories.append(+ {+ "category": "LLM_REASONING_ERROR",+ "confidence_float": 0.6,+ "reasoning": "Keywords matched",+ }+ )++ if not categories:+ return None++ # Sort by confidence descending+ categories.sort(key=lambda x: x["confidence_float"], reverse=True)+ return categoriesdiff --git a/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2 b/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2index 19271cf45..2861c2a60 100644--- a/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2+++ b/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2@@ -5,7 +5,13 @@ Make sure to ONLY return the JSON object in this format with no additional text{"page_info": str, // Think step by step. Describe all the useful information in the page related to the user goal."thoughts": str, // Think step by step. Explain your reasoning for the status you selected.- "status": str // Must be one of three values: "complete", "terminate", or "continue". Use "complete" ONLY if the user goal has been fully achieved{{ " according to the complete criterion" if complete_criterion else "" }}. Use "terminate" ONLY if the goal CANNOT ever be achieved (e.g., a file doesn't exist, an error modal blocks progress permanently, or an explicit termination condition is met in the user goal). Use "continue" if the goal is not yet achieved but more steps could potentially achieve it (this is the most common case - use this when you need to wait, navigate, or try different actions).+ "status": str, // Must be one of three values: "complete", "terminate", or "continue". Use "complete" ONLY if the user goal has been fully achieved{{ " according to the complete criterion" if complete_criterion else "" }}. Use "terminate" ONLY if the goal CANNOT ever be achieved (e.g., a file doesn't exist, an error modal blocks progress permanently, or an explicit termination condition is met in the user goal). Use "continue" if the goal is not yet achieved but more steps could potentially achieve it (this is the most common case - use this when you need to wait, navigate, or try different actions).+ "failure_categories": array // Only populate when status is "terminate". Classify the root cause. Categories: ANTI_BOT_DETECTION (CAPTCHA, Cloudflare, bot detection), BROWSER_ERROR (crash, page closed), NAVIGATION_FAILURE (404, redirect), PAGE_LOAD_TIMEOUT (timeout), AUTH_FAILURE (login failed, MFA), LLM_REASONING_ERROR (wrong element, wrong action), CREDENTIAL_ERROR (missing credentials), ELEMENT_NOT_FOUND (target missing), WRONG_PAGE_STATE (unexpected page), DATA_EXTRACTION_FAILURE (extraction failed), INFRASTRUCTURE_ERROR (network, OOM), UNKNOWN (cannot determine). Return one or more categories ordered by likelihood.+ [{+ "category": str, // The category from the list above+ "confidence_float": float, // 0.0 to 1.0+ "reasoning": str // Brief explanation+ }]}```diff --git a/skyvern/forge/prompts/skyvern/summarize-max-retries-reason.j2 b/skyvern/forge/prompts/skyvern/summarize-max-retries-reason.j2index 23c19301d..f857f0956 100644--- a/skyvern/forge/prompts/skyvern/summarize-max-retries-reason.j2+++ b/skyvern/forge/prompts/skyvern/summarize-max-retries-reason.j2@@ -10,7 +10,13 @@ Make sure to ONLY return the JSON object in this format with no additional text"error_code": str, // The error code from the user's error code list"reasoning": str, // The reasoning behind the error. Be specific, referencing any user information and their fields in your reasoning. Keep the reasoning short and to the point."confidence_float": float // The confidence of the error. Pick a number between 0.0 and 1.0. 0.0 means no confidence, 1.0 means full confidence- }]{% endif %}+ }]{% endif %},+ "failure_categories": array // Classify the root cause of this failure. Return one or more categories ordered by likelihood. Always return at least one. Categories: ANTI_BOT_DETECTION (CAPTCHA, Cloudflare, bot detection), BROWSER_ERROR (crash, page closed), NAVIGATION_FAILURE (404, redirect), PAGE_LOAD_TIMEOUT (timeout), AUTH_FAILURE (login failed, MFA), LLM_REASONING_ERROR (wrong element, wrong action), CREDENTIAL_ERROR (missing credentials), ELEMENT_NOT_FOUND (target missing), WRONG_PAGE_STATE (unexpected page), DATA_EXTRACTION_FAILURE (extraction failed), MAX_STEPS_EXCEEDED (use only as secondary, always identify root cause as primary), INFRASTRUCTURE_ERROR (network, OOM), UNKNOWN (cannot determine).+ [{+ "category": str, // The category from the list above+ "confidence_float": float, // 0.0 to 1.0+ "reasoning": str // Brief explanation+ }]}```diff --git a/skyvern/forge/prompts/skyvern/summarize-max-steps-reason.j2 b/skyvern/forge/prompts/skyvern/summarize-max-steps-reason.j2index b4ac7e7c9..33577b6e0 100644--- a/skyvern/forge/prompts/skyvern/summarize-max-steps-reason.j2+++ b/skyvern/forge/prompts/skyvern/summarize-max-steps-reason.j2@@ -10,7 +10,13 @@ Make sure to ONLY return the JSON object in this format with no additional text"error_code": str, // The error code from the user's error code list"reasoning": str, // The reasoning behind the error. Be specific, referencing any user information and their fields in your reasoning. Keep the reasoning short and to the point."confidence_float": float // The confidence of the error. Pick a number between 0.0 and 1.0. 0.0 means no confidence, 1.0 means full confidence- }]{% endif %}+ }]{% endif %},+ "failure_categories": array // Classify the root cause of this failure. Return one or more categories ordered by likelihood. Always return at least one. Categories: ANTI_BOT_DETECTION (CAPTCHA, Cloudflare, bot detection), BROWSER_ERROR (crash, page closed), NAVIGATION_FAILURE (404, redirect), PAGE_LOAD_TIMEOUT (timeout), AUTH_FAILURE (login failed, MFA), LLM_REASONING_ERROR (wrong element, wrong action), CREDENTIAL_ERROR (missing credentials), ELEMENT_NOT_FOUND (target missing), WRONG_PAGE_STATE (unexpected page), DATA_EXTRACTION_FAILURE (extraction failed), MAX_STEPS_EXCEEDED (use only as secondary, always identify root cause as primary), INFRASTRUCTURE_ERROR (network, OOM), UNKNOWN (cannot determine).+ [{+ "category": str, // The category from the list above+ "confidence_float": float, // 0.0 to 1.0+ "reasoning": str // Brief explanation+ }]}User Goal:diff --git a/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2 b/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2index 59f4e1045..75715ae57 100644--- a/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2+++ b/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2@@ -10,7 +10,13 @@ Reply in JSON format with the following keys:"thoughts": str, // Think step by step. Would completing the tasks in the task history be good enough to achieve the user goal? If more tasks need to be completed to achieve the goal, what would be the next task? If the goal appears impossible, explain why."user_goal_achieved": bool, // True if the user goal has been completed, false otherwise. If the user wants to extract information and it has not been done, the user goal is not achieved. If info extraction is not required, use the task history, assisted by the screenshot to decide if the user goal has been achieved."should_terminate": bool, // True ONLY if there is CLEAR, EXPLICIT, UNAMBIGUOUS evidence that the goal is IMPOSSIBLE. The page must explicitly state the action cannot be done. False if there's ANY chance the goal can still be achieved.- "termination_reason": str // If should_terminate is true, quote the EXACT error message or text from the page that proves impossibility. Null if should_terminate is false.+ "termination_reason": str, // If should_terminate is true, quote the EXACT error message or text from the page that proves impossibility. Null if should_terminate is false.+ "failure_categories": array // Only populate when should_terminate is true. Classify the root cause. Categories: ANTI_BOT_DETECTION (CAPTCHA, Cloudflare, bot detection), BROWSER_ERROR (crash, page closed), NAVIGATION_FAILURE (404, redirect), PAGE_LOAD_TIMEOUT (timeout), AUTH_FAILURE (login failed, MFA), LLM_REASONING_ERROR (wrong element, wrong action), CREDENTIAL_ERROR (missing credentials), ELEMENT_NOT_FOUND (target missing), WRONG_PAGE_STATE (unexpected page), DATA_EXTRACTION_FAILURE (extraction failed), INFRASTRUCTURE_ERROR (network, OOM), UNKNOWN (cannot determine). Return one or more categories ordered by likelihood.+ [{+ "category": str, // The category from the list above+ "confidence_float": float, // 0.0 to 1.0+ "reasoning": str // Brief explanation+ }]}CRITICAL - Be very conservative about termination. Only terminate when:diff --git a/skyvern/forge/prompts/skyvern/task_v2_summarize-max-steps-reason.j2 b/skyvern/forge/prompts/skyvern/task_v2_summarize-max-steps-reason.j2index 07a7abaa4..026e0d8b0 100644--- a/skyvern/forge/prompts/skyvern/task_v2_summarize-max-steps-reason.j2+++ b/skyvern/forge/prompts/skyvern/task_v2_summarize-max-steps-reason.j2@@ -5,6 +5,12 @@ Make sure to ONLY return the JSON object in this format with no additional text{"page_info": str, // Think step by step. Describe all the useful information in the page related to the user goal."reasoning": str, // Think step by step. Describe the reason you summarized based on 'page_info', screenshots, user goal and result of mini plans. Keep the reasoning short and to the point.+ "failure_categories": array // Classify the root cause of this failure. Return one or more categories ordered by likelihood (highest first). Always return at least one. Categories: ANTI_BOT_DETECTION (CAPTCHA, Cloudflare, bot detection), BROWSER_ERROR (crash, page closed), NAVIGATION_FAILURE (404, redirect), PAGE_LOAD_TIMEOUT (timeout), AUTH_FAILURE (login failed, MFA), LLM_REASONING_ERROR (wrong element, wrong action), CREDENTIAL_ERROR (missing credentials), ELEMENT_NOT_FOUND (target missing), WRONG_PAGE_STATE (unexpected page), DATA_EXTRACTION_FAILURE (extraction failed), MAX_STEPS_EXCEEDED (use only as secondary, always identify root cause as primary), INFRASTRUCTURE_ERROR (network, OOM), UNKNOWN (cannot determine).+ [{+ "category": str, // The category from the list above+ "confidence_float": float, // 0.0 to 1.0+ "reasoning": str // Brief explanation+ }]}User Goal:diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex 08fc89dd8..4de033c52 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -847,6 +847,7 @@ class AgentDB(BaseAlchemyDB):errors: list[dict[str, Any]] | None = None,max_steps_per_run: int | None = None,organization_id: str | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> Task:if (status is None@@ -855,6 +856,7 @@ class AgentDB(BaseAlchemyDB):and errors is Noneand max_steps_per_run is Noneand webhook_failure_reason is None+ and failure_category is None):raise ValueError("At least one of status, extracted_information, or failure_reason must be provided to update the task"@@ -884,6 +886,8 @@ class AgentDB(BaseAlchemyDB):task.max_steps_per_run = max_steps_per_runif webhook_failure_reason is not None:task.webhook_failure_reason = webhook_failure_reason+ if failure_category is not None:+ task.failure_category = failure_categoryawait session.commit()updated_task = await self.get_task(task_id, organization_id=organization_id)if not updated_task:@@ -3629,6 +3633,7 @@ class AgentDB(BaseAlchemyDB):browser_profile_id: str | None | object = _UNSET,browser_address: str | None = None,extra_http_headers: dict[str, str] | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> WorkflowRun:async with self.Session() as session:workflow_run = (@@ -3678,6 +3683,8 @@ class AgentDB(BaseAlchemyDB):workflow_run.verification_code_polling_started_at = Noneif browser_profile_id is not _UNSET:workflow_run.browser_profile_id = browser_profile_id+ if failure_category is not None:+ workflow_run.failure_category = failure_categoryawait session.commit()await save_workflow_run_logs(workflow_run_id)await session.refresh(workflow_run)@@ -5306,6 +5313,7 @@ class AgentDB(BaseAlchemyDB):output: dict[str, Any] | None = None,organization_id: str | None = None,webhook_failure_reason: str | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> TaskV2:async with self.Session() as session:task_v2 = (@@ -5340,6 +5348,8 @@ class AgentDB(BaseAlchemyDB):task_v2.output = outputif webhook_failure_reason is not None:task_v2.webhook_failure_reason = webhook_failure_reason+ if failure_category is not None:+ task_v2.failure_category = failure_categoryawait session.commit()await session.refresh(task_v2)return convert_to_task_v2(task_v2, debug_enabled=self.debug_enabled)diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex f92c516e8..b83db585d 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -122,6 +122,7 @@ class TaskModel(Base):waiting_for_verification_code = Column(Boolean, nullable=False, default=False, server_default=sqlalchemy.false())verification_code_identifier = Column(String, nullable=True)verification_code_polling_started_at = Column(DateTime, nullable=True)+ failure_category = Column(JSON, nullable=True)class StepModel(Base):@@ -418,6 +419,7 @@ class WorkflowRunModel(Base):waiting_for_verification_code = Column(Boolean, nullable=False, default=False, server_default=sqlalchemy.false())verification_code_identifier = Column(String, nullable=True)verification_code_polling_started_at = Column(DateTime, nullable=True)+ failure_category = Column(JSON, nullable=True)queued_at = Column(DateTime, nullable=True)started_at = Column(DateTime, nullable=True)@@ -860,6 +862,7 @@ class TaskV2Model(Base):created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)model = Column(JSON, nullable=True)+ failure_category = Column(JSON, nullable=True)class ThoughtModel(Base):diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex 83904e7dd..5af47c39f 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -225,6 +225,7 @@ def convert_to_task(task_obj: TaskModel, debug_enabled: bool = False, workflow_pbrowser_session_id=task_obj.browser_session_id,browser_address=task_obj.browser_address,download_timeout=task_obj.download_timeout,+ failure_category=task_obj.failure_category,)return task@@ -455,6 +456,7 @@ def convert_to_workflow_run(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,+ failure_category=workflow_run_model.failure_category,)diff --git a/skyvern/forge/sdk/schemas/task_v2.py b/skyvern/forge/sdk/schemas/task_v2.pyindex 4c35166fe..c94660ba9 100644--- a/skyvern/forge/sdk/schemas/task_v2.py+++ b/skyvern/forge/sdk/schemas/task_v2.py@@ -54,6 +54,7 @@ class TaskV2(BaseModel):extra_http_headers: dict[str, str] | None = Nonebrowser_address: str | None = Nonerun_with: str | None = None+ failure_category: list[dict[str, Any]] | None = Nonecreated_at: datetimemodified_at: datetimediff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.pyindex a1a5918af..e80d26559 100644--- a/skyvern/forge/sdk/schemas/tasks.py+++ b/skyvern/forge/sdk/schemas/tasks.py@@ -284,6 +284,7 @@ class Task(TaskBase):retry: int | None = Nonemax_steps_per_run: int | None = Noneerrors: list[dict[str, Any]] = []+ failure_category: list[dict[str, Any]] | None = Nonemodel: dict[str, Any] | None = Nonequeued_at: datetime | None = Nonestarted_at: datetime | None = Nonediff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.pyindex ecf5c6640..7511aaeab 100644--- a/skyvern/forge/sdk/workflow/models/workflow.py+++ b/skyvern/forge/sdk/workflow/models/workflow.py@@ -167,6 +167,7 @@ class WorkflowRun(BaseModel):totp_verification_url: str | None = Nonetotp_identifier: str | None = Nonefailure_reason: str | None = None+ failure_category: list[dict[str, Any]] | None = Noneparent_workflow_run_id: str | None = Noneworkflow_title: str | None = Nonemax_screenshot_scrolls: int | None = Nonediff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 704dc6eef..40f71b688 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -50,6 +50,7 @@ from skyvern.exceptions import (get_user_facing_exception_message,)from skyvern.forge import app+from skyvern.forge.failure_classifier import classify_from_failure_reasonfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactTypefrom skyvern.forge.sdk.cache.factory import CacheFactory@@ -3480,6 +3481,7 @@ class WorkflowService:failure_reason: str | None = None,run_with: str | None = None,ai_fallback: bool | None = None,+ failure_category: list[dict] | None = None,) -> WorkflowRun:workflow_run = await app.DATABASE.update_workflow_run(workflow_run_id=workflow_run_id,@@ -3487,6 +3489,7 @@ class WorkflowService:failure_reason=failure_reason,run_with=run_with,ai_fallback=ai_fallback,+ failure_category=failure_category,)if status in [WorkflowRunStatus.completed, WorkflowRunStatus.failed, WorkflowRunStatus.terminated]:start_time = (@@ -3561,6 +3564,7 @@ class WorkflowService:workflow_run_id: str,failure_reason: str | None,run_with: str | None = None,+ failure_category: list[dict] | None = None,) -> WorkflowRun:LOG.info(f"Marking workflow run {workflow_run_id} as failed",@@ -3572,11 +3576,16 @@ class WorkflowService:# Add workflow failure tag to traceotel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.failed)+ # Auto-classify if no explicit category provided+ if failure_category is None:+ failure_category = classify_from_failure_reason(failure_reason)+return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,status=WorkflowRunStatus.failed,failure_reason=failure_reason,run_with=run_with,+ failure_category=failure_category,)async def mark_workflow_run_as_running(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:@@ -3605,6 +3614,7 @@ class WorkflowService:workflow_run_id: str,failure_reason: str | None,run_with: str | None = None,+ failure_category: list[dict] | None = None,) -> WorkflowRun:LOG.info(f"Marking workflow run {workflow_run_id} as terminated",@@ -3616,11 +3626,16 @@ 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+ if failure_category is None:+ failure_category = classify_from_failure_reason(failure_reason)+return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,status=WorkflowRunStatus.terminated,failure_reason=failure_reason,run_with=run_with,+ failure_category=failure_category,)async def mark_workflow_run_as_canceled(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:@@ -3654,11 +3669,14 @@ 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)+return await self._update_workflow_run_status(workflow_run_id=workflow_run_id,status=WorkflowRunStatus.timed_out,failure_reason=failure_reason,run_with=run_with,+ failure_category=failure_category,)async def get_workflow_run(self, workflow_run_id: str, organization_id: str | None = None) -> WorkflowRun:diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.pyindex b00a89227..d7f16a31a 100644--- a/skyvern/services/task_v2_service.py+++ b/skyvern/services/task_v2_service.py@@ -16,6 +16,7 @@ from skyvern.exceptions import (UrlGenerationFailure,)from skyvern.forge import app+from skyvern.forge.failure_classifier import classify_from_failure_reasonfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactoryfrom skyvern.forge.sdk.api.llm.exceptions import EmptyLLMResponseError, InvalidLLMResponseFormat@@ -94,7 +95,7 @@ def _generate_data_extraction_schema_for_loop(loop_values_key: str) -> dict:async def _summarize_max_steps_failure_reason(task_v2: TaskV2, organization_id: str, browser_state: BrowserState | None-) -> str:+) -> tuple[str, list[dict] | None]:"""Summarize the failure reason for the task v2."""@@ -102,11 +103,11 @@ async def _summarize_max_steps_failure_reason(assert task_v2.workflow_run_id is not Noneif browser_state is None:- return "Failed to start browser"+ return "Failed to start browser", Nonepage = await browser_state.get_working_page()if page is None:- return "Failed to get the current browser page"+ return "Failed to get the current browser page", Nonescreenshots = await SkyvernFrame.take_split_screenshots(page=page, url=str(task_v2.url), draw_boxes=False)@@ -142,10 +143,10 @@ async def _summarize_max_steps_failure_reason(prompt_name="task_v2_summarize-max-steps-reason",thought=thought,)- return json_response.get("reasoning", "")+ return json_response.get("reasoning", ""), json_response.get("failure_categories")except Exception:LOG.warning("Failed to summarize the failure reason for task v2", exc_info=True)- return ""+ return "", Noneasync def _handle_task_v2_termination(@@ -157,6 +158,7 @@ async def _handle_task_v2_termination(termination_reason: str | None,iteration: int,source: str | None = None,+ failure_category: list[dict] | None = None,) -> TaskV2:"""Handle task v2 termination by creating a termination thought and marking the task as terminated.@@ -212,11 +214,13 @@ async def _handle_task_v2_termination(output=output,)+ resolved_failure_category = failure_category or classify_from_failure_reason(termination_reason)task_v2 = await mark_task_v2_as_terminated(task_v2_id=task_v2_id,workflow_run_id=workflow_run_id,organization_id=organization_id,failure_reason=termination_reason or "Task goal is impossible to achieve",+ failure_category=resolved_failure_category,)return task_v2@@ -805,6 +809,7 @@ async def run_task_v2_helper(user_goal_achieved = task_v2_response.get("user_goal_achieved", False)should_terminate = task_v2_response.get("should_terminate", False)termination_reason = task_v2_response.get("termination_reason")+ failure_categories = task_v2_response.get("failure_categories")observation = task_v2_response.get("page_info", "")thoughts: str = task_v2_response.get("thoughts", "")plan = task_v2_response.get("plan", "")@@ -852,6 +857,7 @@ async def run_task_v2_helper(workflow_permanent_id=workflow.workflow_permanent_id,termination_reason=termination_reason,iteration=i,+ failure_category=failure_categories,)return workflow, workflow_run, task_v2@@ -1052,6 +1058,7 @@ async def run_task_v2_helper(user_goal_achieved = completion_resp.get("user_goal_achieved", False)should_terminate = completion_resp.get("should_terminate", False)termination_reason = completion_resp.get("termination_reason")+ completion_failure_categories = completion_resp.get("failure_categories")thought_content = completion_resp.get("thoughts", "")await app.DATABASE.update_thought(thought_id=thought.observer_thought_id,@@ -1094,6 +1101,7 @@ async def run_task_v2_helper(termination_reason=termination_reason,iteration=i,source="completion_check",+ failure_category=completion_failure_categories,)return workflow, workflow_run, task_v2@@ -1105,12 +1113,24 @@ async def run_task_v2_helper()if total_step_count >= max_steps:LOG.info("Task v2 failed - run out of steps", max_steps=max_steps, workflow_run_id=workflow_run_id)- failure_reason = await _summarize_max_steps_failure_reason(task_v2, organization_id, browser_state)+ failure_reason, llm_failure_categories = await _summarize_max_steps_failure_reason(+ task_v2, organization_id, browser_state+ )+ full_failure_reason = (+ f"Reached the max number of {max_steps} steps."+ f" Possible failure reasons: {failure_reason}"+ f' If you need more steps, update the "Max Steps Override"'+ f" configuration when running the task. Or add/update the"+ 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)task_v2 = await mark_task_v2_as_failed(task_v2_id=task_v2_id,workflow_run_id=workflow_run_id,- failure_reason=f'Reached the max number of {max_steps} steps. Possible failure reasons: {failure_reason} If you need more steps, update the "Max Steps Override" configuration when running the task. Or add/update the "x-max-steps-override" header with your desired number of steps in the API request.',+ failure_reason=full_failure_reason,organization_id=organization_id,+ failure_category=failure_category,)return workflow, workflow_run, task_v2else:@@ -1631,9 +1651,15 @@ async def _update_task_v2_status(organization_id: str | None = None,summary: str | None = None,output: dict[str, Any] | None = None,+ failure_category: list[dict] | None = None,) -> TaskV2:task_v2 = await app.DATABASE.update_task_v2(- task_v2_id, organization_id=organization_id, status=status, summary=summary, output=output+ task_v2_id,+ organization_id=organization_id,+ status=status,+ summary=summary,+ output=output,+ failure_category=failure_category,)if status in [TaskV2Status.completed, TaskV2Status.failed, TaskV2Status.terminated]:start_time = (@@ -1658,15 +1684,19 @@ async def mark_task_v2_as_failed(workflow_run_id: str | None = None,failure_reason: str | None = None,organization_id: str | None = None,+ failure_category: list[dict] | None = None,) -> TaskV2:task_v2 = await _update_task_v2_status(task_v2_id,organization_id=organization_id,status=TaskV2Status.failed,+ failure_category=failure_category,)if workflow_run_id:await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed(- workflow_run_id, failure_reason=failure_reason or "Skyvern task 2.0 failed"+ workflow_run_id,+ failure_reason=failure_reason or "Skyvern task 2.0 failed",+ failure_category=failure_category,)# Add task failure tag to trace@@ -1725,14 +1755,20 @@ async def mark_task_v2_as_terminated(workflow_run_id: str | None = None,organization_id: str | None = None,failure_reason: str | None = None,+ failure_category: list[dict] | None = None,) -> TaskV2:task_v2 = await _update_task_v2_status(task_v2_id,organization_id=organization_id,status=TaskV2Status.terminated,+ failure_category=failure_category,)if workflow_run_id:- await app.WORKFLOW_SERVICE.mark_workflow_run_as_terminated(workflow_run_id, failure_reason)+ await app.WORKFLOW_SERVICE.mark_workflow_run_as_terminated(+ workflow_run_id,+ failure_reason,+ failure_category=failure_category,+ )# Add task terminated tag to traceotel_trace.get_current_span().set_attribute("task.completion_status", "terminated")diff --git a/skyvern/utils/prompt_engine.py b/skyvern/utils/prompt_engine.pyindex 20d002533..737bb5979 100644--- a/skyvern/utils/prompt_engine.py+++ b/skyvern/utils/prompt_engine.py@@ -35,6 +35,7 @@ class MaxStepsReasonResponse(BaseModel):page_info: strreasoning: strerrors: list[UserDefinedError] = []+ failure_categories: list[dict] = []def load_prompt_with_elements(diff --git a/skyvern/webeye/actions/actions.py b/skyvern/webeye/actions/actions.pyindex e8ff682a7..dbd33474f 100644--- a/skyvern/webeye/actions/actions.py+++ b/skyvern/webeye/actions/actions.py@@ -56,6 +56,7 @@ class CompleteVerifyResult(BaseModel):thoughts: strpage_info: str | None = None+ failure_categories: list[dict] = []def __repr__(self) -> str:if self.status:@@ -331,6 +332,7 @@ class HoverAction(WebAction):class TerminateAction(DecisiveAction):action_type: ActionType = ActionType.TERMINATE+ failure_categories: list[dict] = []class CompleteAction(DecisiveAction):diff --git a/tests/unit/test_error_detection_integration.py b/tests/unit/test_error_detection_integration.pyindex e2d0cc9de..f6cc1277d 100644--- a/tests/unit/test_error_detection_integration.py+++ b/tests/unit/test_error_detection_integration.py@@ -162,6 +162,7 @@ async def test_max_retries_with_error_detection(agent, mock_browser_state):failure_reason=None,webhook_failure_reason=None,errors=None,+ failure_category=None,):updates = {}if status is not None:@@ -170,6 +171,8 @@ async def test_max_retries_with_error_detection(agent, mock_browser_state):updates["failure_reason"] = failure_reasonif errors is not None:updates["errors"] = errors+ if failure_category is not None:+ updates["failure_category"] = failure_categoryreturn await mock_app.DATABASE.update_task(task.task_id, organization_id=task.organization_id, **updates)with patch.object(ForgeAgent, "summary_failure_reason_for_max_retries", mock_summary):diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pynew file mode 100644index 000000000..714b2edaf--- /dev/null+++ b/tests/unit/test_failure_classifier.py@@ -0,0 +1,282 @@+from __future__ import annotations++import pytest++from skyvern.forge.failure_classifier import classify_from_failure_reason+++class TestNoneAndEmptyInput:+ def test_none_input_returns_none(self) -> None:+ assert classify_from_failure_reason(None) is None++ def test_empty_string_returns_none(self) -> None:+ assert classify_from_failure_reason("") is None++ def test_none_with_none_exception_returns_none(self) -> None:+ assert classify_from_failure_reason(None, exception=None) is None++ def test_unrecognized_reason_returns_none(self) -> None:+ assert classify_from_failure_reason("something completely unrelated happened") is None+++class TestAntiBotDetection:+ @pytest.mark.parametrize(+ "reason",+ [+ "Page blocked by captcha challenge",+ "Cloudflare protection detected",+ "Bot detected on the page",+ "IP blocked by server",+ "Request blocked due to suspicious activity",+ "Access denied by WAF",+ "Anti-bot system triggered",+ "Human verification required",+ ],+ )+ def test_keywords_match(self, reason: str) -> None:+ result = classify_from_failure_reason(reason)+ assert result is not None+ categories = [r["category"] for r in result]+ assert "ANTI_BOT_DETECTION" in categories++ def test_broad_blocked_does_not_match(self) -> None:+ """'blocked' alone should NOT trigger ANTI_BOT_DETECTION (narrowed keywords)."""+ result = classify_from_failure_reason("UI element blocked by overlay")+ if result:+ categories = [r["category"] for r in result]+ assert "ANTI_BOT_DETECTION" not in categories++ def test_broad_forbidden_does_not_match(self) -> None:+ result = classify_from_failure_reason("403 Forbidden from auth endpoint")+ if result:+ categories = [r["category"] for r in result]+ assert "ANTI_BOT_DETECTION" not in categories+++class TestBrowserError:+ def test_keyword_browser_context_closed(self) -> None:+ result = classify_from_failure_reason("browser context closed unexpectedly")+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"++ def test_keyword_page_closed(self) -> None:+ result = classify_from_failure_reason("page closed before action completed")+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"++ def test_exception_type_browser(self) -> None:+ class BrowserCrashError(Exception):+ pass++ result = classify_from_failure_reason("something failed", exception=BrowserCrashError())+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"+ assert "BrowserCrashError" in result[0]["reasoning"]++ def test_exception_type_cdp(self) -> None:+ class CDPConnectionError(Exception):+ pass++ result = classify_from_failure_reason("connection lost", exception=CDPConnectionError())+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"++ def test_exception_type_target_closed(self) -> None:+ class TargetClosedError(Exception):+ pass++ result = classify_from_failure_reason("target gone", exception=TargetClosedError())+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"+++class TestNavigationFailure:+ def test_keyword_failed_to_navigate(self) -> None:+ result = classify_from_failure_reason("Failed to navigate to the login page")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "NAVIGATION_FAILURE" in categories++ def test_keyword_404(self) -> None:+ result = classify_from_failure_reason("Server returned 404 for the URL")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "NAVIGATION_FAILURE" in categories++ def test_exception_type(self) -> None:+ class FailedToNavigateToUrl(Exception):+ pass++ result = classify_from_failure_reason("url error", exception=FailedToNavigateToUrl())+ assert result is not None+ assert result[0]["category"] == "NAVIGATION_FAILURE"+ assert "FailedToNavigateToUrl" in result[0]["reasoning"]+++class TestPageLoadTimeout:+ def test_keyword_timeout(self) -> None:+ result = classify_from_failure_reason("Page load timeout after 30s")+ assert result is not None+ assert result[0]["category"] == "PAGE_LOAD_TIMEOUT"++ def test_exception_type_timeout(self) -> None:+ result = classify_from_failure_reason("waiting for page", exception=TimeoutError())+ assert result is not None+ assert result[0]["category"] == "PAGE_LOAD_TIMEOUT"+++class TestAuthFailure:+ @pytest.mark.parametrize(+ "reason",+ [+ "Login failed with invalid credentials",+ "Authentication failed for user",+ "Auth failed - wrong token",+ "MFA verification required",+ ],+ )+ def test_keywords_match(self, reason: str) -> None:+ result = classify_from_failure_reason(reason)+ assert result is not None+ categories = [r["category"] for r in result]+ assert "AUTH_FAILURE" in categories+++class TestCredentialError:+ def test_keyword_credential_not_found(self) -> None:+ result = classify_from_failure_reason("Credential not found in vault")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "CREDENTIAL_ERROR" in categories++ def test_exception_type_bitwarden(self) -> None:+ class BitwardenVaultError(Exception):+ pass++ result = classify_from_failure_reason("vault error", exception=BitwardenVaultError())+ assert result is not None+ assert result[0]["category"] == "CREDENTIAL_ERROR"+++class TestLLMError:+ def test_keyword_rate_limit(self) -> None:+ result = classify_from_failure_reason("LLM call hit rate limit")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "LLM_ERROR" in categories++ def test_exception_type_llm(self) -> None:+ class LLMProviderError(Exception):+ pass++ result = classify_from_failure_reason("provider down", exception=LLMProviderError())+ assert result is not None+ assert result[0]["category"] == "LLM_ERROR"++ def test_exception_type_rate_limit(self) -> None:+ class RateLimitExceeded(Exception):+ pass++ result = classify_from_failure_reason("too many requests", exception=RateLimitExceeded())+ assert result is not None+ categories = [r["category"] for r in result]+ assert "LLM_ERROR" in categories+++class TestDataExtractionFailure:+ def test_keyword_scraping(self) -> None:+ result = classify_from_failure_reason("Scraping failed on the results page")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "DATA_EXTRACTION_FAILURE" in categories++ def test_exception_type_scraping(self) -> None:+ class ScrapingFailedError(Exception):+ pass++ result = classify_from_failure_reason("page error", exception=ScrapingFailedError())+ assert result is not None+ categories = [r["category"] for r in result]+ assert "DATA_EXTRACTION_FAILURE" in categories+++class TestElementNotFound:+ def test_keyword(self) -> None:+ result = classify_from_failure_reason("Target element not found on the page")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "ELEMENT_NOT_FOUND" in categories++ def test_exception_type(self) -> None:+ class ElementNotFoundError(Exception):+ pass++ result = classify_from_failure_reason("missing", exception=ElementNotFoundError())+ assert result is not None+ categories = [r["category"] for r in result]+ assert "ELEMENT_NOT_FOUND" in categories+++class TestWrongPageState:+ @pytest.mark.parametrize("reason", ["Unexpected page after login", "Wrong page loaded", "Blank page detected"])+ def test_keywords_match(self, reason: str) -> None:+ result = classify_from_failure_reason(reason)+ assert result is not None+ categories = [r["category"] for r in result]+ assert "WRONG_PAGE_STATE" in categories+++class TestMaxStepsExceeded:+ @pytest.mark.parametrize(+ "reason",+ [+ "Reached the max steps limit",+ "Maximum steps exceeded for this task",+ "Reached the max number of 25 steps",+ "Step limit reached",+ ],+ )+ def test_keywords_match(self, reason: str) -> None:+ result = classify_from_failure_reason(reason)+ assert result is not None+ categories = [r["category"] for r in result]+ assert "MAX_STEPS_EXCEEDED" in categories+++class TestLLMReasoningError:+ @pytest.mark.parametrize("reason", ["Agent took wrong action on the form", "Invalid action type returned"])+ def test_keywords_match(self, reason: str) -> None:+ result = classify_from_failure_reason(reason)+ assert result is not None+ categories = [r["category"] for r in result]+ assert "LLM_REASONING_ERROR" in categories+++class TestMultipleCategories:+ def test_captcha_and_max_steps(self) -> None:+ """A max_steps failure caused by captcha should return both categories."""+ result = classify_from_failure_reason("Reached the max steps because captcha kept appearing")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "ANTI_BOT_DETECTION" in categories+ assert "MAX_STEPS_EXCEEDED" in categories++ def test_sorted_by_confidence_descending(self) -> None:+ """Results should be sorted by confidence_float, highest first."""+ result = classify_from_failure_reason("Reached the max steps because captcha kept appearing")+ assert result is not None+ assert len(result) >= 2+ confidences = [r["confidence_float"] for r in result]+ assert confidences == sorted(confidences, reverse=True)+++class TestExceptionOnlyClassification:+ def test_exception_without_reason(self) -> None:+ """Exception alone (no failure_reason) should still classify."""++ class BrowserCrashError(Exception):+ pass++ result = classify_from_failure_reason(None, exception=BrowserCrashError())+ assert result is not None+ assert result[0]["category"] == "BROWSER_ERROR"