Skip to content

Automate browser based workflows with AI

Label a run stuck on an unsolved captcha as bot protection, not a browser error, when its browser closes afterward (SKY-17725) (#8797)

Shuchang Zheng7a4f0f137218
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 326b2ccfb..7df96e4c5 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -90,7 +90,7 @@ from skyvern.exceptions import (
from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wait_time
from skyvern.forge import app
from skyvern.forge.async_operations import AgentPhase, AsyncOperationPool
-from skyvern.forge.failure_classifier import FailureCategory, classify_from_failure_reason
+from skyvern.forge.failure_classifier import FailureCategory, classify_from_failure_reason, is_captcha_solve_failure
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.aws import get_aws_client
from skyvern.forge.sdk.api.files import (
@@ -4460,6 +4460,37 @@ class ForgeAgent:
)
return latest_status
+ @staticmethod
+ def _latest_unsolved_captcha(steps: list[Step]) -> str | None:
+ """The captcha-solve failure the run was still stuck on, read from its last two steps that ran actions.
+
+ Two steps cover a failed captcha step and the retry after it. A later successful solve clears it, as does a
+ later success of the same action on the same element: an input-setup captcha guard reports its solve as an
+ abort of that input.
+ """
+ acted = [step.output.actions_and_results for step in steps if step.output and step.output.actions_and_results]
+ later_successful_targets: set[tuple[ActionType, str | None]] = set()
+ for actions_and_results in reversed(acted[-2:]):
+ for action, results in reversed(actions_and_results):
+ target = (action.action_type, action.element_id)
+ for result in reversed(results):
+ if result.success:
+ later_successful_targets.add(target)
+ elif is_captcha_solve_failure(result.exception_type):
+ solved_later = target in later_successful_targets or any(
+ action_type == ActionType.SOLVE_CAPTCHA for action_type, _ in later_successful_targets
+ )
+ return None if solved_later else result.exception_type
+ return None
+
+ async def _unsolved_captcha_exception(self, task: Task) -> str | None:
+ try:
+ steps = await app.DATABASE.tasks.get_task_steps(task_id=task.task_id, organization_id=task.organization_id)
+ return self._latest_unsolved_captcha(steps)
+ except Exception:
+ LOG.warning("Failed to read steps for captcha evidence", task_id=task.task_id, exc_info=True)
+ return None
+
async def _enrich_failure_reason_with_download_status(self, task: Task, reason: str) -> str:
"""Append one bounded sentence to a terminal failure reason when the run's latest download-intent
action received no file and passively observed a server 5xx status.
@@ -4519,6 +4550,15 @@ class ForgeAgent:
reason = redact_secrets_from_text(reason, run_secrets)
failure_category = classify_from_failure_reason(reason, exception=exception, fallback_to_unknown=True)
+ if any(category.get("category") == FailureCategory.BROWSER_ERROR for category in failure_category or []):
+ unsolved_captcha_exception = await self._unsolved_captcha_exception(task)
+ if unsolved_captcha_exception:
+ failure_category = classify_from_failure_reason(
+ reason,
+ exception=exception,
+ fallback_to_unknown=True,
+ unsolved_captcha_exception=unsolved_captcha_exception,
+ )
LOG.info(
"Task failure classified",
task_id=task.task_id,
diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.py
index 456efa8a7..742877bde 100644
--- a/skyvern/forge/failure_classifier.py
+++ b/skyvern/forge/failure_classifier.py
@@ -8,7 +8,7 @@ from typing import Any
import structlog
from skyvern.constants import PROXY_TRANSPORT_NAV_ERRORS
-from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_MARKER, FailedToNavigateToUrl
+from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_MARKER, CaptchaSolveError, FailedToNavigateToUrl
LOG = structlog.get_logger(__name__)
@@ -70,11 +70,29 @@ def _proxy_transport_evidence(reason: str, exception: Exception | None) -> str |
return "keyword_match" if any(code in driver_text for code in _PROXY_TRANSPORT_CODES_LOWER) else None
+def is_captcha_solve_failure(exception_name: str | None) -> bool:
+ """Whether an action result's recorded exception type is a CaptchaSolveError.
+
+ Subclasses are walked at call time because solver integrations register their failures (loop breaker,
+ timeout) as subclasses when imported, and an action result keeps only the class name.
+ """
+ if not exception_name:
+ return False
+ pending: list[type[CaptchaSolveError]] = [CaptchaSolveError]
+ while pending:
+ error_type = pending.pop()
+ if error_type.__name__ == exception_name:
+ return True
+ pending.extend(error_type.__subclasses__())
+ return False
+
+
def classify_from_failure_reason(
failure_reason: str | None,
exception: Exception | None = None,
fallback_to_unknown: bool = False,
exception_name: str | None = None,
+ unsolved_captcha_exception: str | None = None,
) -> list[dict] | None:
"""Classify failure from failure_reason text and/or exception type.
@@ -84,6 +102,10 @@ def classify_from_failure_reason(
unavailable — e.g. a Temporal activity failure whose cause type only crosses the
serialization boundary as a string. Ignored when ``exception`` is provided.
+ ``unsolved_captcha_exception`` names a captcha-solve failure the run was still stuck on when
+ it ended. It outranks a BROWSER_ERROR: a browser lost while the run is blocked by a captcha
+ only reports how the run stopped, not why it failed.
+
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
@@ -400,6 +422,19 @@ def classify_from_failure_reason(
}
)
+ if unsolved_captcha_exception and any(
+ category["category"] == FailureCategory.BROWSER_ERROR.value for category in categories
+ ):
+ categories.append(
+ {
+ "category": FailureCategory.ANTI_BOT_DETECTION.value,
+ "confidence_float": 0.95,
+ "reason_code": UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE,
+ "reasoning": f"Exception: {unsolved_captcha_exception} before the browser was lost",
+ "evidence_source": "exception_type",
+ }
+ )
+
if not categories:
if fallback_to_unknown:
return [
@@ -437,7 +472,7 @@ def classify_from_failure_reason(
# Bump when the taxonomy or the category->component mapping below changes, so a frozen
# coverage baseline stays reproducible per classifier_version.
-CLASSIFIER_VERSION = 3
+CLASSIFIER_VERSION = 4
FAILURE_ATTRIBUTION_SCHEMA_VERSION = 1
# Bounded sentinels — neither is an infra component id.
@@ -456,6 +491,59 @@ _FAILURE_CATEGORY_LITERALS = frozenset(category.value for category in FailureCat
BROWSER_SESSION_CLOSED_REASON_CODE = "browser_session_closed"
BROWSER_SESSION_STARTUP_TIMEOUT_REASON_CODE = "browser_session_startup_timeout"
PROXY_TRANSPORT_FAILED_REASON_CODE = "proxy_transport_failed"
+UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE = "unsolved_captcha_before_browser_loss"
+
+# ANTI_BOT_DETECTION entries carrying one of these are labels only: runtime consumers must treat the
+# failure exactly as they did before it was labeled anti-bot. Code that acts on a failure_category it
+# reads (or hands to a model) must go through without_output_only_anti_bot or skip these entries.
+OUTPUT_ONLY_ANTI_BOT_REASON_CODES = frozenset({UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE})
+
+
+def is_output_only_anti_bot_entry(category: object) -> bool:
+ return (
+ isinstance(category, dict)
+ and category.get("category") == FailureCategory.ANTI_BOT_DETECTION.value
+ and category.get("reason_code") in OUTPUT_ONLY_ANTI_BOT_REASON_CODES
+ )
+
+
+def without_output_only_anti_bot_categories(categories: list) -> list:
+ return [category for category in categories if not is_output_only_anti_bot_entry(category)]
+
+
+def without_output_only_anti_bot(value: Any) -> Any:
+ """``value`` with output-only anti-bot entries removed from every ``failure_category`` list in it; customer
+ data shaped like a category elsewhere is left alone, and a value with no marked entry is returned as is."""
+ return _scrub_output_only_anti_bot(value) if _has_output_only_anti_bot(value) else value
+
+
+# Iterative and copy-free: every registered block output pays this walk, and almost none carry a marked entry.
+def _has_output_only_anti_bot(value: Any) -> bool:
+ pending = [value]
+ while pending:
+ item = pending.pop()
+ if isinstance(item, dict):
+ categories = item.get("failure_category")
+ if isinstance(categories, list) and any(is_output_only_anti_bot_entry(c) for c in categories):
+ return True
+ pending.extend(item.values())
+ elif isinstance(item, list):
+ pending.extend(item)
+ return False
+
+
+def _scrub_output_only_anti_bot(value: Any) -> Any:
+ if isinstance(value, list):
+ return [_scrub_output_only_anti_bot(item) for item in value]
+ if isinstance(value, dict):
+ return {
+ key: without_output_only_anti_bot_categories(item)
+ if key == "failure_category" and isinstance(item, list)
+ else _scrub_output_only_anti_bot(item)
+ for key, item in value.items()
+ }
+ return value
+
# The only reason_code literals persisted attribution recognizes; unknown values are dropped,
# not copied. secure_codeblock_*/locator_wait_for_timeout are emitted by classify_from_failure_reason
@@ -471,6 +559,7 @@ _REASON_CODE_LITERALS = frozenset(
BROWSER_SESSION_CLOSED_REASON_CODE,
BROWSER_SESSION_STARTUP_TIMEOUT_REASON_CODE,
PROXY_TRANSPORT_FAILED_REASON_CODE,
+ UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE,
}
)
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index aae8c4e97..a15464539 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -15,6 +15,7 @@ from urllib.parse import urlsplit, urlunsplit
import structlog
from pydantic import JsonValue
+from skyvern.forge.failure_classifier import without_output_only_anti_bot
from skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm as sanitize_generic_tool_result_for_llm
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, assert_clean_user_facing_text
from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
@@ -1638,7 +1639,7 @@ def sanitize_tool_result_for_llm(tool_name: str, result: dict[str, Any]) -> dict
"""Strip large/binary fields from tool results before sending to the LLM."""
sanitized = sanitize_generic_tool_result_for_llm(
tool_name,
- result,
+ without_output_only_anti_bot(result),
drop_top_level_keys=(
"action",
"browser_context",
diff --git a/skyvern/forge/sdk/copilot/repair_origin_run.py b/skyvern/forge/sdk/copilot/repair_origin_run.py
index b5e565de8..658437317 100644
--- a/skyvern/forge/sdk/copilot/repair_origin_run.py
+++ b/skyvern/forge/sdk/copilot/repair_origin_run.py
@@ -31,6 +31,7 @@ import structlog
from skyvern.constants import SCRUBBED_VALUE
from skyvern.exceptions import WorkflowRunNotFound
from skyvern.forge import app
+from skyvern.forge.failure_classifier import without_output_only_anti_bot
from skyvern.forge.sdk.api.files import is_uploaded_file_id
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter
@@ -263,9 +264,9 @@ def origin_block_outputs_from_rows(
registered = registered_by_parameter_id.get(output_parameter_ids[label])
row = OriginBlockOutput(status=run_block.status, has_value=False, created_at=run_block.created_at)
if registered is not None:
- row = replace(row, has_value=True, value=registered.value)
+ row = replace(row, has_value=True, value=without_output_only_anti_bot(registered.value))
elif run_block.output is not None:
- row = replace(row, has_value=True, value=run_block.output)
+ row = replace(row, has_value=True, value=without_output_only_anti_bot(run_block.output))
outputs[label] = row
return OriginOutputSnapshot(
definition=definition.model_copy(deep=True),
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 80d8209ac..8fa109ab5 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -25,6 +25,7 @@ import yaml
from skyvern.constants import SCRUBBED_VALUE
from skyvern.exceptions import CopilotInlineSequentialCredentialUnsupported
from skyvern.forge import app
+from skyvern.forge.failure_classifier import without_output_only_anti_bot, without_output_only_anti_bot_categories
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.artifact.storage.base import artifact_filename_from_uri
from skyvern.forge.sdk.copilot.active_run_session import (
@@ -578,7 +579,12 @@ async def _chronological_run_block_rows(workflow_run_id: str, organization_id: s
workflow_run_id=workflow_run_id,
organization_id=organization_id,
)
- return list(reversed(rows))
+ return [_without_output_only_anti_bot_output(row) for row in reversed(rows)]
+
+
+def _without_output_only_anti_bot_output(row: WorkflowRunBlock) -> WorkflowRunBlock:
+ output = without_output_only_anti_bot(row.output)
+ return row if output is row.output else row.model_copy(update={"output": output})
def _reconcile_narrative_block_attempts(ctx: CopilotContext, blocks: list[WorkflowRunBlock]) -> None:
@@ -2191,7 +2197,7 @@ async def _attach_registered_output_parameter_values(
block_info.update(index_by_key.get(output_parameter_key, {}))
if block_info.get("block_label") in excluded_block_labels:
continue
- value = getattr(row, "value", None)
+ value = without_output_only_anti_bot(getattr(row, "value", None))
item = {
"workflow_run_id": workflow_run_id,
"output_parameter_id": output_parameter_id,
@@ -4931,7 +4937,7 @@ async def _run_blocks_and_collect_debug(
if not run_ok and run and getattr(run, "failure_reason", None):
result_data["failure_reason"] = redact_totp_runtime_values(run.failure_reason)
if not run_ok and run and getattr(run, "failure_category", None):
- result_data["failure_category"] = run.failure_category
+ result_data["failure_category"] = without_output_only_anti_bot_categories(run.failure_category)
_attach_loop_inputs(result_data, execution, workflow_run.workflow_run_id, run_block_rows)
_attach_block_fact_projection(
result_data,
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index cc8d0bdbf..d75fc929b 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -35,6 +35,7 @@ from skyvern.exceptions import (
sanitize_credential_for_error,
)
from skyvern.forge import app
+from skyvern.forge.failure_classifier import without_output_only_anti_bot
from skyvern.forge.sdk.api.aws import AsyncAWSClient
from skyvern.forge.sdk.api.azure import AsyncAzureVaultClient
from skyvern.forge.sdk.core import skyvern_context
@@ -1814,6 +1815,8 @@ class WorkflowRunContext:
if parameter.key in self.values:
LOG.debug(f"Output parameter {parameter.output_parameter_id} already has a registered value, overwriting")
+ # Later blocks template from this value; the persisted output keeps the full label.
+ value = without_output_only_anti_bot(value)
self.values[parameter.key] = value
self.register_block_reference_variable_from_output_parameter(parameter, value)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 308085b44..343246dca 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -119,7 +119,7 @@ from skyvern.exceptions import (
get_user_facing_exception_message,
)
from skyvern.forge import app
-from skyvern.forge.failure_classifier import classify_from_failure_reason
+from skyvern.forge.failure_classifier import OUTPUT_ONLY_ANTI_BOT_REASON_CODES, classify_from_failure_reason
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api import email
from skyvern.forge.sdk.api.aws import AsyncAWSClient
@@ -1925,14 +1925,21 @@ class Block(BaseModel, abc.ABC):
pass
+def _is_retry_blocking_anti_bot_entry(category: dict) -> bool:
+ return (
+ category.get("category") == "ANTI_BOT_DETECTION"
+ and category.get("reason_code") not in OUTPUT_ONLY_ANTI_BOT_REASON_CODES
+ )
+
+
def _should_skip_retry_on_anti_bot_detection(task: Task) -> bool:
categories = task.failure_category
if categories:
- return any(c.get("category") == "ANTI_BOT_DETECTION" for c in categories)
+ return any(_is_retry_blocking_anti_bot_entry(c) for c in categories)
if task.failure_reason:
result = classify_from_failure_reason(task.failure_reason)
- if result and any(c.get("category") == "ANTI_BOT_DETECTION" for c in result):
+ if result and any(_is_retry_blocking_anti_bot_entry(c) for c in result):
return True
return False
diff --git a/tests/unit/helpers.py b/tests/unit/helpers.py
index a0214527d..122ec94bb 100644
--- a/tests/unit/helpers.py
+++ b/tests/unit/helpers.py
@@ -10,8 +10,10 @@ from unittest.mock import AsyncMock, MagicMock
from pytest import MonkeyPatch # type: ignore[import-not-found]
+from skyvern.exceptions import MissingBrowserStatePage, get_user_facing_exception_message
from skyvern.forge import app
from skyvern.forge.agent import ForgeAgent
+from skyvern.forge.failure_classifier import classify_from_failure_reason
from skyvern.forge.sdk.api.llm import api_handler_factory
from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry
from skyvern.forge.sdk.api.llm.models import LLMRouterConfig, LLMRouterModelConfig
@@ -145,6 +147,18 @@ def router_test_context(
LLMConfigRegistry._configs.pop(llm_key, None) # type: ignore[attr-defined]
+def unsolved_captcha_relabel_categories() -> tuple[list[dict], list[dict]]:
+ """A browser loss's merge-base categories, and the same failure relabeled after an unsolved captcha."""
+ browser_loss = MissingBrowserStatePage()
+ reason = get_user_facing_exception_message(browser_loss)
+ before = classify_from_failure_reason(reason, exception=browser_loss, fallback_to_unknown=True)
+ after = classify_from_failure_reason(
+ reason, exception=browser_loss, fallback_to_unknown=True, unsolved_captcha_exception="CaptchaNotSolvedInTime"
+ )
+ assert before is not None and after is not None and after != before
+ return before, after
+
+
def make_organization(now: datetime) -> Organization:
return Organization(
organization_id="org-123",
diff --git a/tests/unit/test_context_manager.py b/tests/unit/test_context_manager.py
index 602dc19b8..77498ad1f 100644
--- a/tests/unit/test_context_manager.py
+++ b/tests/unit/test_context_manager.py
@@ -51,6 +51,7 @@ from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinit
from skyvern.schemas.workflows import BlockStatus
from tests.unit.conftest import make_block_output_parameter
from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
+from tests.unit.helpers import unsolved_captcha_relabel_categories
from tests.unit.scoped_asyncio import ScopedAsyncio
@@ -583,3 +584,27 @@ async def test_block_outcome_is_invisible_to_templates_and_the_branch_snapshot()
assert context.get_block_outcome("login") == BlockOutcome(
status=BlockStatus.failed, error_codes=["AUTH_FAILURE"], failure_reason="wrong password"
)
+
+
+async def test_templates_see_the_failure_categories_from_before_an_output_only_relabel() -> None:
+ before, after = unsolved_captcha_relabel_categories()
+ # Customer data that happens to look like a category list is not a failure_category and stays as is.
+ lookalike_rows = after
+
+ async def observe(categories: list[dict] | None) -> tuple[str, str]:
+ context = _outcome_context()
+ login_output = make_block_output_parameter("login_output")
+ await context.register_output_parameter_value_post_execution(
+ login_output, {"status": "failed", "failure_category": categories, "rows": lookalike_rows}
+ )
+ block = WaitBlock(label="login", output_parameter=login_output, wait_sec=1)
+ rendered = block.format_block_parameter_template_from_workflow_run_context(
+ "{{ login }} | {{ login_output }} | {{ workflow_run_outputs }}", context
+ )
+ branch_context = BranchEvaluationContext(workflow_run_context=context, block_label="login")
+ return rendered, json.dumps(branch_context.build_llm_safe_context_snapshot(), sort_keys=True, default=str)
+
+ rendered_after = await observe(after)
+ assert rendered_after == await observe(before)
+ assert after[0]["reason_code"] in rendered_after[0]
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index d0bd2f735..6f995faf7 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -40,6 +40,7 @@ from skyvern.forge.sdk.copilot.output_utils import (
summarize_tool_result_detail,
user_facing_success,
)
+from tests.unit.helpers import unsolved_captcha_relabel_categories
def test_sanitize_get_run_results_scrubs_nested_block_screenshots() -> None:
@@ -2440,3 +2441,24 @@ async def test_saved_workflow_reader_uses_document_privacy_projection(monkeypatc
metadata = listed["data"]["workflows"][0]
assert set(private).isdisjoint(metadata)
assert "workflow_definition" not in metadata
+
+
+def _run_tool_result(failure_category: list[dict]) -> dict[str, Any]:
+ task_output = {"task_id": "tsk_1", "status": "failed", "failure_category": failure_category}
+ return {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_1",
+ "failure_category": failure_category,
+ "blocks": [{"label": "submit", "status": "failed", "output": task_output, "extracted_data": task_output}],
+ "registered_output_parameter_values": [{"block_label": "submit", "value": task_output}],
+ },
+ }
+
+
[email protected]("tool_name", ["get_run_results", "run_blocks_and_collect_debug"])
+def test_the_model_reads_the_same_run_categories_after_an_output_only_relabel(tool_name: str) -> None:
+ before, after = unsolved_captcha_relabel_categories()
+ assert sanitize_tool_result_for_llm(tool_name, _run_tool_result(after)) == sanitize_tool_result_for_llm(
+ tool_name, _run_tool_result(before)
+ )
diff --git a/tests/unit/test_copilot_repair_origin_run.py b/tests/unit/test_copilot_repair_origin_run.py
index 5812d95db..4ffa31614 100644
--- a/tests/unit/test_copilot_repair_origin_run.py
+++ b/tests/unit/test_copilot_repair_origin_run.py
@@ -59,6 +59,7 @@ from tests.unit.copilot_test_helpers import (
run_result_block_row,
stub_copilot_agent_loop,
)
+from tests.unit.helpers import unsolved_captcha_relabel_categories
ORG = "o_1"
WPID = "wpid_1"
@@ -880,6 +881,26 @@ async def test_origin_rows_are_valued_the_way_verified_recording_values_them(
assert ORIGIN_OUTPUT_SENTINEL not in repr(source_status)
+async def test_origin_outputs_seed_the_categories_the_run_had_before_an_output_only_relabel(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "get_workflow_by_permanent_id", AsyncMock(return_value=None))
+ workflow = await inert_approval_workflow(INERT_APPROVAL_WORKFLOW_YAML, workflow_id="w_origin")
+ before, after = unsolved_captcha_relabel_categories()
+
+ def seeded(categories: list[dict] | None) -> object:
+ output = {"status": "failed", "failure_category": categories}
+ rows = merge_origin_rows(
+ origin_block_rows(workflow, "approval", status="failed", value=output),
+ origin_block_rows(workflow, "source_status", status="failed", row_output=output, registered=False),
+ )
+ snapshot = origin_block_outputs_from_rows(workflow.workflow_definition, *rows)
+ return {label: output.value for label, output in snapshot.outputs.items()}
+
+ assert seeded(after) == seeded(before)
+
+
@pytest.mark.parametrize(
("run", "expected_refusal", "loads_rows"),
[
diff --git a/tests/unit/test_fail_task_error_detection.py b/tests/unit/test_fail_task_error_detection.py
index 13b31db48..7d93d7ed9 100644
--- a/tests/unit/test_fail_task_error_detection.py
+++ b/tests/unit/test_fail_task_error_detection.py
@@ -10,13 +10,15 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.errors.errors import UserDefinedError
+from skyvern.exceptions import CaptchaNotSolvedInTime, MissingBrowserStatePage, get_user_facing_exception_message
from skyvern.forge.agent import ForgeAgent
+from skyvern.forge.failure_classifier import derive_failure_attribution
from skyvern.forge.sdk.models import StepStatus
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.schemas.steps import AgentStepOutput
from skyvern.utils.secret_redaction import REDACTED_SECRET_PLACEHOLDER
from skyvern.webeye.actions.actions import Action, ActionType
-from skyvern.webeye.actions.responses import ActionSuccess
+from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionSuccess
from tests.unit.helpers import make_organization, make_step, make_task
_EXPECTED_500 = "An HTTP request made during the download action returned HTTP 500, and no file was received."
@@ -608,3 +610,96 @@ async def test_reason_none_stays_none_even_when_updated_task_carries_a_stale_rea
assert result is True
assert mock_detect.await_args.kwargs["failure_reason"] is None
+
+
+def _captcha_failed() -> tuple[Action, list]:
+ return Action(action_type=ActionType.SOLVE_CAPTCHA), [ActionFailure(CaptchaNotSolvedInTime("task-1", "unsolved"))]
+
+
+def _captcha_solved() -> tuple[Action, list]:
+ return Action(action_type=ActionType.SOLVE_CAPTCHA), [ActionSuccess()]
+
+
+def _clicked() -> tuple[Action, list]:
+ return Action(action_type=ActionType.CLICK, element_id="submit"), [ActionSuccess()]
+
+
+def _captcha_input_failed() -> tuple[Action, list]:
+ action = Action(action_type=ActionType.INPUT_TEXT, element_id="answer")
+ return action, [ActionFailure(CaptchaNotSolvedInTime("task-1", "unsolved"))]
+
+
+def _captcha_input_solved() -> tuple[Action, list]:
+ # An input-setup captcha guard reports its solved challenge as an abort of the input action.
+ return Action(action_type=ActionType.INPUT_TEXT, element_id="answer"), [ActionAbort()]
+
+
+def _other_input_typed() -> tuple[Action, list]:
+ return Action(action_type=ActionType.INPUT_TEXT, element_id="username"), [ActionSuccess()]
+
+
+async def _classify_browser_loss_after(agent: ForgeAgent, outcomes: list) -> list[dict]:
+ """Drive fail_task with the browser-gone exception a run raises when its context closes mid-run."""
+ now = datetime.now()
+ task = make_task(now, make_organization(now))
+ prior = [
+ make_step(
+ now,
+ task,
+ step_id=f"step-{order}",
+ status=StepStatus.completed,
+ order=order,
+ output=_step_output([outcome()]),
+ )
+ for order, outcome in enumerate(outcomes)
+ ]
+ terminal = make_step(now, task, step_id="step-terminal", status=StepStatus.running, order=len(prior), output=None)
+ browser_loss = MissingBrowserStatePage()
+
+ with (
+ patch.object(agent, "update_step", new_callable=AsyncMock),
+ patch.object(agent, "update_task", new_callable=AsyncMock) as mock_update_task,
+ patch("skyvern.forge.agent.app") as mock_app,
+ ):
+ mock_update_task.side_effect = _echo_persisted_reason(task)
+ mock_app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled.return_value = False
+ mock_app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts.return_value = set()
+ mock_app.DATABASE.tasks.get_task_steps = AsyncMock(return_value=[*prior, terminal])
+
+ await agent.fail_task(task, terminal, get_user_facing_exception_message(browser_loss), exception=browser_loss)
+
+ return mock_update_task.await_args.kwargs["failure_category"]
+
+
+ "outcomes",
+ [
+ pytest.param([_clicked, _captcha_failed], id="captcha-failed-on-the-step-before"),
+ pytest.param([_captcha_failed, _clicked], id="submit-retried-after-the-captcha-failed"),
+ pytest.param([_captcha_input_failed, _other_input_typed], id="another-field-typed-after-an-input-captcha"),
+ ],
+)
+async def test_a_browser_loss_while_stuck_on_a_captcha_is_anti_bot_not_a_browser_error(agent, outcomes):
+ categories = await _classify_browser_loss_after(agent, outcomes)
+
+ assert categories[0]["category"] == "ANTI_BOT_DETECTION"
+ assert derive_failure_attribution(categories)["primary_infra_component"] != "browser"
+
+
+ "outcomes",
+ [
+ pytest.param([_clicked, _clicked], id="no-captcha"),
+ pytest.param([_captcha_failed, _captcha_solved], id="captcha-solved-after-failing"),
+ pytest.param([_captcha_input_failed, _captcha_input_solved], id="input-captcha-solved-after-failing"),
+ pytest.param([_captcha_input_failed, _captcha_solved], id="input-captcha-solved-by-a-solve-action"),
+ pytest.param([_captcha_failed, _clicked, _clicked], id="captcha-failed-steps-earlier"),
+ ],
+)
+async def test_a_browser_loss_without_an_unsolved_captcha_stays_a_browser_error(agent, outcomes):
+ categories = await _classify_browser_loss_after(agent, outcomes)
+
+ assert categories[0]["category"] == "BROWSER_ERROR"
+ assert derive_failure_attribution(categories)["primary_infra_component"] == "browser"
diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.py
index 731a5b433..86bb5fc6d 100644
--- a/tests/unit/test_failure_classifier.py
+++ b/tests/unit/test_failure_classifier.py
@@ -721,6 +721,31 @@ def test_derive_end_to_end_from_real_classifier_output() -> None:
assert derive_failure_attribution(fc)["primary_infra_component"] == "proxy"
+ "browser_loss",
+ [
+ pytest.param(skyvern_exceptions.MissingBrowserStatePage(), id="page-missing"),
+ pytest.param(
+ skyvern_exceptions.ScreenshotTargetClosed("Target page, context or browser has been closed"),
+ id="target-closed",
+ ),
+ ],
+)
+def test_an_unsolved_captcha_outranks_the_browser_loss_that_ended_the_run(browser_loss: Exception) -> None:
+ categories = classify_from_failure_reason(
+ skyvern_exceptions.get_user_facing_exception_message(browser_loss),
+ exception=browser_loss,
+ fallback_to_unknown=True,
+ unsolved_captcha_exception="CaptchaNotSolvedInTime",
+ )
+
+ assert categories is not None
+ assert categories[0]["category"] == "ANTI_BOT_DETECTION"
+ assert categories[0]["evidence_source"] == "exception_type"
+ assert "BROWSER_ERROR" in [category["category"] for category in categories]
+ assert derive_failure_attribution(categories)["primary_infra_component"] != "browser"
+
+
def test_derive_parameter_binding_error_maps_to_worker() -> None:
# PM adjudication: an internal configuration mismatch is owned by the worker in v1.
fc = [{"category": "PARAMETER_BINDING_ERROR", "confidence_float": 0.95, "reasoning": "Keywords matched"}]
diff --git a/tests/unit/workflow/test_block_anti_bot_retry_skip.py b/tests/unit/workflow/test_block_anti_bot_retry_skip.py
index 08d5b5bdf..773586ce7 100644
--- a/tests/unit/workflow/test_block_anti_bot_retry_skip.py
+++ b/tests/unit/workflow/test_block_anti_bot_retry_skip.py
@@ -2,6 +2,15 @@ from __future__ import annotations
from datetime import datetime, timezone
+import pytest
+
+from skyvern.exceptions import (
+ BrowserSessionDegraded,
+ MissingBrowserStatePage,
+ ScreenshotTargetClosed,
+ get_user_facing_exception_message,
+)
+from skyvern.forge.failure_classifier import classify_from_failure_reason
from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.forge.sdk.workflow.models.block import _should_skip_retry_on_anti_bot_detection
@@ -105,3 +114,34 @@ class TestFallbackFromReason:
failure_reason="Access denied after login - user does not have permission",
)
assert _should_skip_retry_on_anti_bot_detection(task) is False
+
+
+_BROWSER_LOSSES = [
+ pytest.param(MissingBrowserStatePage(), id="page-missing"),
+ pytest.param(ScreenshotTargetClosed("Target page, context or browser has been closed"), id="target-closed"),
+ pytest.param(BrowserSessionDegraded(3, "screenshot"), id="browser-degraded"),
+]
+
+
[email protected]("browser_loss", _BROWSER_LOSSES)
+ "reason_suffix",
+ [
+ pytest.param("", id="exception-message-only"),
+ pytest.param(" A captcha challenge was still on the page.", id="reason-also-names-a-captcha"),
+ ],
+)
+def test_the_unsolved_captcha_relabel_leaves_the_retry_decision_unchanged(
+ browser_loss: Exception, reason_suffix: str
+) -> None:
+ """Categorization is output-only: relabeling a browser loss as anti-bot must not stop a block retry."""
+ reason = get_user_facing_exception_message(browser_loss) + reason_suffix
+ before = classify_from_failure_reason(reason, exception=browser_loss, fallback_to_unknown=True)
+ after = classify_from_failure_reason(
+ reason, exception=browser_loss, fallback_to_unknown=True, unsolved_captcha_exception="CaptchaNotSolvedInTime"
+ )
+
+ assert after is not None and after[0]["category"] == "ANTI_BOT_DETECTION"
+ assert _should_skip_retry_on_anti_bot_detection(
+ _make_failed_task(failure_reason=reason, failure_category=after)
+ ) is _should_skip_retry_on_anti_bot_detection(_make_failed_task(failure_reason=reason, failure_category=before))