Skip to content

Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.

fix(browser): clean up leaked Playwright driver when launch fails in __aenter__

Soham Kukreti701b0b197092
diff --git a/crawl4ai/browser_manager.py b/crawl4ai/browser_manager.py
index d7b8009c..f4ab0aa3 100644
--- a/crawl4ai/browser_manager.py
+++ b/crawl4ai/browser_manager.py
@@ -626,7 +626,15 @@ class _CDPConnectionCache:
else:
from playwright.async_api import async_playwright
pw = await async_playwright().start()
- browser = await pw.chromium.connect_over_cdp(cdp_url)
+ try:
+ browser = await pw.chromium.connect_over_cdp(cdp_url)
+ except BaseException:
+ # Stop the driver we just started so a failed connect doesn't leak it
+ try:
+ await pw.stop()
+ except BaseException:
+ pass
+ raise
cls._cache[cdp_url] = (pw, browser, 1)
return pw, browser
@@ -788,6 +796,25 @@ class BrowserManager:
Note: This method should be called in a separate task to avoid blocking the main event loop.
"""
+ try:
+ await self._start_impl()
+ except BaseException:
+ # Roll back partial startup (e.g. Playwright driver) since a failed __aenter__ never triggers __aexit__
+ try:
+ await self.close()
+ except BaseException:
+ pass
+ if self.playwright is not None:
+ # close() intentionally skips the driver for external-CDP configs; on failed startup we still own it
+ try:
+ await self.playwright.stop()
+ except BaseException:
+ pass
+ self.playwright = None
+ self.browser = None
+ raise
+
+ async def _start_impl(self):
if self.playwright is not None:
await self.close()
diff --git a/tests/regression/test_reg_browser.py b/tests/regression/test_reg_browser.py
index 2d9f87fb..dac55a84 100644
--- a/tests/regression/test_reg_browser.py
+++ b/tests/regression/test_reg_browser.py
@@ -7,6 +7,7 @@ stealth mode, session management, network capture, and anti-bot features using
real browser crawling with no mocking.
"""
+import asyncio
import base64
import time
@@ -37,6 +38,87 @@ async def test_browser_lifecycle(local_server):
await crawler.close()
+async def test_failed_browser_launch_leaves_no_driver(monkeypatch):
+ """Issue #2155: a browser-launch failure inside __aenter__ must roll back
+ partial startup — no leaked Playwright driver process, no half-built state.
+
+ Launch failure is forced by pointing PLAYWRIGHT_BROWSERS_PATH at an empty
+ directory, so the driver starts but the browser executable is missing.
+ """
+ import tempfile
+
+ import psutil
+
+ from crawl4ai.browser_manager import BrowserManager
+
+ monkeypatch.setenv(
+ "PLAYWRIGHT_BROWSERS_PATH", tempfile.mkdtemp(prefix="c4ai-no-browsers-")
+ )
+ before = {p.pid for p in psutil.Process().children(recursive=True)}
+
+ manager = BrowserManager(browser_config=BrowserConfig(headless=True))
+ with pytest.raises(Exception, match="Executable doesn't exist"):
+ await manager.start()
+
+ # Half-built state must be rolled back (this also proves the driver was
+ # stopped, since only close()/stop() reset it).
+ assert manager.playwright is None, "playwright driver not rolled back"
+ assert manager.browser is None, "browser reference not rolled back"
+
+ # No Playwright driver child process may survive the failed start.
+ await asyncio.sleep(0.5) # allow the stopped subprocess to be reaped
+ leaked = []
+ for child in psutil.Process().children(recursive=True):
+ if child.pid in before:
+ continue
+ try:
+ cmd = " ".join(child.cmdline())
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ if "playwright" in cmd and "run-driver" in cmd:
+ leaked.append(child.pid)
+ assert leaked == [], f"leaked Playwright driver process(es): {leaked}"
+
+
+async def test_failed_cached_cdp_connect_leaves_no_driver():
+ """Issue #2155: a failed connect inside _CDPConnectionCache.acquire() must
+ stop the driver it started (the manager never sees it, so start()'s
+ rollback alone cannot clean it up)."""
+ import psutil
+
+ from crawl4ai.browser_manager import BrowserManager
+
+ before = {p.pid for p in psutil.Process().children(recursive=True)}
+ config = BrowserConfig(
+ headless=True,
+ cdp_url="http://127.0.0.1:9", # unreachable endpoint
+ cache_cdp_connection=True,
+ )
+ manager = BrowserManager(browser_config=config)
+ # Matching on connect_over_cdp proves the driver was already started
+ # when the failure happened (the scenario under test).
+ with pytest.raises(Exception, match="connect_over_cdp"):
+ await manager.start()
+
+ assert manager.playwright is None
+ assert manager.browser is None
+
+ await asyncio.sleep(0.5)
+ leaked = []
+ for child in psutil.Process().children(recursive=True):
+ if child.pid in before:
+ continue
+ try:
+ cmd = " ".join(child.cmdline())
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ if "playwright" in cmd and "run-driver" in cmd:
+ leaked.append(child.pid)
+ assert leaked == [], f"leaked Playwright driver process(es): {leaked}"
+
+
@pytest.mark.asyncio
async def test_browser_context_manager(local_server):
"""Verify async with pattern works and cleanup happens without error."""