From 6c8ac23c69cc88dba95adf42e59f85a401800a07 Mon Sep 17 00:00:00 2001 From: hanyuanlu Date: Tue, 17 Nov 2026 11:27:42 +0800 Subject: [PATCH] fix(flow): isolate nested dictionary initial state --- lib/crewai/src/crewai/flow/runtime/__init__.py | 7 ++++++- lib/crewai/tests/test_flow.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/crewai/src/crewai/flow/runtime/__init__.py b/lib/crewai/src/crewai/flow/runtime/__init__.py index 3455a8b41c..3757ecb86c 100644 --- a/lib/crewai/src/crewai/flow/runtime/__init__.py +++ b/lib/crewai/src/crewai/flow/runtime/__init__.py @@ -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) diff --git a/lib/crewai/tests/test_flow.py b/lib/crewai/tests/test_flow.py index eb9094fcd7..956ff1b334 100644 --- a/lib/crewai/tests/test_flow.py +++ b/lib/crewai/tests/test_flow.py @@ -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."""