Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

add portalocker multiprocess semaphore

Nick Sweeting1415562d6ea9
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 83e27f9b1..e17db12a1 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -3,6 +3,7 @@ import logging
import os
import platform
import signal
+import tempfile
import threading
import time
from collections.abc import Callable, Coroutine
@@ -13,6 +14,7 @@ from sys import stderr
from typing import Any, Literal, ParamSpec, TypeVar
from urllib.parse import urlparse
+import portalocker
from dotenv import load_dotenv
load_dotenv()
@@ -596,6 +598,14 @@ def _log_pretty_url(s: str, max_len: int | None = 22) -> str:
GLOBAL_RETRY_SEMAPHORES: dict[str, asyncio.Semaphore] = {}
GLOBAL_RETRY_SEMAPHORE_LOCK = threading.Lock()
+# Multiprocess semaphore support
+MULTIPROCESS_SEMAPHORE_DIR = Path(tempfile.gettempdir()) / 'browser_use_semaphores'
+MULTIPROCESS_SEMAPHORE_DIR.mkdir(exist_ok=True)
+
+# Global multiprocess semaphore registry
+MULTIPROCESS_SEMAPHORES: dict[str, portalocker.utils.NamedBoundedSemaphore] = {}
+MULTIPROCESS_SEMAPHORE_LOCK = threading.Lock()
+
def retry(
wait: float = 3,
@@ -606,63 +616,86 @@ def retry(
semaphore_limit: int | None = None,
semaphore_name: str | None = None,
semaphore_lax: bool = True,
- semaphore_scope: Literal['global', 'class', 'self'] = 'global',
+ semaphore_scope: Literal['global', 'class', 'self', 'multiprocess'] = 'global',
semaphore_timeout: float | None = None,
):
"""
- Retry decorator with semaphore support for async functions.
-
- Args:
- wait: Seconds to wait between retries
- retries: Number of retry attempts after initial failure
- timeout: Per-attempt timeout in seconds
- retry_on: Tuple of exception types to retry on (None = retry all exceptions)
- backoff_factor: Multiplier for wait time after each retry (1.0 = no backoff)
- semaphore_limit: Max concurrent executions (creates semaphore if needed)
- semaphore_name: Name for semaphore (defaults to function name)
- semaphore_lax: If True, continue without semaphore on acquisition failure
- semaphore_scope: Scope for semaphore sharing:
- - 'global': All calls share one semaphore (default)
- - 'class': All instances of a class share one semaphore
- - 'self': Each instance gets its own semaphore
- semaphore_timeout: Max time to wait for semaphore acquisition (None = timeout * (limit - 1))
-
- Example:
- @retry(wait=3, retries=3, timeout=5, semaphore_limit=3, semaphore_scope='self')
- async def some_function(self, ...):
- # Limited to 5s per attempt, retries up to 3 times on failure
- # Max 3 concurrent executions per instance
+ Retry decorator with semaphore support for async functions.
+
+ Args:
+ wait: Seconds to wait between retries
+ retries: Number of retry attempts after initial failure
+ timeout: Per-attempt timeout in seconds
+ retry_on: Tuple of exception types to retry on (None = retry all exceptions)
+ backoff_factor: Multiplier for wait time after each retry (1.0 = no backoff)
+ semaphore_limit: Max concurrent executions (creates semaphore if needed)
+ semaphore_name: Name for semaphore (defaults to function name)
+ semaphore_lax: If True, continue without semaphore on acquisition failure
+ semaphore_scope: Scope for semaphore sharing:
+ - 'global': All calls share one semaphore (default)
+ - 'class': All instances of a class share one semaphore
+ - 'self': Each instance gets its own semaphore
+ - 'multiprocess': All processes on the machine share one semaphore
+ semaphore_timeout: Max time to wait for semaphore acquisition (None = timeout * (limit - 1))
+
+ Example:
+ @retry(wait=3, retries=3, timeout=5, semaphore_limit=3, semaphore_scope='self')
+ async def some_function(self, ...):
+ # Limited to 5s per attempt, retries up to 3 times on failure
+ # Max 3 concurrent executions per instance
+
+ Notes:
+ - semaphore aquision happens once at start time, it's not retried
+ - semaphore_timeout is only used if semaphore_limit is set.
+ - if semaphore_timeout is set to 0, it will wait forever for a semaphore slot to become available.
+ - if semaphore_timeout is set to None, it will wait for the default (timeout * (semaphore_limit - 1)) +0.01s
+ - retries are 0-indexed, so retries=1 means the function will be called 2 times total (1 initial + 1 retry)
"""
def decorator(func: Callable[P, Coroutine[Any, Any, T]]) -> Callable[P, Coroutine[Any, Any, T]]:
@wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: # type: ignore[return]
# Get or create semaphore if needed
- semaphore = None
+ semaphore: Any = None
semaphore_acquired = False
+ multiprocess_lock: Any = None
if semaphore_limit is not None:
# Determine semaphore key based on scope
base_name = semaphore_name or func.__name__
- if semaphore_scope == 'global':
+ if semaphore_scope == 'multiprocess':
+ # Use multiprocess semaphore
sem_key = base_name
- elif semaphore_scope == 'class' and args and hasattr(args[0], '__class__'):
- # Use class name for class-level semaphore
- class_name = args[0].__class__.__name__
- sem_key = f'{class_name}.{base_name}'
- elif semaphore_scope == 'self' and args:
- # Use instance id for instance-level semaphore
- instance_id = id(args[0])
- sem_key = f'{instance_id}.{base_name}'
+ with MULTIPROCESS_SEMAPHORE_LOCK:
+ if sem_key not in MULTIPROCESS_SEMAPHORES:
+ # Create a NamedBoundedSemaphore with the given limit
+ MULTIPROCESS_SEMAPHORES[sem_key] = portalocker.utils.NamedBoundedSemaphore(
+ maximum=semaphore_limit,
+ name=sem_key,
+ directory=str(MULTIPROCESS_SEMAPHORE_DIR),
+ )
+ semaphore = MULTIPROCESS_SEMAPHORES[sem_key]
else:
- # Fallback to global if we can't determine scope
- sem_key = base_name
-
- with GLOBAL_RETRY_SEMAPHORE_LOCK:
- if sem_key not in GLOBAL_RETRY_SEMAPHORES:
- GLOBAL_RETRY_SEMAPHORES[sem_key] = asyncio.Semaphore(semaphore_limit)
- semaphore = GLOBAL_RETRY_SEMAPHORES[sem_key]
+ # Use in-process semaphore
+ if semaphore_scope == 'global':
+ sem_key = base_name
+ elif semaphore_scope == 'class' and args and hasattr(args[0], '__class__'):
+ # Use class name for class-level semaphore
+ class_name = args[0].__class__.__name__
+ sem_key = f'{class_name}.{base_name}'
+ elif semaphore_scope == 'self' and args:
+ # Use instance id for instance-level semaphore
+ instance_id = id(args[0])
+ sem_key = f'{instance_id}.{base_name}'
+ else:
+ # Fallback to global if we can't determine scope
+ sem_key = base_name
+
+ with GLOBAL_RETRY_SEMAPHORE_LOCK:
+ if sem_key not in GLOBAL_RETRY_SEMAPHORES:
+ GLOBAL_RETRY_SEMAPHORES[sem_key] = asyncio.Semaphore(semaphore_limit)
+ semaphore = GLOBAL_RETRY_SEMAPHORES[sem_key]
# Try to acquire semaphore
sem_start = time.time()
@@ -675,21 +708,49 @@ def retry(
# Use provided timeout, but ensure minimum of 0.01 if 0 was passed
sem_timeout = max(0.01, semaphore_timeout) if semaphore_timeout == 0 else semaphore_timeout
- try:
- async with asyncio.timeout(sem_timeout):
- await semaphore.acquire()
- semaphore_acquired = True
- except TimeoutError:
- sem_wait_time = time.time() - sem_start
- if not semaphore_lax:
- raise TimeoutError(
- f'Failed to acquire semaphore "{sem_key}" within {sem_timeout}s '
- f'(limit={semaphore_limit}, timeout={timeout}s per operation)'
+ if semaphore_scope == 'multiprocess':
+ # Multiprocess semaphore uses context manager with timeout
+ try:
+ # Use a temporary thread to run the blocking operation
+ # portalocker returns a Lock object or None
+ multiprocess_lock = await asyncio.to_thread(
+ lambda: semaphore.acquire(timeout=sem_timeout, check_interval=0.05, fail_when_locked=False)
+ )
+ if multiprocess_lock:
+ semaphore_acquired = True
+ else:
+ raise TimeoutError(f'Could not acquire semaphore within {sem_timeout}s')
+ except Exception as e:
+ sem_wait_time = time.time() - sem_start
+ if 'Could not acquire' in str(e) or isinstance(e, TimeoutError):
+ if not semaphore_lax:
+ raise TimeoutError(
+ f'Failed to acquire multiprocess semaphore "{sem_key}" within {sem_timeout}s '
+ f'(limit={semaphore_limit}, timeout={timeout}s per operation)'
+ )
+ logger.warning(
+ f'Failed to acquire multiprocess semaphore "{sem_key}" after {sem_wait_time:.1f}s, '
+ f'proceeding without concurrency limit'
+ )
+ else:
+ raise
+ else:
+ # Regular asyncio semaphore
+ try:
+ async with asyncio.timeout(sem_timeout):
+ await semaphore.acquire()
+ semaphore_acquired = True
+ except TimeoutError:
+ sem_wait_time = time.time() - sem_start
+ if not semaphore_lax:
+ raise TimeoutError(
+ f'Failed to acquire semaphore "{sem_key}" within {sem_timeout}s '
+ f'(limit={semaphore_limit}, timeout={timeout}s per operation)'
+ )
+ logger.warning(
+ f'Failed to acquire semaphore "{sem_key}" after {sem_wait_time:.1f}s, '
+ f'proceeding without concurrency limit'
)
- logger.warning(
- f'Failed to acquire semaphore "{sem_key}" after {sem_wait_time:.1f}s, '
- f'proceeding without concurrency limit'
- )
# Execute function with retries
start_time = time.time()
@@ -731,7 +792,11 @@ def retry(
finally:
if semaphore_acquired and semaphore:
- semaphore.release()
+ if semaphore_scope == 'multiprocess' and multiprocess_lock:
+ # Release the lock object for portalocker
+ await asyncio.to_thread(lambda: multiprocess_lock.release())
+ elif semaphore:
+ semaphore.release()
return wrapper
diff --git a/pyproject.toml b/pyproject.toml
index 3627146c3..29bbee3fb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -20,6 +20,7 @@ dependencies = [
"mem0ai>=0.1.106",
"patchright>=1.52.5",
"playwright>=1.52.0",
+ "portalocker>=2.7.0,<3.0.0",
"posthog>=3.7.0",
"psutil>=7.0.0",
"pydantic>=2.11.5",