Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Classify a site rate-limit or 403 page as bot protection, not an AI model error (#8824)
Shuchang Zheng4b95f97e6c45
diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.pyindex 6daf1c432..da494170d 100644--- a/skyvern/forge/failure_classifier.py+++ b/skyvern/forge/failure_classifier.py@@ -57,6 +57,73 @@ _NO_ADDRESS_RECORD_MARKER_LOWER = NO_ADDRESS_RECORD_NAV_ERROR_MARKER.lower()# text (a model-written outcome reason, the navigated URL) can mention a transport code the proxy never raised._NAV_FAILURE_DRIVER_MESSAGE_RE = re.compile(r"failed to navigate to url \S+\. error message: (.*)", re.DOTALL)_URL_RE = re.compile(r"[a-z][a-z0-9+.-]*://\S+")+# Throttle or block wording is never an LLM provider failure. In a browser-agent reason it is the site's own page+# (bot protection); in an integration's reason it is the called service throttling us (a website error).+_SITE_THROTTLE_RE = re.compile(+ r"\brate[\s-]?limit|too many requests|requested too many times|\b(?:http|status(?: code)?|error)\s*:?\s*429\b"+)+_SITE_FORBIDDEN_RE = re.compile(r"\b403 (?:error|forbidden)\b|\b(?:http|status(?: code)?|error)\s*:?\s*403\b")+# Integration, vault and storage APIs report their own quota or status, which no site produced. Each "<block_type>+# block failed|terminated|timed out" prefix (loops, conditionals and workflow triggers forward their child's) is read+# before the reason it wraps, and an unlisted block type counts as an integration so a new one is never labeled bot+# protection.+_BLOCK_FAILURE_PREFIX_RE = re.compile(+ r"\s*([a-z][a-z0-9_]*) block (?:failed|terminated|timed out)\b(?:\.\s*(?:failure reason|reason):\s*)?"+)+_BROWSER_AGENT_BLOCK_TYPES = frozenset(+ {"task", "task_v2", "navigation", "extraction", "login", "action", "validation", "file_download", "goto_url"}+)+_BLOCK_WRAPPER_TYPES = frozenset({"for_loop", "while_loop", "conditional", "workflow_trigger"})+# A code block drives the page, so a CAPTCHA it reports is the site's even though it is not a browser-agent block.+_PAGE_DRIVING_CODE_BLOCK_TYPES = frozenset({"code"})+# Our own code writes these before a task starts, so no browser agent wrote the text that follows.+_PRE_TASK_FAILURE_PREFIXES = (+ "failed to download file from google drive",+ "setup workflow failed",+ "failed to initialize workflow run context",+)+# Run setup and context initialization fail before any page loads; their reasons are credential-vault and API errors.+# The "failed to send" entries name their producer, because a task's own reason can open with a bare "Failed to send".+_NON_SITE_FAILURE_PREFIXES = (+ *_PRE_TASK_FAILURE_PREFIXES,+ "google sheets ",+ "reconnect the google account",+ "http request failed",+ "failed to send human interaction email",+ "failed to send webhook",+ "failed to send downloaded file",+ "failed to upload file to ",+ "1password ",+ "bitwarden ",+ "azure error:",+)+# Wording only our own LLM failure paths produce: every LLMProviderError message names "LLMProvider" whatever the+# cause class, and the max-steps summary says "LLM service errors".+_LLM_ORIGIN_TEXT_MARKERS = ("llm rate limit", "llmprovider", "ratelimiterror", "llm service error")+++def _non_agent_block_type(reason: str) -> tuple[str | None, str]:+ """The first prefixed block type that is neither a browser agent nor a wrapper, and the reason it prefixes."""+ while prefix := _BLOCK_FAILURE_PREFIX_RE.match(reason):+ block_type = prefix.group(1)+ if block_type not in _BROWSER_AGENT_BLOCK_TYPES and block_type not in _BLOCK_WRAPPER_TYPES:+ return block_type, reason+ reason = reason[prefix.end() :]+ return None, reason.lstrip()+++def _is_non_site_failure(reason: str) -> bool:+ block_type, inner_reason = _non_agent_block_type(reason)+ return block_type is not None or inner_reason.startswith(_NON_SITE_FAILURE_PREFIXES)+++# Narrower than _is_non_site_failure, because it removes an anti-bot label instead of adding one. A task's own+# failure reason can start with "Failed to send" in the model's words, and the task block retry loop reads it.+def _is_pageless_failure(reason: str) -> bool:+ block_type, inner_reason = _non_agent_block_type(reason)+ if block_type is not None:+ return block_type not in _PAGE_DRIVING_CODE_BLOCK_TYPES+ return inner_reason.startswith(_PRE_TASK_FAILURE_PREFIXES)def _proxy_transport_evidence(reason: str, exception: Exception | None) -> str | None:@@ -154,7 +221,20 @@ def classify_from_failure_reason(if not _has_auth_context:_antibot_keywords.append("access denied")- if any(kw in reason for kw in _antibot_keywords):+ _is_llm_exception = any(kw in exc_name for kw in ["LLM", "APIError", "RateLimit"])+ _has_llm_origin_text = any(marker in reason for marker in _LLM_ORIGIN_TEXT_MARKERS)+ _is_llm_origin = _is_llm_exception or _has_llm_origin_text+ _is_non_site = _is_non_site_failure(reason)+ _has_throttle_wording = bool(_SITE_THROTTLE_RE.search(reason))+ # A 403 is ambiguous like "access denied": with auth context it is a permission failure, not a bot block.+ _is_site_block = (+ not _is_llm_origin+ and not _is_non_site+ and (_has_throttle_wording or (not _has_auth_context and bool(_SITE_FORBIDDEN_RE.search(reason))))+ )++ # "http_request block failed" contains "request block", so integration failures skip the keyword list.+ if not _is_pageless_failure(reason) and any(kw in reason for kw in _antibot_keywords):categories.append({"category": FailureCategory.ANTI_BOT_DETECTION.value,@@ -165,6 +245,28 @@ def classify_from_failure_reason("evidence_source": "keyword_only",})+ elif _is_site_block:+ categories.append(+ {+ "category": FailureCategory.ANTI_BOT_DETECTION.value,+ "confidence_float": 0.7,+ "reasoning": "Site rate-limit or 403 wording in failure reason",+ "evidence_source": "keyword_only",+ # Lets runtime consumers keep treating this entry as they did before it was anti-bot.+ "reason_code": SITE_THROTTLE_REASON_CODE,+ }+ )+ # An integration or third-party API throttled our call: not our infrastructure, the model, or bot protection.+ elif _has_throttle_wording and _is_non_site and not _is_llm_origin:+ categories.append(+ {+ "category": FailureCategory.WEBSITE_ERROR.value,+ "confidence_float": 0.7,+ "reasoning": "External service rate-limit wording in an integration failure reason",+ "evidence_source": "keyword_match",+ "reason_code": EXTERNAL_SERVICE_THROTTLE_REASON_CODE,+ }+ )# Proxy errors — check before browser errors so proxy failures don't fall into BROWSER_ERROR.# The exception name may contain "Browser" (e.g. UnknownErrorWhileCreatingBrowserContext) but the@@ -350,7 +452,8 @@ def classify_from_failure_reason()# LLM error- if any(kw in exc_name for kw in ["LLM", "APIError", "RateLimit"]) or "rate limit" in reason:+ # Free text says "rate limit" about a site's page as well, so it counts only with LLM-origin wording.+ if _is_llm_exception or ("rate limit" in reason and _has_llm_origin_text):categories.append({"category": FailureCategory.LLM_ERROR.value,@@ -474,7 +577,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 = 6+CLASSIFIER_VERSION = 7FAILURE_ATTRIBUTION_SCHEMA_VERSION = 1# Bounded sentinels — neither is an infra component id.@@ -495,11 +598,15 @@ BROWSER_SESSION_STARTUP_TIMEOUT_REASON_CODE = "browser_session_startup_timeout"BROWSER_SESSION_EXPIRED_BEFORE_RUN_REASON_CODE = "browser_session_expired_before_run"PROXY_TRANSPORT_FAILED_REASON_CODE = "proxy_transport_failed"UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE = "unsolved_captcha_before_browser_loss"+SITE_THROTTLE_REASON_CODE = "site_throttle"+EXTERNAL_SERVICE_THROTTLE_REASON_CODE = "external_service_throttle"# 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})+OUTPUT_ONLY_ANTI_BOT_REASON_CODES = frozenset(+ {UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE, SITE_THROTTLE_REASON_CODE}+)def is_output_only_anti_bot_entry(category: object) -> bool:@@ -549,8 +656,8 @@ def _scrub_output_only_anti_bot(value: Any) -> Any:# 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-# above (same file); the browser-session codes are emitted by the browser-lease producer.+# not copied. secure_codeblock_*/locator_wait_for_timeout/site_throttle/external_service_throttle are emitted by+# classify_from_failure_reason above (same file); the browser-session codes are emitted by the browser-lease producer._REASON_CODE_LITERALS = frozenset({"secure_codeblock_runner_unavailable",@@ -563,6 +670,8 @@ _REASON_CODE_LITERALS = frozenset(BROWSER_SESSION_STARTUP_TIMEOUT_REASON_CODE,BROWSER_SESSION_EXPIRED_BEFORE_RUN_REASON_CODE,PROXY_TRANSPORT_FAILED_REASON_CODE,+ SITE_THROTTLE_REASON_CODE,+ EXTERNAL_SERVICE_THROTTLE_REASON_CODE,UNSOLVED_CAPTCHA_BEFORE_BROWSER_LOSS_REASON_CODE,})diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pyindex 4b8c86477..e60368859 100644--- a/tests/unit/test_failure_classifier.py+++ b/tests/unit/test_failure_classifier.py@@ -22,6 +22,7 @@ from skyvern.forge.failure_classifier import (classify_from_failure_reason,derive_failure_attribution,)+from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError as ProviderLLMErrorfrom skyvern.webeye.scraper.scraper import build_scraping_failed_reason@@ -100,6 +101,14 @@ class RateLimitExceeded(Exception):pass+class RateLimitError(Exception):+ pass+++class ThrottlingException(Exception):+ pass++class ScrapingFailedError(Exception):pass@@ -246,6 +255,215 @@ def test_broad_blocked_and_forbidden_do_not_match_antibot() -> None:assert "ANTI_BOT_DETECTION" not in [r["category"] for r in result], reason+ "reason",+ [+ pytest.param(+ "navigation block terminated. Reason: The site returned Cloudflare Error 1015 (HTTP 429: temporarily "+ "rate limited/banned) when accessing the update URL, so the form could not be submitted.",+ id="cloudflare-1015",+ ),+ pytest.param(+ "navigation block terminated. Reason: Page indicates 403 error or rate limit; cannot proceed with opt-out.",+ id="model-hedged-403-or-rate-limit",+ ),+ pytest.param(+ "navigation block terminated. Reason: The site says this page was requested too many times.",+ id="requested-too-many-times",+ ),+ pytest.param("The site returned a 403 Forbidden page; the form cannot be reached.", id="forbidden-page"),+ pytest.param(+ "for_loop block failed. failure reason: Page indicates 403 error or rate limit; cannot proceed.",+ id="site-page-in-loop",+ ),+ pytest.param(+ "goto_url block terminated. Reason: The page shows HTTP 429 Too Many Requests.", id="goto-url-page"+ ),+ pytest.param(+ "task block failed. failure reason: The website displayed 'Too many requests, please try again later' "+ "(HTTP 429) and blocked further navigation.",+ id="task-site-429-page",+ ),+ pytest.param(+ "navigation block failed. failure reason: The page returned 403 Forbidden after submitting the form.",+ id="navigation-site-403-page",+ ),+ pytest.param(+ "task block failed. failure reason: Failed to send the form: the site shows HTTP 429 Too Many Requests",+ id="task-reason-opening-with-failed-to-send",+ ),+ pytest.param(+ "Failed to send the form: the site shows HTTP 429 Too Many Requests", id="raw-task-reason-failed-to-send"+ ),+ pytest.param(+ "workflow_trigger block failed. failure reason: navigation block terminated. Reason: The page shows "+ "HTTP 429 Too Many Requests.",+ id="site-page-in-child-workflow",+ ),+ ],+)+def test_site_throttle_or_block_page_is_antibot_not_llm_error(reason: str) -> None:+ categories = _classify(reason)++ assert categories[0]["category"] == "ANTI_BOT_DETECTION"+ assert "LLM_ERROR" not in [category["category"] for category in categories]+ assert derive_failure_attribution(categories)["primary_infra_component"] == "unattributed"+++def test_words_that_merely_end_in_rate_are_not_a_site_throttle() -> None:+ assert classify_from_failure_reason("The corporate limit field is required but empty") is None+++ ("reason", "exception"),+ [+ pytest.param(+ "navigation block failed. failure reason: "+ + str(ProviderLLMError("GEMINI_2_5_FLASH", cause=RateLimitError("Rate limit reached for the model"))),+ None,+ id="provider-error-text",+ ),+ pytest.param(+ "The task failed due to LLM service errors. This is typically caused by rate limiting, service outages, "+ "or resource exhaustion from the LLM provider.",+ None,+ id="max-steps-llm-summary",+ ),+ pytest.param("navigation block failed. failure reason: HTTP 429", RateLimitError("429"), id="exception-object"),+ pytest.param(+ "text_prompt block failed. failure reason: "+ + str(ProviderLLMError("GPT_5", cause=RateLimitError("Rate limit reached for the model"))),+ None,+ id="provider-error-in-non-browser-block",+ ),+ ],+)+def test_llm_rate_limit_is_still_llm_error(reason: str, exception: Exception | None) -> None:+ categories = _classify(reason, exception, fallback_to_unknown=True)+ names = [category["category"] for category in categories]++ assert names[0] == "LLM_ERROR"+ assert "ANTI_BOT_DETECTION" not in names+ assert "WEBSITE_ERROR" not in names+ assert derive_failure_attribution(categories)["primary_infra_component"] == "llm"+++ "reason",+ [+ pytest.param("Google Sheets rate limit on write: quota exceeded", id="sheets-raw"),+ pytest.param(+ "google_sheets_write block failed. failure reason: Google Sheets rate limit on write: quota exceeded",+ id="sheets-workflow-level",+ ),+ pytest.param("HTTP request failed: 429 Too Many Requests from the target API", id="http-request-raw"),+ pytest.param(+ "send_email block failed. failure reason: 429 Too Many Requests from the mail API", id="email-workflow"+ ),+ pytest.param(+ "for_loop block failed. failure reason: Google Sheets rate limit on write: quota exceeded",+ id="sheets-in-loop",+ ),+ pytest.param(+ "conditional block terminated. Reason: for_loop block failed. failure reason: "+ "Google Sheets rate limit on read: quota exceeded",+ id="sheets-in-loop-in-conditional",+ ),+ pytest.param(+ "while_loop block failed. failure reason: Failed to send human interaction email: 429 Too Many Requests",+ id="human-interaction-email-in-loop",+ ),+ pytest.param(+ "Failed to send human interaction email: 429 Too Many Requests from the mail API",+ id="human-interaction-email-raw",+ ),+ pytest.param(+ "file_download block failed. failure reason: Failed to send downloaded file(s) to s3: 429 Too Many Requests",+ id="file-download-storage-throttle",+ ),+ pytest.param(+ "file_download block failed. failure reason: Failed to download file from Google Drive: "+ '<HttpError 429 when requesting https://www.googleapis.com/drive/v3/files/abc?alt=media returned "User '+ 'rate limit exceeded.">',+ id="drive-api-in-browser-block",+ ),+ pytest.param(+ "google_sheets_read block failed. failure reason: Google Sheets read failed: 429 Too Many Requests: "+ "rate limit exceeded",+ id="sheets-read-429",+ ),+ pytest.param(+ "http_request block failed. failure reason: HTTP request failed: 429 Too Many Requests",+ id="http-request-block-429",+ ),+ pytest.param(+ "http_request block failed. failure reason: HTTP 403: {'detail': 'User rate limit exceeded.'}",+ id="http-request-block-api-quota",+ ),+ pytest.param(+ "Failed to initialize workflow run context. failure reason: "+ + str(skyvern_exceptions.OnePasswordRateLimitError("Too many requests")),+ id="vault-throttle-at-run-start",+ ),+ ],+)+def test_integration_or_api_throttle_is_website_error(reason: str) -> None:+ categories = _classify(reason, fallback_to_unknown=True)+ names = [category["category"] for category in categories]++ assert names[0] == "WEBSITE_ERROR"+ assert "ANTI_BOT_DETECTION" not in names+ assert "LLM_ERROR" not in names+ assert derive_failure_attribution(categories)["primary_infra_component"] == "non_infra"+++def test_llm_provider_throttle_is_neither_bot_protection_nor_a_website_error() -> None:+ reason = "navigation block failed. failure reason: " + str(+ ProviderLLMError("BEDROCK_SONNET", cause=ThrottlingException("Too many requests, please wait"))+ )++ names = _categories_for(reason, fallback_to_unknown=True)++ assert "ANTI_BOT_DETECTION" not in names+ assert "WEBSITE_ERROR" not in names+++# A pageless failure's text says nothing about a site, and "http_request block" itself contains "request block".+# A failure from a block that drives the page keeps today's keyword label.+ ("reason", "is_antibot"),+ [+ pytest.param("http_request block failed. failure reason: HTTP 404: Not Found", False, id="http-request-404"),+ pytest.param(+ "for_loop block failed. failure reason: http_request block failed. failure reason: HTTP 401: Unauthorized",+ False,+ id="http-request-in-loop",+ ),+ pytest.param(+ "send_email block failed. failure reason: File access denied: path must not be empty",+ False,+ id="send-email-file-access-denied",+ ),+ pytest.param("code block failed. failure reason: CAPTCHA could not be solved.", True, id="code-block-captcha"),+ pytest.param(+ "task block failed. failure reason: Failed to send the form because a captcha appeared",+ True,+ id="task-reason-starting-like-an-integration",+ ),+ pytest.param(+ "workflow_trigger block failed. failure reason: navigation block terminated. Reason: A Cloudflare "+ "challenge blocked the page.",+ True,+ id="child-workflow-captcha",+ ),+ ],+)+def test_antibot_keywords_skip_only_pageless_failures(reason: str, is_antibot: bool) -> None:+ names = _categories_for(reason, fallback_to_unknown=True)++ assert ("ANTI_BOT_DETECTION" in names) is is_antibot++def test_multiple_categories_are_sorted_by_confidence_descending() -> None:result = _classify("Reached the max steps because captcha kept appearing")@@ -412,7 +630,7 @@ def test_user_code_crash_mentioning_process_exit_is_not_infrastructure() -> Nonepytest.param("http_request block failed. failure reason: HTTP 500: ", id="http-request-block-500"),],)-def test_website_error_comes_only_from_the_model_never_from_failure_prose(reason: str) -> None:+def test_a_server_error_is_website_error_only_when_the_model_says_so(reason: str) -> None:categories = classify_from_failure_reason(reason, fallback_to_unknown=True) or []assert "WEBSITE_ERROR" not in [category["category"] for category in categories]diff --git a/tests/unit/workflow/test_block_anti_bot_retry_skip.py b/tests/unit/workflow/test_block_anti_bot_retry_skip.pyindex 773586ce7..1988fb09d 100644--- a/tests/unit/workflow/test_block_anti_bot_retry_skip.py+++ b/tests/unit/workflow/test_block_anti_bot_retry_skip.py@@ -116,6 +116,37 @@ class TestFallbackFromReason:assert _should_skip_retry_on_anti_bot_detection(task) is False+# Each decision was recorded from the classifier before site rate-limit and 403 wording was labeled anti-bot and+# before integration throttles were labeled website errors. Those labels are bookkeeping: a failure that kept its+# retries then must keep them now, and one that skipped them must still skip them.+ ("reason", "skips_retry"),+ [+ pytest.param(+ "Failed to send the form because a captcha appeared", True, id="captcha-reason-worded-like-integration"+ ),+ pytest.param("HTTP request failed: 429 Too Many Requests", False, id="http-request-throttle"),+ pytest.param(+ "The site returned Cloudflare Error 1015 (HTTP 429: temporarily rate limited/banned).",+ True,+ id="cloudflare-keyword-with-429",+ ),+ pytest.param("Page indicates 403 error or rate limit; cannot proceed.", False, id="hedged-403-or-rate-limit"),+ pytest.param("The site says this page was requested too many times.", False, id="requested-too-many-times"),+ pytest.param("The site returned a 403 Forbidden page.", False, id="forbidden-page"),+ pytest.param("Google Sheets rate limit on write: quota exceeded", False, id="sheets-quota"),+ pytest.param("Page blocked by captcha challenge", True, id="captcha"),+ pytest.param("Access denied: rate limit exceeded", True, id="access-denied-with-rate-limit"),+ ],+)+def test_site_throttle_labeling_does_not_change_the_retry_decision(reason: str, skips_retry: bool) -> None:+ from_reason = _make_failed_task(failure_reason=reason)+ from_persisted = _make_failed_task(failure_category=classify_from_failure_reason(reason, fallback_to_unknown=True))++ assert _should_skip_retry_on_anti_bot_detection(from_reason) is skips_retry+ assert _should_skip_retry_on_anti_bot_detection(from_persisted) is skips_retry++_BROWSER_LOSSES = [pytest.param(MissingBrowserStatePage(), id="page-missing"),pytest.param(ScreenshotTargetClosed("Target page, context or browser has been closed"), id="target-closed"),