Skip to content

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

fix(browser): tolerate stepping a torn-down event bus on warm-Lambda resume

Saurav Panda16c2745a37b4
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 17099c4aa..15867e8e9 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -11,7 +11,7 @@ from urllib.parse import urlparse, urlunparse
from uuid import UUID
import httpx
-from bubus import EventBus
+from bubus import BaseEvent, EventBus
from cdp_use import CDPClient
from cdp_use.cdp.fetch import AuthRequiredEvent, RequestPausedEvent
from cdp_use.cdp.network import Cookie
@@ -103,6 +103,37 @@ class CDPSession(BaseModel):
_lifecycle_lock: Any = PrivateAttr(default=None)
+class ResilientEventBus(EventBus):
+ """``EventBus`` whose ``step()``/``wait_until_idle()`` tolerate a torn-down bus.
+
+ On a warm-Lambda resume the V2 worker can reuse a ``keep_alive`` ``BrowserSession``
+ whose event bus was already stopped and had its async primitives (``event_queue`` /
+ ``_on_idle``) nulled out by ``Agent.close()`` (done to release the event loop). In that
+ state bubus's ``EventBus.step()`` asserts ``EventBus._start() must be called before
+ step()``, which crashed the worker mid-run and dead-lettered the task (ENG-5280).
+
+ The nulling is deliberate — it lets the next ``dispatch()`` recreate a fresh queue and
+ ``_start()`` the bus again — so instead of changing teardown we make ``step()`` and
+ ``wait_until_idle()`` safe no-ops when the bus has not been started. A later
+ ``dispatch()`` still restarts the bus as usual.
+ """
+
+ async def step(
+ self,
+ event: 'BaseEvent[Any] | None' = None,
+ timeout: float | None = None,
+ wait_for_timeout: float = 0.1,
+ ) -> 'BaseEvent[Any] | None':
+ if self._on_idle is None or self.event_queue is None:
+ return None
+ return await super().step(event, timeout, wait_for_timeout)
+
+ async def wait_until_idle(self, timeout: float | None = None) -> None:
+ if self._on_idle is None or self.event_queue is None:
+ return None
+ return await super().wait_until_idle(timeout)
+
+
class BrowserSession(BaseModel):
"""Event-driven browser session with backwards compatibility.
@@ -518,7 +549,7 @@ class BrowserSession(BaseModel):
return self._demo_mode
# Main shared event bus for all browser session + all watchdogs
- event_bus: EventBus = Field(default_factory=EventBus)
+ event_bus: EventBus = Field(default_factory=ResilientEventBus)
# Mutable public state - which target has agent focus
agent_focus_target_id: TargetID | None = None
@@ -713,7 +744,7 @@ class BrowserSession(BaseModel):
# Reset all state
await self.reset()
# Create fresh event bus
- self.event_bus = EventBus()
+ self.event_bus = ResilientEventBus()
async def stop(self) -> None:
"""Stop the browser session without killing the browser process.
@@ -738,7 +769,7 @@ class BrowserSession(BaseModel):
# Reset all state
await self.reset()
# Create fresh event bus
- self.event_bus = EventBus()
+ self.event_bus = ResilientEventBus()
async def close(self) -> None:
"""Alias for stop()."""
diff --git a/tests/ci/test_event_bus_resilience.py b/tests/ci/test_event_bus_resilience.py
new file mode 100644
index 000000000..29f85b8d5
--- /dev/null
+++ b/tests/ci/test_event_bus_resilience.py
@@ -0,0 +1,83 @@
+"""Regression tests for ENG-5280: V2 worker crash on warm-Lambda resume.
+
+When a ``keep_alive`` ``BrowserSession`` is reused across warm Lambda invocations, its
+event bus is stopped and has its async primitives (``event_queue`` / ``_on_idle``) nulled
+out by ``Agent.close()`` to release the event loop. On resume the worker can ``step()`` the
+torn-down bus before any ``dispatch()`` restarts it. Stock ``bubus.EventBus.step()`` asserts
+``EventBus._start() must be called before step()`` in that state, crashing the run.
+
+``BrowserSession`` therefore uses ``ResilientEventBus``, whose ``step()`` / ``wait_until_idle()``
+are safe no-ops on a torn-down bus while a later ``dispatch()`` still restarts it.
+"""
+
+import asyncio
+
+from bubus import BaseEvent, EventBus
+
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.session import ResilientEventBus
+
+
+class ResiliencePingEvent(BaseEvent):
+ pass
+
+
+def _tear_down_like_agent_close(bus: EventBus) -> None:
+ """Mimic the keep_alive teardown in Agent.close() that triggers ENG-5280."""
+ bus.event_queue = None
+ bus._on_idle = None
+
+
+def test_browser_session_uses_resilient_event_bus():
+ """The session's default event bus must be the resilient subclass."""
+ session = BrowserSession(browser_profile=BrowserProfile(keep_alive=True))
+ assert isinstance(session.event_bus, ResilientEventBus)
+
+
+async def test_step_on_torn_down_bus_is_noop_not_assertion():
+ """Stepping a stopped+nulled bus returns None instead of raising AssertionError."""
+ bus = ResilientEventBus(name='ResilientWarmResumeStep')
+ bus.dispatch(ResiliencePingEvent())
+ await asyncio.sleep(0.1)
+ await bus.stop(clear=False, timeout=1.0)
+ _tear_down_like_agent_close(bus)
+
+ # Warm-Lambda resume: worker steps the torn-down bus. Must not raise.
+ assert await bus.step() is None
+ assert await bus.wait_until_idle(timeout=0.1) is None
+
+
+async def test_torn_down_bus_still_restarts_on_dispatch():
+ """A later dispatch() must recreate the queue and process events normally."""
+ processed: list[BaseEvent] = []
+ bus = ResilientEventBus(name='ResilientWarmResumeRestart')
+ bus.on('ResiliencePingEvent', lambda event: processed.append(event))
+
+ bus.dispatch(ResiliencePingEvent())
+ await asyncio.sleep(0.1)
+ await bus.stop(clear=False, timeout=1.0)
+ _tear_down_like_agent_close(bus)
+
+ # No-op step on the torn-down bus, then dispatch again -> bus restarts.
+ assert await bus.step() is None
+ processed.clear()
+ event = bus.dispatch(ResiliencePingEvent())
+ await asyncio.wait_for(event, timeout=2.0)
+ assert len(processed) == 1
+ await bus.stop(timeout=0.5)
+
+
+async def test_stock_event_bus_reproduces_the_crash():
+ """Document the upstream bug the subclass guards against (stock bus still asserts)."""
+ bus = EventBus(name='StockWarmResume')
+ bus.dispatch(ResiliencePingEvent())
+ await asyncio.sleep(0.1)
+ await bus.stop(clear=False, timeout=1.0)
+ _tear_down_like_agent_close(bus)
+
+ try:
+ await bus.step()
+ raised = False
+ except AssertionError:
+ raised = True
+ assert raised, 'stock EventBus.step() should assert on a torn-down bus'