Skip to content

[BUG] A flow kicked off with kickoff_async under asyncio.run, or with stream=True, stays in the runtime state, so a later flow's checkpoints restore the earlier flow #8960

Open

Description

Description

A service runs one flow class once per request, each run with its own checkpoint location. When a run fails, it is restored from its latest checkpoint with Flow.from_checkpoint and kicked off again.

If the runs are kicked off with flow.kickoff(), this works. If they are kicked off with asyncio.run(flow.kickoff_async(...)), as a synchronous service runs an async flow, or with stream=True, every checkpoint of the second run also holds the first flow, and holds it first. Restoring the second run then returns the first flow, with the first run's state and completed methods:

  • The failed run's remaining work never runs: its charge is never retried.
  • The restored flow reports the other order's state as the result.
  • No error or warning is raised.

Every later run carries all earlier flows of the process in its checkpoints, so every later resume restores the wrong flow.

Steps to Reproduce

  1. Define reserve -> charge, where charge fails once for order 2.
  2. Kick off order 1, then order 2, each as OrderFlow(checkpoint=CheckpointConfig(location=<own dir>, on_events=["method_execution_finished"])), with asyncio.run(flow.kickoff_async(...)) (or with stream=True, reading the stream to its end).
  3. Order 2 fails. Restore its latest checkpoint with OrderFlow.from_checkpoint(CheckpointConfig(restore_from=...)) and call kickoff().

Expected behavior

The restored flow is order 2: charge runs again and the state is {'order': 2, 'reserved': True, 'charged': True}, as it is with flow.kickoff().

Screenshots/Code snippets

import asyncio
import glob
import os
import sys
import tempfile
from importlib.metadata import version

from crewai import CheckpointConfig
from crewai.flow.flow import Flow, listen, start

failures = {2}  # Order 2's charge fails once.


class OrderFlow(Flow):
    @start()
    def reserve(self):
        self.state["reserved"] = True

    @listen(reserve)
    def charge(self):
        order = self.state["order"]
        if order in failures:
            failures.discard(order)
            raise RuntimeError(f"charge of order {order} failed")
        self.state["charged"] = True


def kickoff(flow, **kwargs):
    if sys.argv[1] == "stream":  # The same with the flow's stream=True, read to its end.
        flow.stream = True
        session = flow.kickoff(**kwargs)
        for _ in session:
            pass
        return session.result
    if sys.argv[1] == "async":  # One event loop per request, as a synchronous service runs an async flow.
        return asyncio.run(flow.kickoff_async(**kwargs))
    return flow.kickoff(**kwargs)


for order in (1, 2):  # One order after the other, each with its own checkpoints.
    location = tempfile.mkdtemp()
    flow = OrderFlow(checkpoint=CheckpointConfig(location=location, on_events=["method_execution_finished"]))
    try:
        kickoff(flow, inputs={"order": order})
        print(f"order {order}: done")
    except RuntimeError as exc:
        print(f"order {order}: {exc}; resuming from its latest checkpoint")
        latest = max(glob.glob(f"{location}/**/*.json", recursive=True), key=os.path.getmtime)
        restored = OrderFlow.from_checkpoint(CheckpointConfig(restore_from=latest))
        restored.kickoff()
        print(f"order {order} resumed: state {({k: v for k, v in restored.state.items() if k != 'id'})}")

print("crewai", version("crewai"))

Run it as python repro.py async, python repro.py stream and, for comparison, python repro.py kickoff.

Operating System

Ubuntu 22.04

Python Version

3.12

crewAI Version

1.15.34

crewAI Tools Version

not installed

Virtual Environment

Venv

Evidence

python repro.py async and python repro.py stream:

order 1: done
order 2: charge of order 2 failed; resuming from its latest checkpoint
order 2 resumed: state {'order': 1, 'reserved': True, 'charged': True}
crewai 1.15.34

python repro.py kickoff:

order 1: done
order 2: charge of order 2 failed; resuming from its latest checkpoint
order 2 resumed: state {'order': 2, 'reserved': True, 'charged': True}
crewai 1.15.34

The checkpoint order 2 wrote holds two flows, order 1's (complete) first and order 2's second. The same happens on 1.15.28 and 1.15.33, on macOS and on Ubuntu 22.04, and with astream.

Possible Solution

A flow registers itself in the runtime state when it emits its first event (_register_source → register_entity), and register_entity creates the RuntimeState in the context the flow was constructed in if there is none. A kickoff only ends that state when it exits its outermost runtime scope (_exit_runtime_scope sets _runtime_state_var to None), and it does so in the context the kickoff runs in:

  • flow.kickoff() runs in the caller's context, so the state ends with the run, and the next flow starts a new one.
  • asyncio.run(flow.kickoff_async()) runs in the event loop's copy of the context, and stream_events and astream run the kickoff on a thread under contextvars.copy_context() (create_frame_generator). The scope ends in that copy only. The caller's context keeps the RuntimeState holding the finished flow, and the next flow constructed there is appended to it, so its checkpoints serialize both.

Ending the runtime state in the context it was created in fixes the stream case. With stream_events iterating its frames inside a runtime scope of the caller's context:

def _scoped_frames(frames):
    scope = crewai_event_bus._enter_runtime_scope()
    try:
        yield from frames
    finally:
        crewai_event_bus._exit_runtime_scope(scope)

# in stream_events
sync_iterator=_scoped_frames(create_frame_generator(state, run_flow, output_holder))

python repro.py stream restores order 2 with {'order': 2, 'reserved': True, 'charged': True}. The asyncio.run case needs the top-level kickoff to start from a runtime state of its own that holds only the flow being run, instead of reusing one that the constructing context accumulated.

Additional context

This has the same consequence as #8688, where a flow continued with from_pending stays in the runtime state, but it is a different path: no flow here pauses or is continued with from_pending, and neither #8694 nor #8693 changes the result. With #8448, the restore raises ValueError: Checkpoint contains multiple flows named 'OrderFlow'; flow names must be unique for restore instead, so the failed run cannot be resumed at all.

Activity

  1. added
    bug
    on Nov 3, 2026
  2. HhH666-ux commented on Nov 6, 2026

    @HhH666-ux
    Contributor

    #8964 fixes this. A top-level kickoff now starts from its own runtime state: kickoff() and kickoff_async() clear the state inherited from the caller's context, so a kickoff that ran under asyncio.run or a streamed thread no longer leaves a finished flow registered for the next run to serialize into its checkpoints.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions