Repository navigation
Description
Description
An application runs one flow class many times in one process, as a service handles one request after another. Each run takes automatic checkpoints with on_events=["method_execution_finished"], pauses for human feedback (@human_feedback with a provider that raises HumanFeedbackPending), and is continued with Flow.from_pending(...).resume(...).
Once one run has been continued with from_pending, the checkpoints of every later run also hold that earlier flow, and hold it first. When a later run fails and is restored with Flow.from_checkpoint, CrewAI returns the earlier flow, with the earlier run's state and progress. The restored run then continues the earlier run's work: the failed run's own human-feedback step never pauses, and it returns the earlier run's result. No error is raised.
Steps to Reproduce
- Define
add -> check -> ask (@human_feedback, pausing) -> record, whererecordwrites the feedback to the state. - Run A: kick off, answer the pause through
from_pending(...).resume("-3"). It returnsx = -3. - Run B, with its own checkpoint location:
checkfails once. Restore from the latest checkpoint B wrote withfrom_checkpointand kick off again; answer its pause with"68".
Expected behavior
The restored flow is run B's, with B's state. B pauses for its own feedback and returns x = 68, as it does when run A did not happen before it (python repro.py only-b):
- run B's latest checkpoint holds the flows of runs
['B']; - restored the flow of run B;
- run B returns
x = 68; a human was asked to review runs['B'].
Screenshots/Code snippets
import json
import sys
import tempfile
from importlib.metadata import version
from pathlib import Path
from crewai.flow import HumanFeedbackPending, HumanFeedbackProvider, human_feedback
from crewai.flow.flow import Flow, listen, start
from crewai.flow.persistence import SQLiteFlowPersistence
from crewai.state.checkpoint_config import CheckpointConfig
work = Path(tempfile.mkdtemp())
persistence = SQLiteFlowPersistence(str(work / "flows.db"))
answers = {"A": -3, "B": 68} # the human's answer for each run
failures = 0 # `check` fails this many more times
asked = [] # the runs a human was asked to review
class AskHuman(HumanFeedbackProvider):
def request_feedback(self, context, flow):
raise HumanFeedbackPending(context=context) # pause until the application answers
class Pipeline(Flow):
@start()
def add(self):
self.state["x"] += 1
@listen(add)
def check(self):
global failures
if failures:
failures -= 1
raise RuntimeError("check failed")
@listen(check)
@human_feedback(message="Review x", provider=AskHuman())
def ask(self):
return self.state["x"]
@listen(ask)
def record(self, result):
self.state["x"] = int(result.feedback)
def run(name, x):
"""Kick a flow off; answer a pause with from_pending, and resume a failure from the latest checkpoint."""
location = work / name
checkpoint = CheckpointConfig(location=str(location), on_events=["method_execution_finished"])
flow = Pipeline(persistence=persistence, checkpoint=checkpoint)
step = lambda: flow.kickoff(inputs={"run": name, "x": x})
while True:
try:
result = step()
except RuntimeError as exc:
latest = max(location.rglob("*.json"), key=lambda path: path.stat().st_mtime_ns)
flows = [e["checkpoint_state"] for e in json.loads(latest.read_text())["entities"] if e["entity_type"] == "flow"]
print(f"run {name} failed ({exc}); its latest checkpoint holds the flows of runs", [f["run"] for f in flows])
flow = Pipeline.from_checkpoint(CheckpointConfig(restore_from=str(latest)))
flow.persistence, flow.checkpoint = persistence, checkpoint
print(f" restored the flow of run {flow.state['run']}")
step = lambda: flow.kickoff()
continue
if not isinstance(result, HumanFeedbackPending):
return flow.state["x"]
asked.append(flow.state["run"])
flow = Pipeline.from_pending(result.context.flow_id, persistence, checkpoint=checkpoint)
step = lambda: flow.resume(str(answers[flow.state["run"]]))
if sys.argv[1:] != ["only-b"]: # `python repro.py only-b` skips run A
print("run A returns x =", run("A", 1))
failures = 1
print("run B returns x =", run("B", 2))
print(f"crewai {version('crewai')}: a human was asked to review runs {asked}")Operating System
Ubuntu 22.04
Python Version
3.12
crewAI Version
1.15.30
crewAI Tools Version
not installed
Virtual Environment
Venv
Evidence
run A returns x = -3
run B failed (check failed); its latest checkpoint holds the flows of runs ['A', 'B']
restored the flow of run A
run B returns x = -2
crewai 1.15.30: a human was asked to review runs ['A']
Run B adds 1 to run A's final x (-3) instead of its own input, never asks for its own review, and returns -2.
Without run A (python repro.py only-b):
run B failed (check failed); its latest checkpoint holds the flows of runs ['B']
restored the flow of run B
run B returns x = 68
crewai 1.15.30: a human was asked to review runs ['B']
1.15.28 and main (83b5288) print the same.
Possible Solution
Scope the runtime state that a checkpoint serializes to the flow that takes it, so that a flow continued with from_pending is not part of the checkpoints of later, unrelated runs; or have from_checkpoint restore the flow that wrote the checkpoint rather than the first flow it finds.
Additional context
Flow.from_checkpoint (crewai/flow/runtime/__init__.py) returns the first Flow entity in state.root. The checkpoint run B writes lists two flow entities, run A's (completed, x = -3) before run B's, so run A's is returned. A run that was not continued with from_pending does not appear in later checkpoints: without the pause, run B's checkpoint holds only run B and the restore is correct.
This is related to two earlier reports, but has a different cause:
- [BUG] A flow resumed with from_pending forgets the methods completed before the pause, so a later checkpoint restore runs them again #8441: a flow continued with
from_pendingforgets the methods it completed before the pause, so restoring that same flow reruns them. Its checkpoints hold one flow. Here the restored flow is another run's; with the fix proposed for [BUG] A flow resumed with from_pending forgets the methods completed before the pause, so a later checkpoint restore runs them again #8441 (fix(flow): preserve completed methods and execution history across from_pending #8461) applied, the checkpoint still holds['A', 'B']and run A is still restored. - [BUG] A flow resumed from a checkpoint writes checkpoints of a blank flow, so a second resume starts over #8438: a flow restored with
from_checkpointwrites checkpoints of a blank flow. Here the extra entity is another run that went throughfrom_pending. With the fix proposed for [BUG] A flow resumed from a checkpoint writes checkpoints of a blank flow, so a second resume starts over #8438 (fix(flow): make resumed flows checkpoint the instance that runs #8448), which selects the flow by name and rejects a checkpoint holding several flows of one class, run B cannot be restored at all (ValueError: Checkpoint contains multiple flows named 'Pipeline').
Activity