Skip to content

Commit 7dbe882

Browse files
authored
fix(browsers): Clean up BrowserPool and its plugins after a failed entry or exit (#2446)
### Description - A failed or cancelled entry or exit of `BrowserPool`, `PlaywrightBrowserPlugin` or `StagehandBrowserPlugin` leaves it inactive, so it can be entered again. A pool whose entry fails exits the plugins it already entered. A plugin whose entry fails tries to stop the Playwright driver it started and stops waiting after a few seconds, so a timed-out plugin entry doesn't hang the pool. - Exiting a pool closes every browser and every plugin it entered, even when one of them fails or the exit is cancelled. It raises the first failure and logs the rest. ### Issues - Part of #2301 - Follow-up: #2445 ### Testing - New unit tests for failed and cancelled entries and exits of the pool and both plugins, and for a Playwright driver that doesn't stop. *✍️ Drafted by Claude Code*
1 parent 7123e1b commit 7dbe882

6 files changed

Lines changed: 698 additions & 41 deletions

File tree

‎src/crawlee/browsers/_browser_pool.py‎

Lines changed: 61 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from crawlee.browsers._types import BrowserType, CrawleePage
2020

2121
if TYPE_CHECKING:
22-
from collections.abc import Awaitable, Callable, Mapping, Sequence
22+
from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence
2323
from pathlib import Path
2424
from types import TracebackType
2525

@@ -98,6 +98,7 @@ def __init__(
9898
self._retire_browser_after_page_count = retire_browser_after_page_count
9999
self._pages = WeakValueDictionary[str, CrawleePage]() # Track the pages in the pool
100100
self._plugins_cycle = itertools.cycle(self._plugins) # Cycle through the plugins
101+
self._entered_plugins: list[BrowserPlugin] = []
101102

102103
# Hooks for custom behavior at different stages of the browser and page lifecycles.
103104
self._pre_launch_hooks: list[Callable[[str, BrowserPlugin], Awaitable[None]]] = []
@@ -218,8 +219,15 @@ async def __aenter__(self) -> BrowserPool:
218219
try:
219220
for plugin in self._plugins:
220221
await asyncio.wait_for(plugin.__aenter__(), timeout)
222+
self._entered_plugins.append(plugin)
221223
except TimeoutError:
222224
logger.warning('Initializing of the browser plugin %s timed out, will be skipped.', plugin)
225+
except BaseException:
226+
try:
227+
await self.__aexit__(None, None, None)
228+
except Exception:
229+
logger.warning('Exiting a browser plugin failed while rolling back the pool entry.', exc_info=True)
230+
raise
223231

224232
return self
225233

@@ -229,26 +237,47 @@ async def __aexit__(
229237
exc_value: BaseException | None,
230238
exc_traceback: TracebackType | None,
231239
) -> None:
232-
"""Exit the context manager and close all browser plugins.
240+
"""Exit the context manager and close the browser plugins it entered.
233241
234242
Raises:
235243
RuntimeError: If the context manager is not active.
236244
"""
237245
if not self._active:
238246
raise RuntimeError(f'The {self.__class__.__name__} is not active.')
239247

240-
await self._identify_inactive_browsers_task.stop()
241-
await self._close_inactive_browsers_task.stop()
242-
243-
for browser in self._active_browsers + self._inactive_browsers:
244-
await browser.close(force=True)
245-
self._active_browsers.clear()
246-
self._inactive_browsers.clear()
247-
248-
for plugin in self._plugins:
249-
await plugin.__aexit__(exc_type, exc_value, exc_traceback)
248+
# Every browser and plugin is closed even when an earlier step fails, as an inactive pool can't be exited again.
249+
failures: list[BaseException] = []
250+
try:
251+
try:
252+
await self._stop_recurring_tasks()
253+
finally:
254+
try:
255+
browser_closes = (
256+
browser.close(force=True) for browser in self._active_browsers + self._inactive_browsers
257+
)
258+
await self._run_collecting_failures(browser_closes, failures)
259+
finally:
260+
self._active_browsers.clear()
261+
self._inactive_browsers.clear()
262+
263+
try:
264+
plugin_exits = (
265+
plugin.__aexit__(exc_type, exc_value, exc_traceback) for plugin in self._entered_plugins
266+
)
267+
await self._run_collecting_failures(plugin_exits, failures)
268+
finally:
269+
self._entered_plugins.clear()
270+
self._active = False
271+
except BaseException:
272+
# A cancellation above is raised instead, so the failures are only logged.
273+
for failure in failures:
274+
logger.warning('Closing the browser pool failed.', exc_info=failure)
275+
raise
250276

251-
self._active = False
277+
for failure in failures[1:]:
278+
logger.warning('Closing the browser pool failed.', exc_info=failure)
279+
if failures:
280+
raise failures[0]
252281

253282
@ensure_context
254283
async def new_page(
@@ -392,6 +421,25 @@ async def _close_inactive_browsers(self) -> None:
392421
await browser.close()
393422
self._inactive_browsers.remove(browser)
394423

424+
async def _stop_recurring_tasks(self) -> None:
425+
try:
426+
await self._identify_inactive_browsers_task.stop()
427+
finally:
428+
await self._close_inactive_browsers_task.stop()
429+
430+
@staticmethod
431+
async def _run_collecting_failures(
432+
coroutines: Iterable[Coroutine[Any, Any, object]], failures: list[BaseException]
433+
) -> None:
434+
"""Run `coroutines` concurrently and add their errors to `failures`, also when the wait is cancelled."""
435+
tasks = [asyncio.create_task(coroutine) for coroutine in coroutines]
436+
try:
437+
await asyncio.gather(*tasks, return_exceptions=True)
438+
finally:
439+
# A cancelled `gather` still waits for its tasks, so each one is done here.
440+
errors = (task.exception() for task in tasks if not task.cancelled())
441+
failures.extend(error for error in errors if error is not None)
442+
395443
async def _execute_hooks(self, hooks: list[Callable[..., Awaitable[None]]], *args: Any) -> None:
396444
"""Execute the provided hooks with the given arguments."""
397445
for hook in hooks:

‎src/crawlee/browsers/_playwright_browser_plugin.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
import asyncio
6+
from datetime import timedelta
57
from logging import getLogger
68
from typing import TYPE_CHECKING, Any
79

@@ -41,6 +43,9 @@ class PlaywrightBrowserPlugin(BrowserPlugin):
4143

4244
AUTOMATION_LIBRARY = 'playwright'
4345

46+
_PLAYWRIGHT_STOP_TIMEOUT = timedelta(seconds=5)
47+
"""The time limit for stopping Playwright while rolling back a failed entry."""
48+
4449
def __init__(
4550
self,
4651
*,
@@ -155,7 +160,18 @@ async def __aenter__(self) -> PlaywrightBrowserPlugin:
155160
raise RuntimeError(f'The {self.__class__.__name__} is already active.')
156161

157162
self._active = True
158-
self._playwright = await self._playwright_context_manager.__aenter__()
163+
164+
try:
165+
self._playwright = await self._playwright_context_manager.__aenter__()
166+
except BaseException:
167+
# Best effort: a Playwright driver that has already started is stopped too.
168+
try:
169+
timeout = self._PLAYWRIGHT_STOP_TIMEOUT.total_seconds()
170+
await asyncio.wait_for(self.__aexit__(None, None, None), timeout)
171+
except Exception:
172+
logger.debug('Stopping Playwright failed while rolling back the plugin entry.', exc_info=True)
173+
raise
174+
159175
return self
160176

161177
@override
@@ -168,9 +184,11 @@ async def __aexit__(
168184
if not self._active:
169185
raise RuntimeError(f'The {self.__class__.__name__} is not active.')
170186

171-
await self._playwright_context_manager.__aexit__(exc_type, exc_value, exc_traceback)
172-
self._playwright_context_manager = async_playwright()
173-
self._active = False
187+
try:
188+
await self._playwright_context_manager.__aexit__(exc_type, exc_value, exc_traceback)
189+
finally:
190+
self._playwright_context_manager = async_playwright()
191+
self._active = False
174192

175193
@override
176194
@ensure_context

‎src/crawlee/browsers/_stagehand_browser_plugin.py‎

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import annotations
22

3+
import asyncio
4+
from datetime import timedelta
35
from logging import getLogger
46
from typing import TYPE_CHECKING, Any
57

@@ -44,6 +46,9 @@ class StagehandBrowserPlugin(BrowserPlugin):
4446

4547
AUTOMATION_LIBRARY = 'stagehand'
4648

49+
_PLAYWRIGHT_STOP_TIMEOUT = timedelta(seconds=5)
50+
"""The time limit for stopping Playwright while rolling back a failed entry."""
51+
4752
def __init__(
4853
self,
4954
*,
@@ -163,19 +168,29 @@ async def __aenter__(self) -> StagehandBrowserPlugin:
163168
raise RuntimeError(f'The {self.__class__.__name__} is already active.')
164169

165170
self._active = True
166-
self._playwright = await self._playwright_context_manager.__aenter__()
167-
168-
if self._stagehand_options.env == 'LOCAL':
169-
if 'executable_path' not in self._browser_launch_options:
170-
chrome_path = self._playwright.chromium.executable_path
171-
self._browser_launch_options['executable_path'] = chrome_path
172-
logger.debug('Resolved Chromium path from Playwright: %s', chrome_path)
173-
174-
self._stagehand_init_params['local_chrome_path'] = self._browser_launch_options['executable_path']
175171

176-
client = AsyncStagehand(**self._stagehand_init_params)
177-
await client.__aenter__()
178-
self._stagehand_client = client
172+
try:
173+
self._playwright = await self._playwright_context_manager.__aenter__()
174+
175+
if self._stagehand_options.env == 'LOCAL':
176+
if 'executable_path' not in self._browser_launch_options:
177+
chrome_path = self._playwright.chromium.executable_path
178+
self._browser_launch_options['executable_path'] = chrome_path
179+
logger.debug('Resolved Chromium path from Playwright: %s', chrome_path)
180+
181+
self._stagehand_init_params['local_chrome_path'] = self._browser_launch_options['executable_path']
182+
183+
client = AsyncStagehand(**self._stagehand_init_params)
184+
await client.__aenter__()
185+
self._stagehand_client = client
186+
except BaseException:
187+
# Best effort: a Playwright driver that has already started is stopped too.
188+
try:
189+
timeout = self._PLAYWRIGHT_STOP_TIMEOUT.total_seconds()
190+
await asyncio.wait_for(self.__aexit__(None, None, None), timeout)
191+
except Exception:
192+
logger.debug('Stopping Playwright failed while rolling back the plugin entry.', exc_info=True)
193+
raise
179194

180195
return self
181196

@@ -189,14 +204,17 @@ async def __aexit__(
189204
if not self._active:
190205
raise RuntimeError(f'The {self.__class__.__name__} is not active.')
191206

192-
if self._stagehand_client is not None:
193-
await self._stagehand_client.__aexit__(exc_type, exc_value, exc_traceback)
194-
self._stagehand_client = None
195-
196-
await self._playwright_context_manager.__aexit__(exc_type, exc_value, exc_traceback)
197-
self._playwright_context_manager = async_playwright()
198-
self._playwright = None
199-
self._active = False
207+
try:
208+
if self._stagehand_client is not None:
209+
await self._stagehand_client.__aexit__(exc_type, exc_value, exc_traceback)
210+
finally:
211+
try:
212+
await self._playwright_context_manager.__aexit__(exc_type, exc_value, exc_traceback)
213+
finally:
214+
self._stagehand_client = None
215+
self._playwright = None
216+
self._playwright_context_manager = async_playwright()
217+
self._active = False
200218

201219
@override
202220
@ensure_context

0 commit comments

Comments
 (0)