Don't drain other event loops' buses in BaseEvent.__await__

SY
7d ago
+138-0

Fixes browser-use/browser-use#5509

When a handler awaits an event, BaseEvent.__await__ enters a drain loop that
iterates EventBus.all_instances — every bus in the process — and runs their
queued handlers on the awaiting task's loop.

In an app with more than one event loop (e.g. several agent sessions running in
parallel, each with its own loop), this executes one bus's handlers on another
bus's loop. Those handlers hang, events get stuck in started, and they pile up
until the bus hits its 100-event capacity:

The drain loop should only touch buses that belong to the current running loop —
every other bus is already drained by its own _run_loop on its own loop.

Changes:

  • Track each bus's owning loop in EventBus._loop (set in _start).
  • Skip buses whose _loop isn't the current running loop in the __await__ drain.

Added tests/test_cross_loop_isolation.py: a bus on a second loop is kept busy
while a handler on the main loop awaits its event; the test asserts that event is
never run on the wrong loop. It fails on main and passes with the fix. Full
suite passes (139 tests).


Summary by cubic

Prevent cross-loop handler execution by making BaseEvent.__await__ drain only buses on the current, running event loop. Previously it drained all process-global buses and ran their handlers on the awaiting task’s loop; now it skips buses on other loops and stopped buses. Single-loop behavior is unchanged; multi-loop apps avoid stuck events and capacity overflows.

  • Track the owning loop in EventBus._loop (set in _start).
  • In the __await__ drain, skip buses whose _loop differs from the current loop or whose _is_running is False.
  • Add tests/test_cross_loop_isolation.py to assert a bus on another loop is never drained; make teardown unconditional to avoid leaked background threads.