Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12786): lower expected CDP frame publisher logs (#7633)
LawyZheng5ed9a5d9de69
diff --git a/skyvern/webeye/cdp_frame_publisher.py b/skyvern/webeye/cdp_frame_publisher.pyindex 10d986813..88ba99e95 100644--- a/skyvern/webeye/cdp_frame_publisher.py+++ b/skyvern/webeye/cdp_frame_publisher.py@@ -26,6 +26,28 @@ LOG = structlog.get_logger()DEFAULT_CAPTURE_INTERVAL_SECONDS: float = 1.0+_TARGET_CLOSED_ERROR_TYPE = "TargetClosedError"+_TEARDOWN_ERROR_MESSAGES = (+ "Connection closed while reading from the driver",+ "Target page, context or browser has been closed",+)+++def _is_cdp_session_teardown_error(exc: BaseException) -> bool:+ """True iff opening a CDP session failed because the browser/driver was tearing down.++ Matches ``TargetClosedError`` by type *name*, not identity: ``scripts/patch_browser.sh``+ rewrites ``playwright`` imports to ``patchright`` in every module except+ ``cloud/persistent_browsers``, so the two packages expose distinct ``TargetClosedError``+ classes and an ``isinstance`` check against either would miss the other. The driver-pipe+ drop surfaces as a base ``Error`` carrying a distinctive message, so it is matched on+ text. Anything else is treated as an unexpected failure worth a warning.+ """+ if type(exc).__name__ == _TARGET_CLOSED_ERROR_TYPE:+ return True+ message = str(exc)+ return any(needle in message for needle in _TEARDOWN_ERROR_MESSAGES)+def _write_frame_atomically(temp_dir: Path, stream_key: str, data: bytes) -> None:"""Atomic tempfile+``os.replace`` write; intended to run on a worker thread."""@@ -79,6 +101,10 @@ class CDPFramePublisher:self._stopped = asyncio.Event()self._cdp_session: CDPSession | None = Noneself._attached_page: Page | None = None+ # Whether an unexpected (non-teardown) session-open failure has already warned in+ # the current unhealthy streak. Re-armed by a successful attach so each streak+ # warns once instead of flooding warnings every tick.+ self._warned_unexpected_cdp_open_failure = False# Digest of the last frame whose write + upload both succeeded. Lets us# dedupe identical frames without losing a retry on transient upload# failure.@@ -182,17 +208,13 @@ class CDPFramePublisher:await self._detach_cdp_session()try:self._cdp_session = await page.context.new_cdp_session(page)- except Exception:- LOG.warning(- "Could not open CDP session for frame publishing",- stream_key=self._stream_key,- organization_id=self._organization_id,- exc_info=True,- )+ except Exception as exc:self._cdp_session = Noneself._attached_page = None+ self._log_cdp_open_failure(exc)returnself._attached_page = page+ self._warned_unexpected_cdp_open_failure = Falseself._last_published_digest = NoneLOG.info("CDP frame publisher attached to page",@@ -244,6 +266,32 @@ class CDPFramePublisher:# transient upload failure retries instead of getting deduped away.self._last_published_digest = digest+ def _log_cdp_open_failure(self, exc: BaseException) -> None:+ """Log a ``new_cdp_session`` failure at the severity its cause warrants.++ A teardown race (target/context/browser closed, or the driver pipe dropped) is the+ expected, benign case and stays at debug. Any other failure -- e.g. a browser/CDP/+ proxy incompatibility while the page is still live -- stays at warning so a+ persistently blank live stream remains explainable, but only the first occurrence+ per unhealthy streak warns; subsequent failures in the same unhealthy streak drop to+ debug so a stuck publisher cannot flood warning ingestion at the ~1 Hz capture cadence.+ """+ if _is_cdp_session_teardown_error(exc) or self._warned_unexpected_cdp_open_failure:+ LOG.debug(+ "Could not open CDP session for frame publishing",+ stream_key=self._stream_key,+ organization_id=self._organization_id,+ exc_info=True,+ )+ return+ self._warned_unexpected_cdp_open_failure = True+ LOG.warning(+ "Could not open CDP session for frame publishing",+ stream_key=self._stream_key,+ organization_id=self._organization_id,+ exc_info=True,+ )+async def _write_frame(self, data: bytes) -> bool:"""Persist one frame; True iff both the local write and the upload succeeded."""temp_dir = Path(get_skyvern_temp_dir()) / self._organization_iddiff --git a/tests/unit/test_worker_cdp_frame_publisher.py b/tests/unit/test_worker_cdp_frame_publisher.pyindex be7dd0305..c1af532c7 100644--- a/tests/unit/test_worker_cdp_frame_publisher.py+++ b/tests/unit/test_worker_cdp_frame_publisher.py@@ -8,6 +8,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from structlog.testing import capture_logsfrom skyvern.webeye import cdp_frame_publisher as publisher_modulefrom skyvern.webeye.cdp_frame_publisher import (@@ -21,6 +22,15 @@ ORG_ID = "o_test_123"STREAM_KEY = "wr_test_456.png"+class TargetClosedError(Exception):+ """Stand-in named exactly like the driver's teardown class.++ Both stock Playwright and patchright name this class ``TargetClosedError`` while+ exposing it as distinct types, so the publisher classifies it by type name. A local+ look-alike proves that name-based match without importing either driver.+ """++def _make_cdp_session(frame_bytes_seq: list[bytes]) -> MagicMock:"""CDP session whose ``send`` returns successive base64-encoded PNGs."""encoded_seq = [base64.b64encode(b).decode("ascii") for b in frame_bytes_seq]@@ -201,6 +211,136 @@ async def test_capture_screenshot_failure_is_non_fatal(streaming_temp_dir: Path,session.detach.assert_awaited()+ "teardown_exc",+ [+ TargetClosedError("Target page, context or browser has been closed"),+ TargetClosedError("boom"),+ RuntimeError("Connection closed while reading from the driver"),+ ],+ ids=["target_closed_type", "target_closed_type_noncanonical_message", "driver_pipe_message"],+)+async def test_cdp_session_open_teardown_error_is_debug_and_retried(+ teardown_exc: Exception, fake_storage: AsyncMock, monkeypatch: pytest.MonkeyPatch+) -> None:+ page = MagicMock()+ page.context = MagicMock()+ page.context.new_cdp_session = AsyncMock(side_effect=teardown_exc)+ pub = CDPFramePublisher(+ browser_state=_make_browser_state(page),+ stream_key=STREAM_KEY,+ organization_id=ORG_ID,+ )+ fake_log = SimpleNamespace(debug=MagicMock(), warning=MagicMock())+ monkeypatch.setattr(publisher_module, "LOG", fake_log)++ await _drive_publish_once(pub)+ await _drive_publish_once(pub)++ # A known teardown race is expected and benign: kept at debug, never warned, retried.+ assert page.context.new_cdp_session.await_count == 2+ assert fake_log.debug.call_count == 2+ fake_log.debug.assert_called_with(+ "Could not open CDP session for frame publishing",+ stream_key=STREAM_KEY,+ organization_id=ORG_ID,+ exc_info=True,+ )+ fake_log.warning.assert_not_called()+ fake_storage.assert_not_awaited()+++async def test_cdp_session_open_unexpected_error_warns_once_then_dedupes(+ fake_storage: AsyncMock, monkeypatch: pytest.MonkeyPatch+) -> None:+ page = MagicMock()+ page.context = MagicMock()+ page.context.new_cdp_session = AsyncMock(side_effect=RuntimeError("CDP proxy handshake incompatible"))+ pub = CDPFramePublisher(+ browser_state=_make_browser_state(page),+ stream_key=STREAM_KEY,+ organization_id=ORG_ID,+ )+ fake_log = SimpleNamespace(debug=MagicMock(), warning=MagicMock())+ monkeypatch.setattr(publisher_module, "LOG", fake_log)++ await _drive_publish_once(pub)+ await _drive_publish_once(pub)+ await _drive_publish_once(pub)++ # An unexpected, non-teardown attachment failure while the page may still be live must+ # stay visible so persistently blank frames are explainable -- but only the first+ # occurrence warns; subsequent failures in the same streak drop to debug to avoid a flood.+ assert page.context.new_cdp_session.await_count == 3+ fake_log.warning.assert_called_once_with(+ "Could not open CDP session for frame publishing",+ stream_key=STREAM_KEY,+ organization_id=ORG_ID,+ exc_info=True,+ )+ assert fake_log.debug.call_count == 2+ fake_storage.assert_not_awaited()+++async def test_cdp_session_open_warn_gate_resets_after_successful_attach(+ streaming_temp_dir: Path, fake_storage: AsyncMock, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A healthy attach must re-arm the warning so a *new* unhealthy streak warns again,+ proving the first-occurrence gate silences repeats without hiding fresh failures."""+ bad_page_first = MagicMock()+ bad_page_first.context = MagicMock()+ bad_page_first.context.new_cdp_session = AsyncMock(side_effect=RuntimeError("CDP proxy handshake incompatible"))+ good_page = _make_page_with_session(_make_cdp_session([b"recovered-frame"]))+ bad_page_second = MagicMock()+ bad_page_second.context = MagicMock()+ bad_page_second.context.new_cdp_session = AsyncMock(side_effect=RuntimeError("CDP proxy handshake incompatible"))++ current = {"page": bad_page_first}++ async def _get_page() -> MagicMock:+ return current["page"]++ state = SimpleNamespace(get_working_page=_get_page, is_connected=lambda: True)+ pub = CDPFramePublisher(browser_state=state, stream_key=STREAM_KEY, organization_id=ORG_ID)+ fake_log = SimpleNamespace(debug=MagicMock(), warning=MagicMock(), info=MagicMock())+ monkeypatch.setattr(publisher_module, "LOG", fake_log)++ await _drive_publish_once(pub) # unexpected failure -> warn (1)+ current["page"] = good_page+ await _drive_publish_once(pub) # healthy attach -> gate re-arms+ current["page"] = bad_page_second+ await _drive_publish_once(pub) # new unexpected streak -> warn (2)++ assert fake_log.warning.call_count == 2+++async def test_unexpected_publish_iteration_failure_remains_warning() -> None:+ pub = CDPFramePublisher(+ browser_state=_make_browser_state(None),+ stream_key=STREAM_KEY,+ organization_id=ORG_ID,+ )++ async def _unexpected_failure() -> None:+ pub._stopped.set()+ raise RuntimeError("unexpected publisher failure")++ pub._publish_one_frame = AsyncMock(side_effect=_unexpected_failure) # type: ignore[method-assign]++ with capture_logs() as logs:+ await pub._run()++ matching_logs = [log for log in logs if log.get("event") == "CDP frame publish iteration failed"]+ assert len(matching_logs) == 1+ assert matching_logs[0].get("log_level") == "warning"+ assert matching_logs[0].get("stream_key") == STREAM_KEY+ assert matching_logs[0].get("organization_id") == ORG_ID++@pytest.mark.asyncioasync def test_save_streaming_file_failure_is_non_fatal(streaming_temp_dir: Path, monkeypatch: pytest.MonkeyPatch