Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
fixed events
Nick Sweetingd0ec528802e7
diff --git a/.github/.git-blame-ignore-revs b/.github/.git-blame-ignore-revsindex 6565a193f..df9bfe8c8 100644--- a/.github/.git-blame-ignore-revs+++ b/.github/.git-blame-ignore-revs@@ -1 +1,2 @@66b3c26df51adec32d42c3b2c0304e0662457298+2be4ba4f7078d47bbeed04baf6f8fb04017df028diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex e3b080762..baf273bed 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -8,7 +8,7 @@ from typing import Any, Literalfrom langchain_core.language_models.chat_models import BaseChatModelfrom openai import RateLimitError-from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model+from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model, model_validatorfrom uuid_extensions import uuid7strfrom browser_use.agent.message_manager.views import MessageManagerState@@ -109,6 +109,17 @@ class ActionResult(BaseModel):error: str | None = Noneinclude_in_memory: bool = False # whether to include in past messages as context or not+ @model_validator(mode='after')+ def validate_success_requires_done(self):+ """Ensure success=True can only be set when is_done=True"""+ if self.success is True and self.is_done is not True:+ raise ValueError(+ 'success=True can only be set when is_done=True. '+ 'For regular actions that succeed, leave success as None. '+ 'Use success=False only for actions that fail.'+ )+ return self+class StepMetadata(BaseModel):"""Metadata for a single step including timing and token information"""diff --git a/browser_use/eventbus/models.py b/browser_use/eventbus/models.pyindex 3b7ad8b7c..9e2595639 100644--- a/browser_use/eventbus/models.py+++ b/browser_use/eventbus/models.py@@ -1,54 +1,104 @@import asyncioimport logging-import warnings+from collections.abc import Awaitable, Callablefrom datetime import UTC, datetime-from typing import TYPE_CHECKING, Annotated, Any+from typing import TYPE_CHECKING, Annotated, Any, Selffrom uuid import UUID-from pydantic import AfterValidator, BaseModel, Field, PrivateAttr+from pydantic import AfterValidator, BaseModel, ConfigDict, Field, PrivateAttrfrom uuid_extensions import uuid7strfrom browser_use.utils import get_browser_use_version-logger = logging.getLogger(__name__)-if TYPE_CHECKING:from browser_use.eventbus.service import EventBus-# Constants for validation-MAX_STRING_LENGTH = 10000 # 10K chars for most strings-MAX_URL_LENGTH = 2000-MAX_TASK_LENGTH = 5000-MAX_COMMENT_LENGTH = 2000-MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MB++logger = logging.getLogger(__name__)+++def is_valid_event_name(s: str) -> bool:+ assert str(s).isidentifier() and not str(s).startswith('_'), f'Invalid event name: {s}'+ return str(s)+++def is_valid_python_id(s: str) -> bool:+ assert str(s).isdigit(), f'Invalid Python ID: {s}'+ return str(s)+UUIDStr = Annotated[str, AfterValidator(lambda s: str(UUID(s)))]+PythonIdStr = Annotated[str, AfterValidator(is_valid_python_id)]+PythonIdentifierStr = Annotated[str, AfterValidator(is_valid_event_name)]+EventHandler = Callable[['BaseEvent'], Any] | Callable[['BaseEvent'], Awaitable[Any]]+class BaseEvent(BaseModel):"""The base model used for all Events that flow through the EventBus system."""-- model_config = {'arbitrary_types_allowed': True}+ model_config = ConfigDict(arbitrary_types_allowed=True, validate_assignment=True, validate_default=True)++ event_type: PythonIdentifierStrevent_schema: str | None = Field(default=None, description='Event schema version in format ClassName@version', max_length=100)- event_type: str- event_id: str = Field(default_factory=uuid7str)- event_path: list[str] = Field(default_factory=list, description='Path tracking for event routing')- event_parent_id: str | None = Field(default=None, description='ID of the parent event that triggered this event')+ event_timeout: float | None = Field(default=60.0, description='Timeout in seconds for event to complete')++ # Runtime metadata+ event_id: UUIDStr = Field(default_factory=uuid7str, max_length=36)+ event_path: list[PythonIdentifierStr] = Field(default_factory=list, description='Path tracking for event routing')+ event_parent_id: UUIDStr | None = Field(+ default=None, description='ID of the parent event that triggered this event', max_length=36+ )# Completion tracking fieldsevent_created_at: datetime = Field(- default_factory=lambda: datetime.now(UTC), description='Timestamp when event was queued/created'+ default_factory=lambda: datetime.now(UTC),+ description='Timestamp when event was first dispatched to an EventBus aka marked pending',)- event_started_at: datetime | None = Field(default=None, description='Timestamp when event was started')- event_completed_at: datetime | None = Field(default=None, description='Timestamp when event was completed')-- # Results indexed by handler ID- event_results: dict[str, 'EventResult'] = Field(default_factory=dict, exclude=True)-++ event_results: dict[PythonIdStr, 'EventResult'] = Field(+ default_factory=dict, exclude=True+ ) # Results indexed by str(id(handler_func))+# Completion signal_event_completed: asyncio.Event | None = PrivateAttr(default=None)+ _event_processed_at: datetime | None = PrivateAttr(default=None)++ def __str__(self) -> str:+ icon = (+ '⏳'+ if self.event_status == 'pending'+ else '✅'+ if self.event_status == 'completed'+ else '❌'+ if self.event_status == 'error'+ else '🏃'+ )+ return f'{self.__class__.__name__}#{self.event_id[-4:]}{icon}{">".join(self.event_path[1:])})'++ def _log_safe_summary(self) -> str:+ """only event metadata without contents, avoid potentially sensitive event contents in logs"""+ return {k: v for k, v in self.model_dump(mode='json').items() if k.startswith('event_') and 'results' not in k}++ def __await__(self) -> Self:+ """Wait for event to complete and return self"""++ async def wait_for_handlers_to_complete_then_return_event():+ assert self.event_completed is not None+ try:+ await asyncio.wait_for(self.event_completed.wait(), timeout=self.event_timeout)+ except TimeoutError as err:+ raise RuntimeError(+ f'{self} waiting for results timed out after {self.event_timeout}s (being processed by {len(self.event_results)} handlers)'+ ) from err+ return self++ return wait_for_handlers_to_complete_then_return_event().__await__()++ def __hash__(self) -> int:+ """Make events hashable using their unique event_id"""+ return hash(self.event_id)@propertydef event_completed(self) -> asyncio.Event | None:@@ -62,115 +112,166 @@ class BaseEvent(BaseModel):return self._event_completed@property- def state(self) -> str:- return 'completed' if self.event_completed_at else 'started' if self.event_started_at else 'queued'+ def event_started_at(self) -> datetime | None:+ """Timestamp when event first started being processed by any handler"""+ started_times = [result.started_at for result in self.event_results.values() if result.started_at is not None]+ # If no handlers but event was processed, use the processed timestamp+ if not started_times and self._event_processed_at:+ return self._event_processed_at+ return min(started_times) if started_times else None++ @property+ def event_completed_at(self) -> datetime | None:+ """Timestamp when event was completed by all handlers"""+ # If no handlers at all but event was processed, use the processed timestamp+ if not self.event_results and self._event_processed_at:+ return self._event_processed_at++ # All handlers must be done (completed or error)+ all_done = all(result.status in ('completed', 'error') for result in self.event_results.values())+ if not all_done:+ return None++ # Return the latest completion time+ completed_times = [result.completed_at for result in self.event_results.values() if result.completed_at is not None]+ return max(completed_times) if completed_times else self._event_processed_at++ @property+ def event_status(self) -> str:+ return 'completed' if self.event_completed_at else 'started' if self.event_started_at else 'pending'def model_post_init(self, __context: Any) -> None:- """Initialize completion event and set event schema after model creation"""+ """Append the library version number to the event schema so we know what version was used to create any JSON dump"""if self.event_schema is None:version = get_browser_use_version()self.event_schema = f'{self.__class__.__module__}.{self.__class__.__qualname__}@{version}'- def event_result_update(self, handler: Any=None, eventbus: 'EventBus'=None, **kwargs) -> None:+ def event_result_update(+ self, handler: EventHandler | None = None, eventbus: 'EventBus | None' = None, **kwargs+ ) -> 'EventResult':"""Create or update an EventResult for a handler"""- handler_id = str(id(handler))+ handler_id: PythonIdStr = str(id(handler))eventbus = eventbus or (handler and hasattr(handler, '__self__') and handler.__self__) or None- eventbus_id = str(id(eventbus))+ eventbus_id: PythonIdStr = str(id(eventbus))# Get or create EventResultif handler_id not in self.event_results:self.event_results[handler_id] = EventResult(handler_id=handler_id,- handler_name=handler and handler.__name__ or '??unknown_handler??',+ handler_name=handler and handler.__name__ or str(handler),eventbus_id=eventbus_id,- eventbus_name=eventbus and eventbus.name or '??unknown_eventbus??',+ eventbus_name=eventbus and eventbus.name or str(eventbus),event_parent_id=self.event_id,status=kwargs.get('status', 'pending'),+ timeout=self.event_timeout,)-+ logger.debug(f'Created EventResult for handler {handler_id}: {handler.__name__}')+# Update the EventResult with provided kwargsself.event_results[handler_id].update(**kwargs)- self._check_completion()+ logger.debug(+ f'Updated EventResult for handler {handler_id}: status={self.event_results[handler_id].status}, total_results={len(self.event_results)}'+ )+ # Don't mark complete here - let the EventBus do it after all handlers are done+ return self.event_results[handler_id]- def _check_completion(self) -> None:+ def _mark_complete_if_all_handlers_completed(self) -> None:"""Check if all handlers are done and signal completion"""if self.event_completed and not self.event_completed.is_set():- all_done = all(- result.status in ('completed', 'error')- for result in self.event_results.values()- )+ # If there are no results at all, the event is complete+ if not self.event_results:+ self._event_processed_at = datetime.now(UTC)+ self.event_completed.set()+ return++ # Otherwise check if all results are done+ all_done = all(result.status in ('completed', 'error') for result in self.event_results.values())if all_done:- self.event_completed_at = datetime.now(UTC)+ self._event_processed_at = datetime.now(UTC)self.event_completed.set()-- async def event_results_by_handler_id(self) -> dict[str, Any]:- """Get results keyed by handler ID"""- # Wait for completion- if self.event_completed:- await self.event_completed.wait()-- results = {}- for handler_id, event_result in self.event_results.items():- if event_result.status == 'completed' and event_result.result is not None:- results[handler_id] = event_result.result- return results-- async def event_results_flat_dict(self) -> dict[str, Any]:++ async def event_results_by_handler_id(self, timeout: float | None = None) -> dict[PythonIdStr, Any]:+ """Get all results by handler id"""+ try:+ await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)+ except TimeoutError:+ pass+ return {handler_id: await event_result for handler_id, event_result in self.event_results.items()}++ async def event_results_flat_dict(self, timeout: float | None = None) -> dict[Any, Any]:"""Merge all dict results into single dict"""- await self.event_completed.wait()-- merged = {}+ try:+ await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)+ except TimeoutError:+ pass++ merged_results: dict[Any, Any] = {}for event_result in self.event_results.values():if event_result.status == 'completed' and event_result.result is not None:if not event_result.result: # skip if result is {} or Nonecontinue+ if isinstance(event_result.result, BaseEvent): # skip if result is another Event+ continueif not isinstance(event_result.result, dict):- raise TypeError(f"Handler '{event_result.handler_name}' returned {type(event_result.result).__name__} instead of dict")- merged.update(event_result.result) # update the merged dict with the contents of the result dict- return merged-- async def event_results_flat_list(self) -> list[Any]:+ # raise TypeError(f"Handler '{event_result.handler_name}' returned {type(event_result.result).__name__} instead of dict")+ continue+ merged_results.update(event_result.result) # update the merged dict with the contents of the result dict+ return merged_results++ async def event_results_flat_list(self, timeout: float | None = None) -> list[Any]:"""Merge all list results into single list"""- await self.event_completed.wait()-- merged = []+ try:+ await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)+ except TimeoutError:+ pass++ merged_results = []for event_result in self.event_results.values():if event_result.status == 'completed' and event_result.result is not None:if isinstance(event_result.result, list):- merged.extend(event_result.result) # append the contents of the list to the merged list+ merged_results.extend(event_result.result) # append the contents of the list to the merged list+ elif isinstance(event_result.result, BaseEvent): # skip if result is another Event+ continueelse:- merged.append(event_result.result) # append individual item to the merged list- return merged+ merged_results.append(event_result.result) # append individual item to the merged list+ return merged_results- async def event_result(self, timeout: float = 30.0) -> Any:- results = await self.event_results_flat_list()+ async def event_result(self, timeout: float | None = None) -> Any:+ results = await self.event_results_flat_list(timeout=timeout)return results[0] if results else None-- async def result(self, timeout: float = 30.0) -> 'BaseEvent':- """Wait for event to complete and return self"""- if self.event_completed:- await self.event_completed.wait()- return self+++# PSA: All BaseEvent buil-in attrs and methods must be prefixed with "event_" in order to avoid clashing with data contents (which share a namespace with the metadata)+# This is the same approach Pydantic uses for their special `model_*` attrs (and BaseEvent is also a pydantic model, so model_ prefixes are reserved too)+# resist the urge to nest the event data in an inner object unless absolutely necessary, flat simplifies most of the code and makes it easier to read JSON logs with less nesting+pydantic_builtin_attrs = dir(BaseModel)+event_builtin_attrs = {key for key in dir(BaseEvent) if key.startswith('event_')}+attr_name_allowed = lambda key: key in pydantic_builtin_attrs or key in event_builtin_attrs or key.startswith('_')+illegal_attrs = {key for key in dir(BaseEvent) if not attr_name_allowed(key)}+assert not illegal_attrs, (+ f'All BaseEvent attrs and methods must be prefixed with "event_" in order to avoid clashing with BaseEvent subclass fields used to store event contents (which share a namespace with the event_ metadata). not allowed: {illegal_attrs}'+)class EventResult(BaseModel):"""Individual result from a single handler"""-+id: str = Field(default_factory=uuid7str)handler_id: strhandler_name: streventbus_id: streventbus_name: str+ timeout: float = 60.0status: str = 'pending' # pending, started, completed, errorresult: Any = Noneerror: str | None = Nonestarted_at: datetime | None = Nonecompleted_at: datetime | None = Noneevent_parent_id: str | None = None-- # Completion signal++ # Completion signal_completed: asyncio.Event | None = PrivateAttr(default=None)@property@@ -183,27 +284,35 @@ class EventResult(BaseModel):except RuntimeError:pass # Keep it None if no event loopreturn self._completed+# _event: BaseEvent | None = PrivateAttr(default=None) # in a db we'd store a foreign key to the event-+model_config = {'arbitrary_types_allowed': True}def __str__(self) -> str:handler_qualname = f'{self.eventbus_name}.{self.handler_name}'- return f"{handler_qualname}() -> {self.result or self.error or '...'} ({self.status})"--+ return f'{handler_qualname}() -> {self.result or self.error or "..."} ({self.status})'++ def __repr__(self) -> str:+ icon = '🏃' if self.status == 'pending' else '✅' if self.status == 'completed' else '❌'+ return f'{self.handler_name}#{self.handler_id[-4:]}(e) {icon}'+def __await__(self):"""Wait for this result to complete and return the result or raise error"""- async def wait_and_return():- await self.completed.wait()-++ async def wait_for_handler_to_complete_and_return_result():+ try:+ await asyncio.wait_for(self.completed.wait(), timeout=self.timeout)+ except TimeoutError as err:+ raise RuntimeError(f'Handler {self.handler_name} timed out after {self.event_timeout}s') from err+if self.status == 'error' and self.error:- raise RuntimeError(f"Handler {self.handler_name} failed: {self.error}")-+ raise RuntimeError(f'Handler {self.handler_name} failed: {self.error}')+return self.result-- return wait_and_return().__await__()-++ return wait_for_handler_to_complete_and_return_result().__await__()+def update(self, **kwargs) -> None:"""Update the EventResult with provided kwargs"""if 'result' in kwargs:diff --git a/browser_use/eventbus/service.py b/browser_use/eventbus/service.pyindex 33ec6e797..9443a5df7 100644--- a/browser_use/eventbus/service.py+++ b/browser_use/eventbus/service.py@@ -3,24 +3,22 @@ import inspectimport loggingimport warningsfrom collections import defaultdict-from collections.abc import Awaitable, Callable-from contextvars import ContextVar, copy_context-from datetime import UTC, datetime+from collections.abc import Callable+from contextvars import ContextVarfrom pathlib import Path-from typing import Any, Union+from typing import Any, Literalimport anyiofrom pydantic import BaseModelfrom uuid_extensions import uuid7str-from browser_use.eventbus.models import BaseEvent, UUIDStr+from browser_use.eventbus.models import BaseEvent, EventHandler, PythonIdentifierStr, PythonIdStr, UUIDStr+from browser_use.utils import _log_pretty_pathlogger = logging.getLogger(__name__)-# Type alias for event handlers-EventHandler = Union[Callable[[BaseEvent], Any], Callable[[BaseEvent], Awaitable[Any]]]-# Context variable to track the current event being processed+# Context variable to track the current event being processed (for setting event_parent_id from inside a child event)_current_event_context: ContextVar[BaseEvent | None] = ContextVar('current_event', default=None)@@ -29,25 +27,30 @@ class EventBus:Async event bus with write-ahead logging and guaranteed FIFO processing.Features:- - Enqueue events synchronously, await their results using await event.result()+ - Enqueue events synchronously, await their results using 'await Event()'- FIFP Write-ahead logging with UUIDs and timestamps,- Serial event processing, parallel handler execution per event"""- name: str- event_queue: asyncio.Queue[BaseEvent] | None- event_history: dict[UUIDStr, BaseEvent]- handlers: dict[str, list[EventHandler]]- wal_path: Path | None = None+ # Class Attributes+ name: PythonIdentifierStrparallel_handlers: bool = False+ wal_path: Path | None = None+ handlers: dict[PythonIdStr, list[EventHandler]] # collected by .on(<event_type>, <handler>)+ # Runtime Stateid: UUIDStr+ event_queue: asyncio.Queue[BaseEvent] | None+ event_history: dict[UUIDStr, BaseEvent] # collected by .dispatch(<event>)+_is_running: bool = False_runloop_task: asyncio.Task | None = None_runloop_lock: asyncio.Lock | None = None_on_idle: asyncio.Event | None = None- def __init__(self, name: str | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = False):+ def __init__(+ self, name: PythonIdentifierStr | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = False+ ):self.id = uuid7str()self.name = name or f'EventBus_{self.id[-8:]}'assert self.name.isidentifier(), f'EventBus name must be a unique identifier string, got: {self.name}'@@ -55,37 +58,52 @@ class EventBus:self.event_history = {}self.handlers = defaultdict(list)self.parallel_handlers = parallel_handlers+ self.wal_path = Path(wal_path) if wal_path else Noneself._runloop_lock = Noneself._on_idle = None- # Set up WAL path and create parent directory if needed- if wal_path:- self.wal_path = Path(wal_path)- self.wal_path.parent.mkdir(parents=True, exist_ok=True)-- # Register default logger handler- self.on('*', self._default_log_handler)+ # Instead of registering as normal event handlers,+ # these special handlers are just called manually at the end of _run_loop_step+ # self.on('*', self._default_log_handler)+ # self.on('*', self._default_wal_handler)def __del__(self):"""Auto-cleanup on garbage collection"""if self._is_running:self._is_running = False- if self._runloop_task and not self._runloop_task.done():- try:- self._runloop_task.cancel()- except RuntimeError:- pass++ if self._runloop_task and not self._runloop_task.done():+ try:+ self._runloop_task.cancel()+ except RuntimeError:+ pass # No event loop - that's fine++ # Suppress the warning by accessing internal asyncio attributes+ # This prevents "Task was destroyed but it is pending" warnings+ if hasattr(self._runloop_task, '_log_destroy_pending'):+ self._runloop_task._log_destroy_pending = False++ # Also try to get the exception to mark it as handled+ try:+ self._runloop_task.exception()+ except (asyncio.CancelledError, asyncio.InvalidStateError):+ pass # Expected for cancelled or pending tasks+ except RuntimeError:+ pass # No event loop - that's finedef __str__(self) -> str:- return self.name+ icon = '🟢' if self._is_running else '🔴'+ return f'{self.name}{icon}(⏳ {len(self.events_pending or [])} | ▶️ {len(self.events_started or [])} | ✅ {len(self.events_completed or [])} ➡️ {len(self.handlers)} 👂)'def __repr__(self) -> str:- return self.name+ return str(self)@property- def events_queued(self) -> list[BaseEvent]:- """Get events that haven't started processing yet"""- return [event for event in self.event_history.values() if event.event_started_at is None]+ def events_pending(self) -> list[BaseEvent]:+ """Get events that haven't started processing yet (does not include events that have not even finished dispatching yet in self.event_queue)"""+ return [+ event for event in self.event_history.values() if event.event_started_at is None and event.event_completed_at is None+ ]@propertydef events_started(self) -> list[BaseEvent]:@@ -97,7 +115,7 @@ class EventBus:"""Get events that have completed processing"""return [event for event in self.event_history.values() if event.event_completed_at is not None]- def on(self, event_pattern: str | type[BaseModel], handler: EventHandler) -> None:+ def on(self, event_pattern: PythonIdentifierStr | Literal['*'] | type[BaseModel], handler: EventHandler) -> None:"""Subscribe to events matching a pattern, event type name, or event model class.Use event_pattern='*' to subscribe to all events. Handler can be sync or async function or method.@@ -107,7 +125,7 @@ class EventBus:eventbus.on(TaskStartedEvent, handler) # Event model classeventbus.on('*', handler) # Subscribe to all eventseventbus.on('*', other_eventbus.dispatch) # Forward all events to another EventBus-+Note: When forwarding events between buses, all handler results are automaticallyflattened into the original event's results, so EventResults sees all handlersfrom all buses as a single flat collection.@@ -119,37 +137,47 @@ class EventBus:event_key = event_pattern.__name__else:event_key = str(event_pattern)-+# Check for duplicate handler names- handler_name = handler.__name__+ if hasattr(handler, '__self__'):+ handler_name = f'{handler.__self__}.{handler.__name__}()'+ else:+ handler_name = handler.__name__existing_names = [h.__name__ for h in self.handlers.get(event_key, [])]-+if handler_name in existing_names:warnings.warn(f"⚠️ Handler '{handler_name}' already registered for event '{event_key}'. "- f"This may cause ambiguous results when using name-based access. "- f"Consider using unique function names.",+ f'This may cause ambiguous results when using name-based access. '+ f'Consider using unique function names.',UserWarning,- stacklevel=2+ stacklevel=2,)-+# Register handlerself.handlers[event_key].append(handler)- logger.debug(f"✅ {self} Registered handler {handler_name} for event {event_key}")-- # Auto-start if needed (but not for the default logger)- if not self._is_running and handler_name != '_default_log_handler':- self._start()+ logger.debug(f'👂 {self}.on({event_key}, {handler_name}) Registered event handler')- def dispatch(self, event: BaseEvent, timeout: float = 30.0) -> BaseEvent:+ def dispatch(self, event: BaseEvent) -> BaseEvent:"""- Enqueue an event for processing and return the event.- (Auto-starts the EventBus's async _run_loop() if not already running)+ Enqueue an event for processing and immediately return an Event(status='pending') version (synchronous).+ You can then await the Event(status='pending') object to block until its Event(status='completed') versionis ready,+ or you can interact with the unawaited Event(status='pending') before its handlers have finished.- Returns the event which can be awaited using event.result() or other query methods.+ (The first EventBus.dispatch() call will auto-start a bus's async _run_loop() if it's not already running)++ >>> completed_event = await eventbus.dispatch(SomeEvent())+ # 1. enqueues the event synchronously+ # 2. returns an awaitable SomeEvent() with pending results in .event_results+ # 3. awaits the SomeEvent() which waits until all pending results are complete and returns the completed SomeEvent()++ >>> result_value = await eventbus.dispatch(SomeEvent()).event_result()+ # 1. enqueues the event synchronously+ # 2. returns a pending SomeEvent() with pending results in .event_results+ # 3. awaiting .event_result() waits until all pending results are complete, and returns the raw result value of the first one"""assert event.event_id, 'Missing event.event_id: UUIDStr = uuid7str()'- assert event.event_created_at, 'Missing event.queued_at: datetime = datetime.now(UTC)'+ assert event.event_created_at, 'Missing event.event_created_at: datetime = datetime.now(UTC)'assert event.event_type and event.event_type.isidentifier(), 'Missing event.event_type: str'assert event.event_schema and '@' in event.event_schema, 'Missing event.event_schema: str (with @version)'@@ -164,6 +192,10 @@ class EventBus:# preserve identity of the original object instead of creating a new one, so that the original object remains awaitable to get the result# NOT: event = event.model_copy(update={'event_path': event.event_path + [self.name]})event.event_path.append(self.name)+ else:+ logger.debug(+ f'⚠️ {self}.dispatch({event.event_type}) - Bus already in path, not adding again. Path: {event.event_path}'+ )assert event.event_path, 'Missing event.event_path: list[str] (with at least the origin function name recorded in it)'assert all(entry.isidentifier() for entry in event.event_path), (@@ -172,48 +204,56 @@ class EventBus:# Add event to historyself.event_history[event.event_id] = event+ logger.debug(f'📝 {self}.dispatch() adding event {event.event_id} to history')+ # Auto-start if neededself._start()# Put event in queue synchronously using put_nowaitif self.event_queue:try:- logger.debug(f'📋 {self} Dispatching event {event.event_type} to queue')self.event_queue.put_nowait(event)+ logger.debug(+ f'🗣️ {self}.dispatch({event.event_type}) ➡️ Event#{event.event_id[-8:]}({event.event_status} #{self.event_queue.qsize()})'+ )except asyncio.QueueFull:- logger.error(f'⚠️ {self} Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')+ logger.error(+ f'⚠️ {self} Event queue is full! Dropping event and aborting {event.event_type}:\n{event.model_dump_json()}'+ )+ raise # could also block indefinitely until queue has space, but dont drop silently or delete events+ else:+ logger.warning(f'⚠️ {self}.dispatch() called but event_queue is None! Event not queued: {event.event_type}')++ # Note: We do NOT pre-create EventResults here anymore.+ # EventResults are created only when handlers actually start executing.+ # This avoids "orphaned" pending results for handlers that get filtered out later.- # Record pending results for all applicable handlers- applicable_handlers = self._get_applicable_handlers(event)- for handler in applicable_handlers.values():- event.event_result_update(handler=handler, eventbus=self, status='pending')-return eventasync def expect(self,- event_type: str | type[BaseModel],+ event_type: PythonIdentifierStr | type[BaseModel],timeout: float | None = None,predicate: Callable[[BaseEvent], bool] | None = None,) -> BaseEvent:"""Wait for an event matching the given type/pattern with optional predicate filter.-+Args:event_type: The event type string or model class to wait fortimeout: Maximum time to wait in seconds (None = wait forever)predicate: Optional filter function that must return True for the event to match-+Returns:The first matching event-+Raises:asyncio.TimeoutError: If timeout is reached before a matching event-+Example:# Wait for any response eventresponse = await eventbus.expect('ResponseEvent', timeout=30)-+# Wait for specific response with predicateresponse = await eventbus.expect('ResponseEvent',@@ -222,23 +262,25 @@ class EventBus:)"""future: asyncio.Future[BaseEvent] = asyncio.Future()-- def temporary_handler(event: BaseEvent) -> None:++ def notify_expect_handler(event: BaseEvent) -> None:"""Handler that resolves the future when a matching event is found"""if not future.done() and (predicate is None or predicate(event)):future.set_result(event)-++ notify_expect_handler.__name__ = f'{self}.expect({event_type}, predicate={predicate and id(predicate)})@{_log_pretty_path(inspect.currentframe().f_code.co_filename)}:{inspect.currentframe().f_lineno}' # add file and line number to the name+# Register temporary handler- self.on(event_type, temporary_handler)-+ self.on(event_type, notify_expect_handler)+try:# Wait for the future with optional timeoutreturn await asyncio.wait_for(future, timeout=timeout)finally:# Clean up handlerevent_key = event_type.__name__ if isinstance(event_type, type) else str(event_type)- if event_key in self.handlers and temporary_handler in self.handlers[event_key]:- self.handlers[event_key].remove(temporary_handler)+ if event_key in self.handlers and notify_expect_handler in self.handlers[event_key]:+ self.handlers[event_key].remove(notify_expect_handler)def _start(self) -> None:"""Start the event bus if not already running"""@@ -250,114 +292,134 @@ class EventBus:self.event_queue = asyncio.Queue()self._runloop_lock = asyncio.Lock()self._on_idle = asyncio.Event()- self._on_idle.set() # Start in idle state+ self._on_idle.clear() # Start in a busy state unless we confirm queue is empty by running _run_loop_step() at least once# Create and start the run loop task- self._runloop_task = loop.create_task(self._run_loop())+ self._runloop_task = loop.create_task(self._run_loop(), name=f'{self}._run_loop')self._is_running = Trueexcept RuntimeError:- pass # No event loop - will start when one becomes available+ # No event loop - will start when one becomes available+ pass- async def stop(self, timeout: float | None = None) -> None:+ async def stop(self, timeout: float = 0.0) -> None:"""Stop the event bus, optionally waiting for events to complete"""if not self._is_running:return- # Log current state-# Wait for completion if timeout specified- if timeout is not None:- await self.wait_until_idle(timeout=timeout)+ if timeout:+ try:+ await self.wait_until_idle(timeout=timeout)+ except TimeoutError:+ passqueue_size = self.event_queue.qsize() if self.event_queue else 0- if queue_size or self.events_queued or self.events_started:- logger.warning(- f'⚠️ {self} stopping with pending events: Queued {queue_size} | Pending {len(self.events_queued)} | Processing {len(self.events_started)} | Completed {len(self.events_completed)}'+ if queue_size or self.events_pending or self.events_started:+ logger.debug(+ f'⚠️ {self} stopping with pending events: Pending {len(self.events_pending) + queue_size} | Started {len(self.events_started)} | Completed {len(self.events_completed)}\n'+ f'PENDING={self.events_pending}\nSTARTED={self.events_started}')- # Force shutdown+ # Signal shutdownself._is_running = False- if self._runloop_task:++ # Cancel the run loop task if it exists+ if self._runloop_task and not self._runloop_task.done():self._runloop_task.cancel()try:- await self._runloop_task- except asyncio.CancelledError:+ # Wait for task to finish cancellation+ await asyncio.wait_for(self._runloop_task, timeout=1.0)+ except (asyncio.CancelledError, TimeoutError):+ # Expected - task was cancelled or timed outpass+ except Exception as e:+ logger.debug(f'Exception while stopping {self}: {e}')- logger.debug(f'⏹ {self} stopped gracefully' if timeout is not None else f'🛑 {self} stopped immediately')+ # Clear references+ self._runloop_task = None+ self._runloop_lock = None+ if self._on_idle:+ self._on_idle.set()++ logger.debug(f'🛑 {self} shut down gracefully' if timeout is not None else f'🛑 {self} killed')async def wait_until_idle(self, timeout: float | None = None) -> None:- """Wait until the event bus is idle (no events being processed)"""+ """Wait until the event bus is idle (no events being processed and all handlers completed)"""self._start()+ assert self._on_idle and self.event_queue, 'EventBus._start() must be called before wait_until_idle() is reached'# First wait for the queue to be empty- await self.event_queue.join()- # logger.debug(f'Queue joined, processing events: {len(self.events_started)}')-# Then wait for idle state with timeout- if self._on_idle:- try:- await asyncio.wait_for(self._on_idle.wait(), timeout=timeout)- except TimeoutError:- logger.warning(- f'⌛️ {self} Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})'- )+ try:+ await asyncio.wait_for(self.event_queue.join(), timeout=timeout)+ await asyncio.wait_for(self._on_idle.wait(), timeout=timeout)+ except TimeoutError:+ logger.warning(+ f'⌛️ {self} Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})'+ )async def _run_loop(self) -> None:"""Main event processing loop"""- while self._is_running:- try:- # Ensure we have async objects- if not self.event_queue:- logger.error(f'❌ {self} Event queue not initialized in _run_loop')- break-- # Check if we're idle- if self._on_idle:- if self.event_queue.empty() and len(self.events_started) == 0:- self._on_idle.set()- else:- self._on_idle.clear()-+ try:+ while self._is_running:try:- await self._run_loop_step()- except TimeoutError:- continue # No events in queue, continue to idle- except asyncio.CancelledError:- break- except Exception as e:- logger.exception(f'❌ {self} Error in event loop: {type(e).__name__} {e}')- # Continue running even if there's an error+ _processed_event = await self._run_loop_step()+ except RuntimeError as e:+ # Event loop is closing+ if 'Event loop is closed' in str(e) or 'no running event loop' in str(e):+ break+ else:+ logger.exception(f'❌ {self} Runtime error in event loop: {e}')+ # Continue running even if there's an error+ except Exception as e:+ logger.exception(f'❌ {self} Error in event loop: {type(e).__name__} {e}')+ # Continue running even if there's an error+ except asyncio.CancelledError:+ # Task was cancelled, clean exit+ # logger.debug(f'🛑 {self} Event loop task cancelled')+ pass+ finally:+ await self.stop()- async def _run_loop_step(self, event: BaseEvent | None = None) -> BaseEvent:+ async def _run_loop_step(+ self, event: BaseEvent | None = None, timeout: float | None = None, wait_for_timeout: float = 0.1+ ) -> BaseEvent:"""Process a single event from the queue"""+ assert self._runloop_lock, 'EventBus._start() must be called before _run_loop_step()'+ assert self._on_idle, 'EventBus._start() must be called before _run_loop_step()'+# Wait for next event with timeout to periodically check idle state- event = event or await asyncio.wait_for(self.event_queue.get(), timeout=0.1)+ if event is None:+ try:+ event = await asyncio.wait_for(self.event_queue.get(), timeout=wait_for_timeout)+ except TimeoutError:+ if not (self.events_pending or self.events_started or self.event_queue.qsize()):+ logger.debug(f'🛑 {self} idle')+ self._on_idle.set()+ return None++ logger.debug(f'🏃 {self}._run_loop_step({event}) STARTING')# Clear idle state when we get an event- if self._on_idle:- self._on_idle.clear()+ self._on_idle.clear()# Process the event- if self._runloop_lock:- async with self._runloop_lock:- event.event_started_at = datetime.now(UTC)+ async with self._runloop_lock:+ # Execute all handlers for this event+ applicable_handlers = self._get_applicable_handlers(event)+ await self._execute_handlers(event, handlers=applicable_handlers, timeout=timeout)- # Execute all handlers for this event- applicable_handlers = self._get_applicable_handlers(event)- await self._execute_handlers(event, handlers=applicable_handlers)+ await self._default_log_handler(event)+ await self._default_wal_handler(event)- # Mark event as completed- event.event_completed_at = datetime.now(UTC)+ # Mark event as complete if all handlers are done+ event._mark_complete_if_all_handlers_completed()- # Persist to WAL if configured- if self.wal_path:- wal_result = await self._default_wal_handler(event)- # logger.debug(f'WAL persistence result: {wal_result}')+ # Mark task as done+ self.event_queue.task_done()- # Mark task as done- self.event_queue.task_done()+ logger.debug(f'✅ {self}._run_loop_step({event}) COMPLETE')return eventdef _get_applicable_handlers(self, event: BaseEvent) -> dict[str, EventHandler]:@@ -375,7 +437,7 @@ class EventBus:filtered_handlers = {}for handler in applicable_handlers:if self._would_create_loop(event, handler):- logger.debug(f'Skipping {handler.__name__} to prevent loop for {event.event_type}')+ logger.debug(f'⚠️ {self} Skipping {handler.__name__}#{str(id(handler))[-4:]}({event}) to prevent infinite loop')continueelse:handler_id = str(id(handler))@@ -383,106 +445,162 @@ class EventBus:return filtered_handlers- async def _execute_handlers(self, event: BaseEvent, handlers: dict[str, EventHandler] | None = None) -> None:+ async def _execute_handlers(+ self, event: BaseEvent, handlers: dict[PythonIdStr, EventHandler] | None = None, timeout: float | None = None+ ) -> None:"""Execute all handlers for an event in parallel"""applicable_handlers = handlers if (handlers is not None) else self._get_applicable_handlers(event)if not applicable_handlers:+ event._mark_complete_if_all_handlers_completed() # mark event completed immediately if it has no handlersreturn# Execute all handlers in parallelif self.parallel_handlers:handler_tasks = {}for handler_id, handler in applicable_handlers.items():- task = asyncio.create_task(self._execute_sync_or_async_handler(event, handler))+ task = asyncio.create_task(+ self._execute_sync_or_async_handler(event, handler, timeout=timeout), name=f'{self}.{handler.__name__}'+ )handler_tasks[handler_id] = (task, handler)- # Wait for all handlers to complete and record results incrementally+ # Wait for all handlers to completefor handler_id, (task, handler) in handler_tasks.items():try:- result = await task- event.event_result_update(handler=handler, eventbus=self, result=result)+ await taskexcept Exception as e:- event.event_result_update(handler=handler, eventbus=self, error=str(e))- logger.error(- f'❌ {self} Handler {handler.__name__} failed for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}'- )+ # Error already logged and recorded in _execute_sync_or_async_handler+ passelse:# otherwise, execute handlers serially, wait until each one completes before moving on to the nextfor handler_id, handler in applicable_handlers.items():try:- # Mark handler as started- event.event_result_update(handler=handler, eventbus=self, status='started')-- # Execute the handler- result = await self._execute_sync_or_async_handler(event, handler)-- # Record successful result- event.event_result_update(handler=handler, eventbus=self, result=result)+ await self._execute_sync_or_async_handler(event, handler, timeout=timeout)except Exception as e:- # Record error- event.event_result_update(handler=handler, eventbus=self, error=str(e))- logger.error(- f'❌ {self} Handler {handler.__name__} failed for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}'+ # Error already logged and recorded in _execute_sync_or_async_handler+ logger.debug(+ f'❌ {self} Handler {handler.__name__}#{str(id(handler))[-4:]}({event}) failed with {type(e).__name__}: {e}')+ pass++ async def _execute_sync_or_async_handler(self, event: BaseEvent, handler: EventHandler, timeout: float | None = None) -> Any:+ """Safely execute a single handler with deadlock detection"""++ logger.debug(f' ↳ {self}._execute_handler({event}, handler={handler.__name__}#{str(id(handler))[-4:]})')++ # Check if this handler has already been executed for this event+ handler_id = str(id(handler))+ if handler_id in event.event_results:+ existing_result = event.event_results[handler_id]+ if existing_result.started_at is not None:+ raise RuntimeError(+ f'Handler {handler.__name__}#{handler_id[-4:]} has already been executed for event {event.event_id}. '+ f'Previous execution started at {existing_result.started_at}'+ )++ # Mark handler as started+ event_result = event.event_result_update(+ handler=handler, eventbus=self, status='started', timeout=timeout or event.event_timeout+ )- async def _execute_sync_or_async_handler(self, event: BaseEvent, handler: EventHandler) -> Any:- """Safely execute a single handler"""# Set the current event in context so child events can reference ittoken = _current_event_context.set(event)++ # Create a task to monitor for potential deadlock / slow handlers+ async def deadlock_monitor():+ await asyncio.sleep(15.0)+ logger.warning(+ f'⚠️ {self}.{handler.__name__}() has been running for >15s on event. Possible slow processing or deadlock.\n'+ '(handler could be trying to await its own result or another blocked async task).\n'+ f'{self}.{handler.__name__}({event})'+ )++ monitor_task = asyncio.create_task(deadlock_monitor(), name=f'{self}.deadlock_monitor.{handler.__name__}')+try:if inspect.iscoroutinefunction(handler):- return await handler(event)+ result = await asyncio.wait_for(handler(event), timeout=event_result.timeout)else:- # Run sync handler in thread pool with context preserved- loop = asyncio.get_event_loop()- ctx = copy_context()- # Create a wrapper that preserves the context- def context_preserving_wrapper():- # The context is already copied, just run the handler- return handler(event)- return await loop.run_in_executor(None, ctx.run, context_preserving_wrapper)+ # Run sync handler directly in the main thread+ # This blocks but ensures we have access to the event loop+ result = handler(event)+ logger.debug(f' ↳ Sync handler {handler.__name__}#{handler_id[-4:]} returned: {result}')+ # Cancel the monitor task since handler completed successfully+ monitor_task.cancel()++ # Record successful result+ event.event_result_update(handler=handler, eventbus=self, result=result)+ if handler_id in event.event_results:+ logger.debug(+ f' ↳ Updated result for {handler.__name__}#{handler_id[-4:]}: {event.event_results[handler_id].status}'+ )+ else:+ logger.error(f' ↳ ERROR: Result not found for {handler.__name__}#{handler_id[-4:]} after update!')+ return result+except Exception as e:+ # Cancel the monitor task on error too+ monitor_task.cancel()++ # Record error+ event.event_result_update(handler=handler, eventbus=self, error=str(e))+logger.exception(- f'❌ {self} Error in handler {handler.__name__} for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}'+ f'❌ {self} Error in handler {handler.__name__}#{str(id(handler))[-4:]}({event}): {type(e).__name__} {e}')raisefinally:# Reset context_current_event_context.reset(token)+ # Ensure monitor task is cancelled+ try:+ if not monitor_task.done():+ monitor_task.cancel()+ await monitor_task+ except asyncio.CancelledError:+ pass # Expected when we cancel the monitor+ except Exception as e:+ # logger.debug(f"❌ {self} Handler monitor task cleanup error for {handler.__name__}#{str(id(handler))[-4:]}({event}): {type(e).__name__}: {e}")+ pass- @staticmethod- def _would_create_loop(event: BaseEvent, handler: EventHandler) -> bool:+ def _would_create_loop(self, event: BaseEvent, handler: EventHandler) -> bool:"""Check if calling this handler would create a loop (i.e. re-process an event that has already been processed by this EventBus)"""- # If handler is another EventBus.dispatch method++ # First check: If handler is another EventBus.dispatch method, check if we're forwarding to another bus that it's already been processed byif hasattr(handler, '__self__') and isinstance(handler.__self__, EventBus) and handler.__name__ == 'dispatch':target_bus = handler.__self__- return target_bus.name in event.event_path+ if target_bus.name in event.event_path:+ return True++ # Second check: Check if there's already a completed result for this handler ID+ # This prevents the same handler from being called multiple times on the same event+ handler_id = str(id(handler))+ if handler_id in event.event_results:+ existing_result = event.event_results[handler_id]+ if existing_result.completed_at is not None:+ logger.debug(+ f'⚠️ Preventing loop: handler {handler.__name__} (id={handler_id}) already completed at {existing_result.completed_at} for event {event.event_id}'+ )+ return True+return False- async def _default_log_handler(self, event: BaseEvent) -> str:+ async def _default_log_handler(self, event: BaseEvent) -> None:"""Default handler that logs all events"""- logger.debug(- f'✅ {self} Event processed: {event.event_type} [{event.event_id}] -> {len(event.event_results)} results @ {event.event_completed_at}'- )- return 'logged'+ # logger.debug(+ # f'✅ {self} completed: {event} -> {list(event.event_results.values()) or '<no handlers matched>'}'+ # )+ pass- async def _default_wal_handler(self, event: BaseEvent) -> str:+ async def _default_wal_handler(self, event: BaseEvent) -> None:"""Persist completed event to WAL file as JSONL"""+if not self.wal_path:- return 'skipped'+ return Nonetry:- # Use model_dump_json which already handles datetime serializationevent_json = event.model_dump_json()-- # Append as JSONL (one JSON object per line)+ self.wal_path.parent.mkdir(parents=True, exist_ok=True)async with await anyio.open_file(self.wal_path, 'a') as f:await f.write(event_json + '\n')-- return 'appended'-except Exception as e:- logger.error(- f'❌ {self} Failed to save event {event.event_id} to WAL file: {type(e).__name__} {e}\n{event.model_dump()}'- )- return 'failed'+ logger.error(f'❌ {self} Failed to save event {event.event_id} to WAL file: {type(e).__name__} {e}\n{event}')diff --git a/tests/ci/test_eventbus.py b/tests/ci/test_eventbus.pyindex 5f7ce139a..84a7522b2 100644--- a/tests/ci/test_eventbus.py+++ b/tests/ci/test_eventbus.py@@ -86,7 +86,7 @@ class TestEventBusBasics:assert bus._is_running is Falseassert bus._runloop_task is Noneassert len(bus.event_history) == 0- assert len(bus.handlers['*']) == 1 # Default logger+ assert len(bus.handlers['*']) == 0 # No default logger anymoreasync def test_auto_start_and_stop(self, mock_agent):"""Test auto-start functionality and stopping the event bus"""@@ -119,32 +119,27 @@ class TestEventEnqueueing:async def test_emit_and_result(self, eventbus):"""Test event emission in async and sync contexts, and result() pattern"""# Test async emission- event = UserActionEvent(action='login', user_id='user123')- result = eventbus.dispatch(event)+ event = UserActionEvent(action='login', user_id='user123', event_timeout=1)+ queued = eventbus.dispatch(event)# Check immediate result- assert isinstance(result, UserActionEvent)- assert result.event_type == 'UserActionEvent'- assert result.action == 'login'- assert result.user_id == 'user123'- assert result.event_id is not None- assert result.event_created_at is not None- assert result.event_started_at is None # Not started yet- assert result.event_completed_at is None # Not completed yet+ assert isinstance(queued, UserActionEvent)+ assert queued.event_type == 'UserActionEvent'+ assert queued.action == 'login'+ assert queued.user_id == 'user123'+ assert queued.event_id is not None+ assert queued.event_created_at is not None+ assert queued.event_started_at is None # Not started yet+ assert queued.event_completed_at is None # Not completed yet+ assert queued.event_status == 'pending'# Test result() pattern- processed = await result.result()+ processed = await queuedassert processed.event_started_at is not Noneassert processed.event_completed_at is not None- # Check that we have results from the default handler- assert len(processed.event_results) == 1- # Get the result from the default handler (by checking handler name)- default_handler_result = None- for event_result in processed.event_results.values():- if event_result.handler_name == '_default_log_handler':- default_handler_result = event_result.result- break- assert default_handler_result == 'logged'+ assert processed.event_status == 'completed'+ # Check that we have no results (no default handler anymore)+ assert len(processed.event_results) == 0# Check event historyassert len(eventbus.event_history) == 1@@ -222,7 +217,7 @@ class TestHandlerRegistration:# Emit event and waitstart = time.time()- event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1')).result()+ event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))duration = time.time() - start# Check handlers ran in parallel (should take ~0.1s, not 0.2s)@@ -307,7 +302,7 @@ class TestErrorHandling:eventbus.on('UserActionEvent', working_handler)# Emit and wait for result- event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1')).result()+ event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))# Verify error capture and isolationfailing_result = next((r for r in event.event_results.values() if r.handler_name == 'failing_handler'), None)@@ -333,13 +328,12 @@ class TestBatchOperations:# Enqueue batchemitted_events = [eventbus.dispatch(event) for event in events]- results = await asyncio.gather(*[event.result() for event in emitted_events])+ results = await asyncio.gather(*emitted_events)# Check all processedassert len(results) == 3for result in results:assert result.event_completed_at is not None- assert any(r.handler_name == '_default_log_handler' for r in result.event_results.values())class TestWriteAheadLog:@@ -363,7 +357,7 @@ class TestWriteAheadLog:# Check event state propertiescompleted = eventbus.events_completed- pending = eventbus.events_queued+ pending = eventbus.events_pendingprocessing = eventbus.events_startedassert len(completed) + len(pending) + len(processing) == len(log)assert len(completed) == 5 # All events should be completed@@ -390,7 +384,7 @@ class TestEventCompletion:completion_order.append('enqueue_done')# Wait for completion- await event.result()+ event = await eventcompletion_order.append('wait_done')# Check order@@ -434,7 +428,7 @@ class TestEdgeCases:event = SystemEventModel(event_name='complex', details=complex_data)- result = await eventbus.dispatch(event).result()+ result = await eventbus.dispatch(event)# Check data preservedassert result.details['nested']['list'][2]['inner'] == 'value'@@ -447,7 +441,7 @@ class TestEdgeCases:event = UserActionEvent(action=f'concurrent_{i}', user_id='u1')# Emit returns the event syncresultsonously, but we need to wait for completionemitted_event = eventbus.dispatch(event)- tasks.append(emitted_event.result())+ tasks.append(emitted_event)# Wait for all events to completeawait asyncio.gather(*tasks)@@ -553,8 +547,8 @@ class TestWALPersistence:for i in range(3):event = UserActionEvent(action=f'action_{i}', user_id=f'user_{i}')emitted_event = bus.dispatch(event)- result = await emitted_event.result()- events.append(result)+ completed_event = await emitted_event+ events.append(completed_event)# Wait for processingawait bus.wait_until_idle()@@ -573,9 +567,7 @@ class TestWALPersistence:assert data['user_id'] == f'user_{i}'assert data['event_type'] == 'UserActionEvent'assert isinstance(data['event_created_at'], str)- assert isinstance(data['event_completed_at'], str)datetime.fromisoformat(data['event_created_at'])- datetime.fromisoformat(data['event_completed_at'])finally:await bus.stop()@@ -589,15 +581,17 @@ class TestWALPersistence:# Create event busbus = EventBus(name='TestBus', wal_path=wal_path)- # Parent directory should be created- assert wal_path.parent.exists()try:# Emit an event- await bus.dispatch(UserActionEvent(action='test', user_id='u1')).result()+ event = bus.dispatch(UserActionEvent(action='test', user_id='u1'))+ await event# Wait for WAL persistence to completeawait bus.wait_until_idle()+ # Parent directory should be created after event is processed+ assert wal_path.parent.exists()+# Check file was createdassert wal_path.exists()finally:@@ -623,7 +617,7 @@ class TestWALPersistence:assert not wal_path.exists()# Wait for completion- await event.result()+ event = await eventawait bus.wait_until_idle()# Now file should exist with completed event@@ -632,7 +626,9 @@ class TestWALPersistence:assert len(lines) == 1data = json.loads(lines[0])assert data['event_type'] == 'UserActionEvent'- assert 'event_completed_at' in data+ # The WAL should have been written after the event completed+ assert data['action'] == 'test'+ assert data['user_id'] == 'u1'finally:await bus.stop()@@ -1013,7 +1009,7 @@ class TestEventResults:# Register a specific handlerasync def test_handler(event):- return 'test_result'+ return {'result': 'test_result'}eventbus.on('UserActionEvent', test_handler)@@ -1021,25 +1017,19 @@ class TestEventResults:assert isinstance(result, BaseEvent)# Wait for completion- await result.result()+ await result# Get results by handler ID- all_results = await result.event_results_by_handler_id()+ all_results = await result.event_results_flat_dict()assert isinstance(all_results, dict)- # Should contain both test_handler and default log handler results- assert len(all_results) == 2- assert 'test_result' in all_results.values()- assert 'logged' in all_results.values()+ # Should contain only test_handler result+ assert len(all_results) == 1+ assert all_results['result'] == 'test_result'- # Test with no specific handlers (only wildcard)+ # Test with no specific handlersresult_no_handlers = eventbus.dispatch(BaseEvent(event_type='NoHandlersEvent'))- await result_no_handlers.result()- # Should only have the default log handler- assert len(result_no_handlers.event_results) == 1- default_result = next(- (r for r in result_no_handlers.event_results.values() if r.handler_name == '_default_log_handler'), None- )- assert default_result is not None- assert default_result.result == 'logged'+ await result_no_handlers+ # Should have no handlers+ assert len(result_no_handlers.event_results) == 0async def test_event_results_indexing(self, eventbus):"""Test indexing by handler name and ID"""@@ -1062,15 +1052,12 @@ class TestEventResults:eventbus.on('TestEvent', handler3)# Test indexing- hr = eventbus.dispatch(BaseEvent(event_type='TestEvent'))-- # Wait for all handlers to complete- await hr.result()+ event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Get results by handler name- handler1_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler1'), None)- handler2_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler2'), None)- handler3_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler3'), None)+ handler1_result = next((r for r in event.event_results.values() if r.handler_name == 'handler1'), None)+ handler2_result = next((r for r in event.event_results.values() if r.handler_name == 'handler2'), None)+ handler3_result = next((r for r in event.event_results.values() if r.handler_name == 'handler3'), None)assert handler1_result is not None and handler1_result.result == 'first'assert handler2_result is not None and handler2_result.result == 'second'@@ -1089,24 +1076,21 @@ class TestEventResults:eventbus.on('TestEvent', early_handler)eventbus.on('TestEvent', late_handler)- result = eventbus.dispatch(BaseEvent(event_type='TestEvent'))- await result.result()+ result = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))- # Check both handlers ran (plus default logger)- assert len(result.event_results) == 3+ # Check both handlers ran+ assert len(result.event_results) == 2early_result = next((r for r in result.event_results.values() if r.handler_name == 'early_handler'), None)late_result = next((r for r in result.event_results.values() if r.handler_name == 'late_handler'), None)assert early_result is not None and early_result.result == 'early'assert late_result is not None and late_result.result == 'late'- # With empty handlers (only default logger remains)+ # With empty handlerseventbus.handlers['EmptyEvent'] = []results_empty = eventbus.dispatch(BaseEvent(event_type='EmptyEvent'))- await results_empty.result()- # Should only have the default wildcard handler- assert len(results_empty.event_results) == 1- default_result = next((r for r in results_empty.event_results.values() if r.handler_name == '_default_log_handler'), None)- assert default_result is not None+ await results_empty+ # Should have no handlers+ assert len(results_empty.event_results) == 0async def test_by_handler_name(self, eventbus):"""Test handler results with duplicate names"""@@ -1128,8 +1112,7 @@ class TestEventResults:eventbus.on('TestEvent', process_data2)eventbus.on('TestEvent', unique_handler)- event = eventbus.dispatch(BaseEvent(event_type='TestEvent'))- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Check results - with duplicate names, both handlers runprocess_results = [r for r in event.event_results.values() if r.handler_name == 'process_data']@@ -1156,15 +1139,14 @@ class TestEventResults:eventbus.on('TestEvent', handler1)eventbus.on('TestEvent', handler2)- event = eventbus.dispatch(BaseEvent(event_type='TestEvent'))- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Get results by handler ID using the method that existsresults = await event.event_results_by_handler_id()# All handlers present with unique IDs even with same name- # Should have 3 results: handler1, handler2, and default logger- assert len(results) >= 2+ # Should have 2 results: handler1, handler2+ assert len(results) == 2assert 'v1' in results.values()assert 'v2' in results.values()@@ -1180,8 +1162,7 @@ class TestEventResults:eventbus.on('GetConfig', config_base)eventbus.on('GetConfig', config_override)- event = eventbus.dispatch(BaseEvent(event_type='GetConfig'))- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='GetConfig'))merged = await event.event_results_flat_dict()# Later handlers override earlier ones@@ -1197,8 +1178,7 @@ class TestEventResults:return 'not a dict'eventbus.on('BadConfig', bad_handler)- event_bad = eventbus.dispatch(BaseEvent(event_type='BadConfig'))- await event_bad.result()+ event_bad = await eventbus.dispatch(BaseEvent(event_type='BadConfig'))# Non-dict results should be skipped, not raise errormerged_bad = await event_bad.event_results_flat_dict()@@ -1220,24 +1200,22 @@ class TestEventResults:eventbus.on('GetErrors', errors2)eventbus.on('GetErrors', errors3)- event = eventbus.dispatch(BaseEvent(event_type='GetErrors'))- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='GetErrors'))all_errors = await event.event_results_flat_list()# Check that all errors are collected (order may vary due to handler execution)- assert set(all_errors) == {'error1', 'error2', 'error3', 'error4', 'error5', 'logged'}+ assert set(all_errors) == {'error1', 'error2', 'error3', 'error4', 'error5'}# Test with non-list handlerasync def single_value(event):return 'single'eventbus.on('GetSingle', single_value)- event_single = eventbus.dispatch(BaseEvent(event_type='GetSingle'))- await event_single.result()+ event_single = await eventbus.dispatch(BaseEvent(event_type='GetSingle'))result = await event_single.event_results_flat_list()assert 'single' in result # Single values are appended- assert 'logged' in result+ assert len(result) == 1async def test_by_handler_name_access(self, eventbus):"""Test accessing results by handler name"""@@ -1251,8 +1229,7 @@ class TestEventResults:eventbus.on('TestEvent', handler_a)eventbus.on('TestEvent', handler_b)- event = eventbus.dispatch(BaseEvent(event_type='TestEvent'))- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Access results by handler namehandler_a_result = next((r for r in event.event_results.values() if r.handler_name == 'handler_a'), None)@@ -1268,10 +1245,7 @@ class TestEventResults:return 'my_result'eventbus.on('TestEvent', my_handler)- event = eventbus.dispatch(BaseEvent(event_type='TestEvent'))-- # Wait for handlers to complete- await event.result()+ event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Access result by handler namemy_handler_result = next((r for r in event.event_results.values() if r.handler_name == 'my_handler'), None)@@ -1324,7 +1298,7 @@ class TestEventBusForwarding:await bus3.wait_until_idle()# Wait for event completion- await event.result()+ event = await event# All handlers from all buses should be visiblebus1_result = next((r for r in event.event_results.values() if r.handler_name == 'bus1_handler'), None)@@ -1370,7 +1344,7 @@ class TestEventBusForwarding:# Wait for processingawait bus1.wait_until_idle()await bus2.wait_until_idle()- await event.result()+ event = await event# Check results from both busesmain_result = next((r for r in event.event_results.values() if r.handler_name == 'main_handler'), None)@@ -1449,7 +1423,7 @@ class TestComplexIntegration:await app_bus.wait_until_idle()await auth_bus.wait_until_idle()await data_bus.wait_until_idle()- await event.result()+ event = await event# Test that all handlers ran# Count handlers by name@@ -1468,7 +1442,7 @@ class TestComplexIntegration:# Test flat dict mergingdict_result = await event.event_results_flat_dict()# Should have merged all dict returns- assert 'app_valid' in dict_result or 'auth_valid' in dict_result or 'data_valid' in dict_result+ assert 'app_valid' in dict_result and 'auth_valid' in dict_result and 'data_valid' in dict_result# Test flat listlist_result = await event.event_results_flat_list()diff --git a/tests/ci/test_parent_event_tracking.py b/tests/ci/test_parent_event_tracking.pyindex 7fe1169e9..27608521f 100644--- a/tests/ci/test_parent_event_tracking.py+++ b/tests/ci/test_parent_event_tracking.py@@ -62,7 +62,7 @@ class TestParentEventTracking:await eventbus.wait_until_idle()# Verify parent processed- await parent_result.result()+ await parent_resultparent_handler_result = next((r for r in parent_result.event_results.values() if r.handler_name == 'parent_handler'), None)@@ -176,7 +176,8 @@ class TestParentEventTracking:async def parent_handler(event: ParentEvent) -> str:nonlocal captured_child# Create child with explicit event_parent_id- child = ChildEvent(data='explicit', event_parent_id='explicit_parent_id')+ explicit_parent_id = '01234567-89ab-cdef-0123-456789abcdef'+ child = ChildEvent(data='explicit', event_parent_id=explicit_parent_id)eventbus.dispatch(child)captured_child = childreturn 'dispatched'@@ -190,7 +191,7 @@ class TestParentEventTracking:# Explicit event_parent_id should be preservedassert captured_child is not None- assert captured_child.event_parent_id == 'explicit_parent_id'+ assert captured_child.event_parent_id == '01234567-89ab-cdef-0123-456789abcdef'assert captured_child.event_parent_id != parent.event_idasync def test_cross_eventbus_parent_tracking(self):