Description
Summary
With a persistent context (user_data_dir set, use_incognito_pages=False), BrowserPool retires a
browser after retire_browser_after_page_count pages, then launches the next one at once. The retired
browser is still running, and it still holds the profile's lock, so the new Chromium fails to launch:
BrowserType.launch_persistent_context: Failed to create a ProcessSingleton for your profile directory.
This usually means that the profile is already in use by another instance of Chromium.
The requests dispatched meanwhile fail. The pool retires automatically, after 100 pages by default, so
any long crawl on a persistent profile hits this.
Reproduction
Self-contained: a local static server with 6 pages, one persistent profile, concurrency 1, a retire
after 2 pages, and no retries (so each lost page shows up as a failed request).
import asyncio
import functools
import http.server
import importlib.metadata
import io
import logging
import tempfile
import threading
from pathlib import Path
from crawlee import ConcurrencySettings
from crawlee.browsers import BrowserPool
from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext
PAGES = 6
def serve(root: Path) -> str:
for i in range(PAGES):
(root / f"p{i}.html").write_text(f"<html><body><h1>page {i}</h1></body></html>")
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(root))
handler.log_message = lambda *a, **k: None
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return f"http://127.0.0.1:{srv.server_address[1]}"
async def main() -> None:
log = io.StringIO()
logging.getLogger().addHandler(logging.StreamHandler(log))
tmp = Path(tempfile.mkdtemp())
(site := tmp / "site").mkdir()
base = serve(site)
pool = BrowserPool.with_default_plugin(
browser_type="chromium",
user_data_dir=str(tmp / "profile"),
use_incognito_pages=False,
headless=True,
browser_launch_options={"channel": "chromium"}, # the full Chromium, new headless mode
retire_browser_after_page_count=2,
)
crawler = PlaywrightCrawler(
browser_pool=pool,
concurrency_settings=ConcurrencySettings(min_concurrency=1, max_concurrency=1, desired_concurrency=1),
max_request_retries=0,
)
handled: list[str] = []
errors: list[str] = []
@crawler.failed_request_handler
async def failed(ctx, error: Exception) -> None:
errors.append(f"{type(error).__name__}: {str(error).splitlines()[0][:160]}")
@crawler.router.default_handler
async def handler(ctx: PlaywrightCrawlingContext) -> None:
handled.append(ctx.request.url)
stats = await crawler.run([f"{base}/p{i}.html" for i in range(PAGES)])
text = log.getvalue()
print(f"crawlee {importlib.metadata.version('crawlee')}, playwright {importlib.metadata.version('playwright')}")
print(f"pages: {PAGES}, handled: {len(handled)}, failed: {stats.requests_failed}")
print(f"log lines mentioning ProcessSingleton: {sum('ProcessSingleton' in ln for ln in text.splitlines())}")
for e in sorted(set(errors)):
print(f" failure: {e} (x{errors.count(e)})")
asyncio.run(main())Output on crawlee 1.11.5 with playwright 1.59.0 and Chromium 1217 (macOS arm64, Python 3.13). The
output on 1.11.1 is identical:
crawlee 1.11.5, playwright 1.59.0
pages: 6, handled: 2, failed: 4
log lines mentioning ProcessSingleton: 8
failure: Error: BrowserType.launch_persistent_context: Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by (x4)
4 of 6 pages lost: only the 2 pages before the first retirement succeed.
In an earlier long crawl (the default retire after 100 pages, concurrency 1), we saw 8 launch failures,
in pairs, about every 14.5 minutes. That interval matches 100 pages at our rate.
Expected
For a persistent profile, one of:
- close the retired browser (and so release the profile lock) before launching its replacement;
- do not retire a browser whose context is persistent; or
- wait for the profile to be released before relaunching.
A side note: retiring also generates a new fingerprint while the persistent profile keeps its cookies.
Workaround
retire_browser_after_page_count=sys.maxsize: one browser per run, never retired.- A
pre_launch_hookthat waits, up to 45 s (below the 60 s launch timeout), until the profile's
SingletonLockis gone. That covers any other relaunch, e.g. after a crash.
Activity