Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Route CDP retry/connection classification through the selected engine (RUS-5) (#7810)
LawyZhenga754c0581976
diff --git a/skyvern/webeye/cdp_retry.py b/skyvern/webeye/cdp_retry.pyindex bef716de7..4e19fa26f 100644--- a/skyvern/webeye/cdp_retry.py+++ b/skyvern/webeye/cdp_retry.py@@ -1,7 +1,7 @@from __future__ import annotationsimport asyncio-from typing import cast+from typing import TYPE_CHECKING, castimport structlogfrom playwright._impl._errors import Error as PWError@@ -10,8 +10,16 @@ from playwright._impl._errors import TimeoutError as PWTimeoutErrorfrom playwright.async_api import Browser, Playwrightfrom skyvern.config import settings+from skyvern.webeye.browser_errors import (+ BrowserCdpConnectionError,+ BrowserTargetClosedError,+ BrowserTimeoutError,+)from skyvern.webeye.cdp_connection import strip_browser_address_discriminator+if TYPE_CHECKING:+ from skyvern.webeye.browser_engine import BrowserEngineSelection+LOG = structlog.get_logger()_CDP_CONNECTION_ERROR_SUBSTR_FALLBACK = (@@ -22,13 +30,46 @@ _CDP_CONNECTION_ERROR_SUBSTR_FALLBACK = ("browser has been closed",)+# Stdlib/OS-level socket failures that mean a retryable CDP connect problem no matter which engine is+# selected: they are raised beneath every driver, so no engine's native error families own them. Kept+# as the shared floor under both the selection-aware and stock paths so migrating classification to a+# selected engine never drops the cross-engine transport signal.+_CDP_CONNECTION_TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (+ ConnectionRefusedError,+ ConnectionResetError,+ TimeoutError,+)+-def is_cdp_connection_error(exc: Exception) -> bool:- if isinstance(- exc, (PWTimeoutError, PWTargetClosedError, ConnectionRefusedError, ConnectionResetError, TimeoutError)- ):+def _has_transport_substring(exc: BaseException) -> bool:+ return any(s in str(exc).lower() for s in _CDP_CONNECTION_ERROR_SUBSTR_FALLBACK)+++def is_cdp_connection_error(exc: Exception, selection: BrowserEngineSelection | None = None) -> bool:+ """Decide whether a failed CDP connect/attach is a retryable connection error.++ With no ``selection`` (no engine authority at this call site) classification uses stock+ Playwright's error identities exactly as before, so the default path is byte-for-byte unchanged.+ With a ``selection`` the retry decision keys off THAT run's selected-engine error families+ (retryable-CDP / CDP-connection / target-closed / timeout) via the engine-neutral classifier, so a+ non-stock engine's native classes are recognized instead of stock Playwright's — and a foreign+ error (one this engine never raises) is not classified, so it falls through to ``False`` and the+ caller re-raises it rather than retrying blindly. Under both paths the engine-neutral transport+ floor still applies: stdlib socket errors always retry, and the engine's OWN base error carrying a+ known transport substring retries (guarded by engine identity so a foreign error with a+ coincidentally-matching message never does). This is a retry predicate only; it never wraps or+ normalizes ``exc`` — the native exception the caller re-raises stays intact.+ """+ if isinstance(exc, _CDP_CONNECTION_TRANSPORT_ERRORS):+ return True+ if selection is not None:+ classified = selection.classify_error(exc)+ if isinstance(classified, (BrowserCdpConnectionError, BrowserTargetClosedError, BrowserTimeoutError)):+ return True+ return selection.is_engine_error(exc) and _has_transport_substring(exc)+ if isinstance(exc, (PWTimeoutError, PWTargetClosedError)):return True- if isinstance(exc, PWError) and any(s in str(exc).lower() for s in _CDP_CONNECTION_ERROR_SUBSTR_FALLBACK):+ if isinstance(exc, PWError) and _has_transport_substring(exc):return Truereturn False@@ -62,6 +103,7 @@ async def connect_over_cdp_with_retry(browser_address: str,headers: dict[str, str] | None = None,log_browser_address: str | None = None,+ selection: BrowserEngineSelection | None = None,) -> Browser:browser_address = strip_browser_address_discriminator(browser_address)browser_address_for_logs = log_browser_address or browser_address@@ -77,7 +119,7 @@ async def connect_over_cdp_with_retry()return browserexcept Exception as e:- if not is_cdp_connection_error(e) or attempt == max_attempts:+ if not is_cdp_connection_error(e, selection) or attempt == max_attempts:# When the caller passed log_browser_address as a safe label, the raw# browser_address may carry session tokens in path/query — Playwright's# exception text would otherwise expose them. Re-raise a RuntimeError@@ -93,6 +135,7 @@ async def connect_over_cdp_with_retry(max_attempts=max_attempts,backoff_seconds=backoff,error_type=type(e).__name__,+ browser_engine=selection.name if selection is not None else None,)await _sleep(backoff)raise RuntimeError("unreachable")diff --git a/tests/unit/test_cdp_connection_retry.py b/tests/unit/test_cdp_connection_retry.pyindex 6b703dfca..08b75cf58 100644--- a/tests/unit/test_cdp_connection_retry.py+++ b/tests/unit/test_cdp_connection_retry.py@@ -1,5 +1,6 @@from __future__ import annotations+from typing import Any, castfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -7,9 +8,30 @@ from playwright._impl._errors import Error as PWErrorfrom playwright._impl._errors import TimeoutError as PWTimeoutErrorfrom skyvern.config import settings+from skyvern.webeye.browser_engine import BrowserEngineMetadata, BrowserEngineSelectionfrom skyvern.webeye.cdp_retry import _resolve_retry_budget, connect_over_cdp_with_retry+class _FakeEngineError(Exception):+ pass+++class _FakeEngineRetryable(_FakeEngineError):+ pass+++def _fake_selection() -> BrowserEngineSelection:+ return BrowserEngineSelection(+ name="fake",+ start_driver=cast(Any, lambda: None),+ error_type=_FakeEngineError,+ timeout_error_type=_FakeEngineError,+ metadata=BrowserEngineMetadata(name="fake"),+ selection_reason="test-fake",+ retryable_error_types=(_FakeEngineRetryable,),+ )++def _make_playwright(side_effect):pw = MagicMock()pw.chromium.connect_over_cdp = AsyncMock(side_effect=side_effect)@@ -200,6 +222,28 @@ class TestRetryBudget:_, backoff = _resolve_retry_budget()assert backoff == (1, 2, 3, 4, 5)+ @pytest.mark.asyncio+ async def test_selected_engine_retryable_error_is_retried(self, monkeypatch):+ """A selected engine's own retryable-CDP class (foreign to Playwright) is recognized via the+ selection and retried, then recovered — proving the retry loop forwards ``selection`` to the+ classifier instead of relying on Playwright's hardcoded identities."""+ _set_budget(monkeypatch, attempts=3, backoff=[1, 2])+ pw = _make_playwright([_FakeEngineRetryable("transient CDP disconnect"), "browser"])+ with patch("skyvern.webeye.cdp_retry._sleep", new_callable=AsyncMock) as mock_sleep:+ result = await connect_over_cdp_with_retry(pw, "http://10.0.0.1:9224", selection=_fake_selection())+ assert result == "browser"+ assert pw.chromium.connect_over_cdp.call_count == 2+ mock_sleep.assert_called_once_with(1)++ @pytest.mark.asyncio+ async def test_selected_engine_foreign_error_is_not_retried(self):+ """Under a non-stock selection a foreign Playwright error is not a recognized connection+ error, so it is raised immediately (never swallowed by a blind retry)."""+ pw = _make_playwright([PWTimeoutError("Timeout 30000ms exceeded.")])+ with pytest.raises(PWTimeoutError):+ await connect_over_cdp_with_retry(pw, "http://10.0.0.1:9224", selection=_fake_selection())+ assert pw.chromium.connect_over_cdp.call_count == 1+@pytest.mark.asyncioasync def test_slow_to_bind_local_port_reconnects_on_a_later_attempt(self, monkeypatch):"""Stealth Chromium that is slow to bind 127.0.0.1:9222 is reconnected once thediff --git a/tests/unit/test_cdp_error_detection.py b/tests/unit/test_cdp_error_detection.pyindex 90f14972e..c196b6d4c 100644--- a/tests/unit/test_cdp_error_detection.py+++ b/tests/unit/test_cdp_error_detection.py@@ -1,13 +1,60 @@from __future__ import annotations+from typing import Any, cast+import pytestfrom playwright._impl._errors import Error as PWErrorfrom playwright._impl._errors import TargetClosedError as PWTargetClosedErrorfrom playwright._impl._errors import TimeoutError as PWTimeoutError+from skyvern.webeye.browser_engine import (+ REGISTRY,+ STOCK_ENGINE_NAME,+ BrowserEngineMetadata,+ BrowserEngineSelection,+)from skyvern.webeye.cdp_retry import is_cdp_connection_error+class _FakeEngineError(Exception):+ """Base native error for a hypothetical non-stock engine (foreign to Playwright)."""+++class _FakeEngineTimeout(_FakeEngineError):+ pass+++class _FakeEngineTargetClosed(_FakeEngineError):+ pass+++class _FakeEngineCdpConnection(_FakeEngineError):+ pass+++class _FakeEngineRetryable(_FakeEngineCdpConnection):+ pass+++def _stock_selection() -> BrowserEngineSelection:+ return REGISTRY.get(STOCK_ENGINE_NAME).select(selection_reason="test-stock")+++def _rich_fake_selection() -> BrowserEngineSelection:+ """A non-stock selection that binds the richer CDP/target-closed/retryable families #14003 added."""+ return BrowserEngineSelection(+ name="fake",+ start_driver=cast(Any, lambda: None),+ error_type=_FakeEngineError,+ timeout_error_type=_FakeEngineTimeout,+ metadata=BrowserEngineMetadata(name="fake"),+ selection_reason="test-fake",+ target_closed_error_types=(_FakeEngineTargetClosed,),+ cdp_connection_error_types=(_FakeEngineCdpConnection,),+ retryable_error_types=(_FakeEngineRetryable,),+ )++class TestConnectionErrorDetection:@pytest.mark.parametrize("exc",@@ -38,3 +85,54 @@ class TestConnectionErrorDetection:)def test_app_errors_not_detected(self, exc: Exception):assert not is_cdp_connection_error(exc), f"Expected app error NOT to match: {exc!r}"+++class TestSelectionAwareDetection:+ """A ``selection`` keys the retry decision off the run's selected-engine error families instead+ of stock Playwright's hardcoded classes, while an absent/None selection is byte-for-byte the+ stock path and the engine-neutral transport floor applies under both."""++ _STOCK_CASES = [+ PWTimeoutError("Timeout 30000ms exceeded."),+ PWTargetClosedError("Target page, context or browser has been closed"),+ ConnectionRefusedError("connect ECONNREFUSED 10.0.36.234:9224"),+ ConnectionResetError("connect ECONNRESET"),+ PWError("BrowserType.connect_over_cdp: connect ECONNREFUSED 10.0.36.234:9224"),+ PWError("Browser closed."),+ PWError("net::ERR_NAME_NOT_RESOLVED"),+ PWError("Navigation timeout exceeded"),+ ValueError("Element not found"),+ ]++ @pytest.mark.parametrize("exc", _STOCK_CASES, ids=lambda e: type(e).__name__ + ": " + str(e)[:40])+ def test_stock_selection_matches_no_selection(self, exc: Exception) -> None:+ # Passing the resolved stock-Playwright selection must never diverge from the legacy None path.+ assert is_cdp_connection_error(exc, _stock_selection()) == is_cdp_connection_error(exc)++ def test_selected_engine_native_families_are_retryable(self) -> None:+ selection = _rich_fake_selection()+ for exc in (+ _FakeEngineRetryable("transient disconnect"),+ _FakeEngineCdpConnection("cdp transport failure"),+ _FakeEngineTargetClosed("target closed"),+ _FakeEngineTimeout("deadline exceeded"),+ ):+ assert is_cdp_connection_error(exc, selection), f"Expected retryable for {exc!r}"++ def test_selected_engine_generic_base_error_is_not_retried(self) -> None:+ # A recognized-but-generic engine error (no transport signal) is not a connection error.+ assert not is_cdp_connection_error(_FakeEngineError("element detached"), _rich_fake_selection())++ def test_selected_engine_base_error_with_transport_substring_is_retried(self) -> None:+ assert is_cdp_connection_error(_FakeEngineError("connect ECONNREFUSED 10.0.0.1:9222"), _rich_fake_selection())++ def test_foreign_playwright_error_is_isolated_under_non_stock_selection(self) -> None:+ # A stock-Playwright error reaching a non-stock run must NOT be swallowed as retryable.+ selection = _rich_fake_selection()+ assert not is_cdp_connection_error(PWTimeoutError("Timeout 30000ms exceeded."), selection)+ assert not is_cdp_connection_error(PWTargetClosedError("Target closed"), selection)++ def test_stdlib_transport_errors_retry_regardless_of_selection(self) -> None:+ selection = _rich_fake_selection()+ for exc in (ConnectionRefusedError("ECONNREFUSED"), ConnectionResetError("ECONNRESET"), TimeoutError("late")):+ assert is_cdp_connection_error(exc, selection), f"Expected transport floor for {exc!r}"