Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/crewai/src/crewai/flow/runtime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1763,7 +1763,12 @@ class StateWithId(FlowState, state_type): # type: ignore
return cast(T, {"id": str(uuid4())})

if isinstance(init_state, dict):
new_state = dict(init_state) # Copy to avoid mutations
# Isolate nested values. A shallow dict() copy leaves inner
# containers shared with the caller and with other Flow instances.
try:
new_state = copy.deepcopy(init_state)
except (TypeError, AttributeError):
new_state = dict(init_state)
if "id" not in new_state:
new_state["id"] = str(uuid4())
return cast(T, new_state)
Expand Down
18 changes: 18 additions & 0 deletions lib/crewai/tests/test_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1790,6 +1790,24 @@ def step_1(self):
flow.state.nested["key"] = "changed_after_copy"
assert copied_state.nested["key"] == "modified"

def test_flow_initial_dict_state_isolates_nested_values():
"""Each Flow gets an independent copy of nested dict initial state.
Regression test for issue #9383: dict(init_state) only copied the outer
dict, so two flows and the caller's original dict shared nested lists.
"""
settings = {"wallet": {"expenses": []}}
class DepartmentOrder(Flow):
@start()
def purchase(self):
self.state["wallet"]["expenses"].append(40)
marketing = DepartmentOrder(initial_state=settings)
engineering = DepartmentOrder(initial_state=settings)

marketing.state["wallet"]["expenses"].append(40)
assert marketing.state["wallet"]["expenses"] == [40]
assert engineering.state["wallet"]["expenses"] == []
assert settings["wallet"]["expenses"] == []
assert marketing.state["wallet"] is not engineering.state["wallet"]

def test_flow_copy_state_with_dict_state():
"""Test that _copy_state works with dict-based states."""
Expand Down
Loading