crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] aemit() bypasses the dependency-aware dispatch path: sync dependencies never run and async depends_on chains execute out of order

Open yuee3 opened this issue 1 month ago • 0 comments

Description

CrewAIEventsBus has three dispatch entry points: emit(), replay(), and aemit(). Two of them check _handler_dependencies and route to the dependency-aware executor _emit_with_dependencies(), which groups handlers into execution levels (sync handlers via the thread pool, async handlers concurrently within a level, levels strictly in order).

aemit() never consults _handler_dependencies. It reads only _async_handlers and calls _acall_handlers() directly, which runs all async handlers concurrently via a single asyncio.gather(). Once an event type has dependencies registered (via @crewai_event_bus.on(EventType, Depends(...))), calling aemit() therefore:

  1. never executes the sync handlers that async handlers depend on (e.g. a sync setup), while the dependent async handlers still run;
  2. executes async handlers concurrently, ignoring depends_on ordering — a dependent handler can finish before the handler it depends on.

For reference, emit() (lib/crewai/src/crewai/events/event_bus.py, has_dependencies check at line 608, routing at 620-626) and replay() (lines 693 and 706-712) both perform has_dependencies = event_type in self._handler_dependencies and dispatch to _emit_with_dependencies() — which explicitly supports async handlers level by level (lines ~505-522). aemit() (lines 771-786) is the only dispatch entry that skips this path.

Steps to Reproduce

  1. Register a sync setup handler, an async first handler with Depends(setup), and an async second handler with Depends(first) for the same event type.
  2. Call await crewai_event_bus.aemit(source, event) from async code.
  3. Record the handler execution order.

Minimal repro script:

import asyncio

from crewai.events import Depends, crewai_event_bus
from crewai.events.base_events import BaseEvent


class ReproEvent(BaseEvent):
    value: int = 0
    type: str = "repro_event"


async def main() -> None:
    order: list[str] = []

    with crewai_event_bus.scoped_handlers():

        @crewai_event_bus.on(ReproEvent)
        def setup(source, event: ReproEvent):
            order.append("setup")

        @crewai_event_bus.on(ReproEvent, Depends(setup))
        async def first(source, event: ReproEvent):
            await asyncio.sleep(0.05)
            order.append("first")

        @crewai_event_bus.on(ReproEvent, Depends(first))
        async def second(source, event: ReproEvent):
            order.append("second")

        await crewai_event_bus.aemit("repro", ReproEvent(value=1))

    print("execution order:", order)  # expected ["setup", "first", "second"]


asyncio.run(main())

Expected behavior

aemit() should honor registered dependencies the same way emit() and replay() do: run the sync dependency handlers and execute async handlers in dependency levels, i.e.

["setup", "first", "second"]

Screenshots/Code snippets

Current aemit() on main (lib/crewai/src/crewai/events/event_bus.py, lines 771-786):

    async def aemit(self, source: Any, event: BaseEvent) -> None:
        """Asynchronously emit an event to registered async handlers.

        Only processes async handlers. Use in async contexts.
        ...
        """
        self._prepare_event(source, event)

        event_type = type(event)

        with self._rwlock.r_locked():
            if self._shutting_down:
                self._console.print(
                    "[CrewAIEventsBus] Warning: Attempted to emit event during shutdown. Ignoring."
                )
                return
            async_handlers = self._async_handlers.get(event_type, frozenset())

        if async_handlers:
            await self._acall_handlers(
                source, event, async_handlers, self._runtime_state
            )

Note there is no _handler_dependencies lookup and no routing to _emit_with_dependencies().

Operating System

Windows 11

Python Version

3.12

crewAI Version

1.15.27 (main @ 5bb6f23)

crewAI Tools Version

N/A (not used in the repro)

Virtual Environment

Venv

Evidence

Output of the repro script above on current main:

execution order: ['second', 'first']
expected        : ['setup', 'first', 'second']

Two symptoms visible:

  • setup (sync, the dependency root) is missing entirely — it was never executed;
  • second ran before first — the async depends_on chain was flattened into a single concurrent asyncio.gather().

The asyncio.sleep(0.05) in first makes the inversion deterministic.

Possible Solution

In aemit(), inside the existing r_locked() block, also compute has_dependencies = event_type in self._handler_dependencies (mirroring emit() and replay()); when true, ensure the executor is initialized and await self._emit_with_dependencies(source, event, self._runtime_state). Events without registered dependencies keep exactly today's behavior (async handlers only, concurrent).

Additional context

  • lib/crewai/tests/events/test_depends.py only exercises emit(); aemit() combined with depends_on has no coverage (the existing test_aemit_ignores_dependencies registers no dependencies).
  • I found this while reviewing the dispatch paths; it is independent of my open PR #8716 (which only adjusts future tracking inside emit() — no shared code lines).
  • I have a minimal fix plus regression tests ready and can open a PR referencing this issue.

yuee3 avatar Nov 01 '26 13:11 yuee3