Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

fix(flow): emit the flow lifecycle on a suppressed resume (#7071)

João Moura8e6c23430f8d
diff --git a/lib/crewai/src/crewai/flow/runtime/__init__.py b/lib/crewai/src/crewai/flow/runtime/__init__.py
index eefbd75b6..0e95d971d 100644
--- a/lib/crewai/src/crewai/flow/runtime/__init__.py
+++ b/lib/crewai/src/crewai/flow/runtime/__init__.py
@@ -1374,7 +1374,7 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
except Exception as e:
if not hook_state["end_dispatched"]:
self._dispatch_execution_end_failure(e)
- await self._emit_flow_failed(e, respect_suppression=True)
+ await self._emit_flow_failed(e)
raise
finally:
# Match kickoff_async: drain pending handlers so the resumed
@@ -1393,20 +1393,30 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
reset_emission_counter()
reset_last_event_id()
- if not self.suppress_flow_events:
- future = crewai_event_bus.emit(
- self,
- FlowStartedEvent(
- type="flow_started",
- flow_name=self._definition.name,
- inputs=None,
- ),
- )
- if future and isinstance(future, Future):
- try:
- await asyncio.wrap_future(future)
- except Exception:
- logger.warning("FlowStartedEvent handler failed", exc_info=True)
+ # Emitted unconditionally, matching both the kickoff path and the
+ # FlowFinishedEvent below. This used to sit behind suppress_flow_events,
+ # which produced an unpaired finish: the finish emit is not gated, so a
+ # resumed flow reported finishing without ever having started, breaking
+ # every started/finished pairing and duration built on it.
+ #
+ # suppress_flow_events is not the right gate for emission in any case. It
+ # asks for console quiet - see _flow_origin in events/event_listener.py,
+ # which says so and notes it "can legitimately be set on a caller's own
+ # flow" - and the listener already honours it where it prints. Suppressing
+ # the event instead removed the resumed leg from telemetry entirely.
+ future = crewai_event_bus.emit(
+ self,
+ FlowStartedEvent(
+ type="flow_started",
+ flow_name=self._definition.name,
+ inputs=None,
+ ),
+ )
+ if future and isinstance(future, Future):
+ try:
+ await asyncio.wrap_future(future)
+ except Exception:
+ logger.warning("FlowStartedEvent handler failed", exc_info=True)
get_env_context()
@@ -1581,10 +1591,11 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
)
self._event_futures.clear()
- if (
- not self.suppress_flow_events
- and not self._should_defer_trace_finalization()
- ):
+ # Not gated on suppress_flow_events: that asks for console quiet, and the
+ # started event above is ungated, so gating here would emit a start with no
+ # terminal event. The defer check stays - it is a real reason to withhold the
+ # finish, because finalize_session_traces() emits it later instead.
+ if not self._should_defer_trace_finalization():
# Background memory saves must finish (and emit their
# completed/failed events) before flow-finished triggers
# listener teardown/finalization; the flush then waits for those
@@ -2589,9 +2600,7 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
get_env_context()
return flow_scope_open
- async def _emit_flow_failed(
- self, error: Exception, *, respect_suppression: bool = False
- ) -> None:
+ async def _emit_flow_failed(self, error: BaseException) -> None:
"""Emit ``FlowFailedEvent`` and close out the trace batch for a failed run.
Mirrors the terminal block of the success path: drain pending event
@@ -2601,15 +2610,9 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
Args:
error: The exception that ended the execution.
- respect_suppression: Skip the emission for suppressed flows. Only
- the resume path gates its lifecycle events on
- ``suppress_flow_events``; ``kickoff_async`` emits them either
- way and lets listeners filter.
"""
if self._should_defer_trace_finalization():
return
- if respect_suppression and self.suppress_flow_events:
- return
try:
if self._event_futures:
diff --git a/lib/crewai/tests/test_async_human_feedback.py b/lib/crewai/tests/test_async_human_feedback.py
index 74b17f6b2..174d2cc26 100644
--- a/lib/crewai/tests/test_async_human_feedback.py
+++ b/lib/crewai/tests/test_async_human_feedback.py
@@ -489,6 +489,81 @@ class TestFlowResumeWithFeedback:
assert flow._is_execution_resuming is True
assert flow.state.counter == 42
+ def test_suppressed_resume_emits_a_matched_lifecycle_pair(self) -> None:
+ """A suppressed resume emits exactly one start and one finish.
+
+ Both lifecycle events used to be gated on ``suppress_flow_events`` here,
+ while the kickoff path emits them either way -- so a suppressed resume was
+ invisible in flow telemetry. Ungating only the start would have been worse:
+ a start with no terminal event breaks pairing in the other direction.
+
+ The flag is not a gate for emission. It asks for console quiet -- see
+ ``_flow_origin`` in ``events/event_listener.py``, which says so and notes it
+ "can legitimately be set on a caller's own flow" -- and the listener already
+ honours it wherever it prints.
+
+ Counts are asserted exactly, and the resume is a real one that runs to
+ completion, so neither an unpaired event nor a swallowed failure can pass.
+ """
+ from crewai.events.event_bus import crewai_event_bus
+ from crewai.events.types.flow_events import (
+ FlowFinishedEvent,
+ FlowStartedEvent,
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ persistence = SQLiteFlowPersistence(os.path.join(tmpdir, "flows.db"))
+
+ class TestFlow(Flow):
+ suppress_flow_events = True
+
+ @start()
+ @human_feedback(message="Review this:")
+ def generate(self):
+ return "generated content"
+
+ @listen(generate)
+ def process(self, feedback_result):
+ return f"Processed: {feedback_result.feedback}"
+
+ context = PendingFeedbackContext(
+ flow_id="suppressed-resume-1",
+ flow_class="test.TestFlow",
+ method_name="generate",
+ method_output="generated content",
+ message="Review this:",
+ )
+ persistence.save_pending_feedback(
+ flow_uuid="suppressed-resume-1",
+ context=context,
+ state_data={"id": "suppressed-resume-1"},
+ )
+
+ flow = TestFlow.from_pending("suppressed-resume-1", persistence)
+
+ seen: list[str] = []
+ original_emit = crewai_event_bus.emit
+
+ def capture_emit(source, event):
+ if isinstance(event, FlowStartedEvent):
+ seen.append("started")
+ elif isinstance(event, FlowFinishedEvent):
+ seen.append("finished")
+ return original_emit(source, event)
+
+ with patch.object(crewai_event_bus, "emit", side_effect=capture_emit):
+ result = flow.resume("looks good!")
+
+ assert result is not None
+ assert seen.count("started") == 1, (
+ f"expected exactly one flow_started on a suppressed resume, got {seen}"
+ )
+ assert seen.count("finished") == 1, (
+ f"expected exactly one flow_finished to pair with it, got {seen} -- "
+ f"an unpaired event breaks started/finished pairing and every "
+ f"duration built on it"
+ )
+
def test_resume_without_pending_raises_error(self) -> None:
"""Test that resume raises error without pending context."""