Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Deliver the driver probe's late reply after the caller gives up, not on a timer (SKY-18759) (#8987)
Shuchang Zheng03734a6c334a
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex e8a849dc4..971471a9f 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -1013,8 +1013,11 @@ async def settle_or_fail(coro: Awaitable[_T], wait_seconds: float = 2.0) -> tuplelapsed = loop.time() - startedif not task.done():task.cancel()- with contextlib.suppress(asyncio.CancelledError):- await task+ # A task that swallows its cancellation would hang an unbounded await here as well.+ await asyncio.wait({task}, timeout=wait_seconds)+ if task.done():+ with contextlib.suppress(asyncio.CancelledError):+ await taskpytest.fail(f"task still running after {wait_seconds}s")return task, elapsed@@ -1027,9 +1030,8 @@ class DriverReplyProbe:without its task ending therefore leaves the reply live, and the driver's late error lands on itwith nobody left to retrieve it."""- def __init__(self, error: BaseException, answers_after_seconds: float = 0.05) -> None:+ def __init__(self, error: BaseException) -> None:self._error = error- self._answers_after_seconds = answers_after_secondsself.called = asyncio.Event()self.reply: asyncio.Future[Any] | None = None@@ -1046,16 +1048,17 @@ class DriverReplyProbe:reply.cancel()issuing_task.add_done_callback(abandon_reply)- loop.call_later(self._answers_after_seconds, lambda: reply.done() or reply.set_exception(self._error))# The driver abandons an unanswered reply on the line after this await, which cancellation skips.await asyncio.wait({reply}, return_when=asyncio.FIRST_COMPLETED)return reply.result()- async def orphaned_reply(self, wait_seconds: float = 2.0) -> bool:- """Whether the late reply carries an error nobody retrieved -- asyncio's never-retrieved line."""+ def orphaned_reply(self) -> bool:+ """Deliver the driver's late error now that the caller has given up, and report whether it landed on a reply+ nobody will retrieve (asyncio's never-retrieved line)."""assert self.reply is not None, "the driver was never called"- await asyncio.wait({self.reply}, timeout=wait_seconds)- return self.reply.done() and not self.reply.cancelled() and self.reply.exception() is not None+ if not self.reply.done():+ self.reply.set_exception(self._error)+ return not self.reply.cancelled() and self.reply.exception() is not Nonedef stalled_scrolling_capture(entered: asyncio.Event, timeout_ms: float) -> AsyncMock:diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.pyindex 932abce90..5d6711ec1 100644--- a/tests/unit/test_mcp_browser_tools.py+++ b/tests/unit/test_mcp_browser_tools.py@@ -2547,8 +2547,6 @@ async def test_skyvern_type_missing_selector_preflight_is_bound_by_the_action_demonkeypatch.setattr(mcp_browser, "strategy_aware_input", strategy_aware_input)monkeypatch.setattr(action_deadline, "ACTION_DEADLINE_HEADROOM_MS", 100)- loop = asyncio.get_running_loop()- started_at = loop.time()result = await asyncio.wait_for(mcp_browser.skyvern_type(selector="#missing",@@ -2559,7 +2557,6 @@ async def test_skyvern_type_missing_selector_preflight_is_bound_by_the_action_detimeout=1.5,)- assert loop.time() - started_at < 1.5assert preflight_cancelled.is_set()assert result["ok"] is Falseassert result["error"]["code"] == mcp_browser.ErrorCode.TIMEOUTdiff --git a/tests/unit/test_navigation_recovery.py b/tests/unit/test_navigation_recovery.pyindex 7cf790156..85b8dae0b 100644--- a/tests/unit/test_navigation_recovery.py+++ b/tests/unit/test_navigation_recovery.py@@ -16,7 +16,7 @@ from skyvern.webeye.utils.page import (_wait_for_navigation_settle,with_dom_utils,)-from tests.unit.conftest import DriverReplyProbe+from tests.unit.conftest import DriverReplyProbe, settle_or_failclass TestIsNavigationContextLost:@@ -145,10 +145,15 @@ class TestEvaluateWithNavigationRecovery:frame = AsyncMock()frame.evaluate = probe- with pytest.raises(SkyvernPageAnalysisTimeout):- await SkyvernFrame.evaluate(frame=frame, expression="() => 42", timeout_ms=25)+ # Checked in the same task, before settle_or_fail yields, so a call the evaluate cancelled without+ # awaiting has not yet abandoned its reply.+ async def abandon_the_evaluate() -> None:+ with pytest.raises(SkyvernPageAnalysisTimeout):+ await SkyvernFrame.evaluate(frame=frame, expression="() => 42", timeout_ms=25)+ assert not probe.orphaned_reply()- assert not await probe.orphaned_reply()+ task, _ = await settle_or_fail(abandon_the_evaluate())+ task.result()@pytest.mark.asyncio@pytest.mark.parametrize("error_type", [PlaywrightError, RuntimeError])diff --git a/tests/unit/webeye/test_screenshot_runtime_events.py b/tests/unit/webeye/test_screenshot_runtime_events.pyindex 7706f3597..4d8945009 100644--- a/tests/unit/webeye/test_screenshot_runtime_events.py+++ b/tests/unit/webeye/test_screenshot_runtime_events.py@@ -28,7 +28,7 @@ from skyvern.webeye.browser_runtime_events import BrowserRuntimeLogContext, browfrom skyvern.webeye.real_browser_state import RealBrowserStatefrom skyvern.webeye.utils import page as page_modulefrom skyvern.webeye.utils.page import ScreenshotMode, SkyvernFrame-from tests.unit.conftest import DriverReplyProbe, stalling_async_mock+from tests.unit.conftest import DriverReplyProbe, settle_or_fail, stalling_async_mockfrom tests.unit.forge_log_capture import capture_runtime_logs@@ -184,20 +184,27 @@ async def test_an_abandoned_capture_leaves_the_driver_no_unretrieved_reply(page:capture = functools.partial(SkyvernFrame.take_scrolling_screenshot, page, mode=ScreenshotMode.LITE, scrolling_number=1)- if stop == "external_cancel":- task = asyncio.create_task(capture(timeout=5000))- await asyncio.wait_for(probe.called.wait(), timeout=2)- task.cancel()- with pytest.raises(asyncio.CancelledError):- await task- elif stop == "caller_deadline":- with pytest.raises(TimeoutError):- async with asyncio.timeout(0.025):- await capture(timeout=5000)- else:- with pytest.raises(TimeoutError):- await capture(timeout=25)- assert not await probe.orphaned_reply()++ # Checked in the same task, before settle_or_fail yields, so a call the capture cancelled without awaiting+ # has not yet abandoned its reply.+ async def abandon_the_capture() -> None:+ if stop == "external_cancel":+ task = asyncio.create_task(capture(timeout=5000))+ await asyncio.wait_for(probe.called.wait(), timeout=2)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ elif stop == "caller_deadline":+ with pytest.raises(TimeoutError):+ async with asyncio.timeout(0.025):+ await capture(timeout=5000)+ else:+ with pytest.raises(TimeoutError):+ await capture(timeout=25)+ assert not probe.orphaned_reply()++ task, _ = await settle_or_fail(abandon_the_capture())+ task.result()@pytest.mark.asyncio