Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(execution): make graph apply transactional
JPPhotofec5949adbfc
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 5ad87d3015..af295c863f 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -4302,6 +4302,52 @@ class GraphExecutionState(BaseModel):)return owner_id in {execution_ref.reference_id, execution_ref.exec_node_id}+ def _validate_execution_frame(+ self, frame: Any, execution_ref: ExecutionReference, owner_name: str = "Execution effect"+ ) -> None:+ if frame is None:+ return+ if isinstance(frame, str):+ if frame not in ("", execution_ref.frame.frame_id):+ raise ValueError(f"{owner_name} belongs to another execution frame")+ return+ if isinstance(frame, (tuple, list)):+ if tuple(frame) != execution_ref.frame.iteration_path:+ raise ValueError(f"{owner_name} belongs to another execution frame")+ return++ frame_id = self._value_from_object(frame, "frame_id", "id")+ if frame_id not in (None, "", execution_ref.frame.frame_id):+ raise ValueError(f"{owner_name} belongs to another execution frame")+ frame_state_id = self._value_from_object(frame, "state_id", "session_id")+ if frame_state_id not in (None, "", execution_ref.frame.state_id):+ raise ValueError(f"{owner_name} belongs to another graph execution state")+ frame_path = self._value_from_object(frame, "iteration_path", "frame_path")+ if frame_path is not None and tuple(frame_path) != execution_ref.frame.iteration_path:+ raise ValueError(f"{owner_name} belongs to another execution frame")+ frame_depth = self._value_from_object(frame, "workflow_call_depth", "call_depth")+ if frame_depth not in (None, execution_ref.frame.workflow_call_depth):+ raise ValueError(f"{owner_name} belongs to another workflow-call depth")++ def _validate_execution_token(self, token: Any, execution_ref: ExecutionReference) -> None:+ token_reference_id = self._value_from_object(token, "reference_id", "execution_ref_id")+ if token_reference_id not in (None, "", execution_ref.reference_id):+ raise ValueError("Execution token belongs to another execution reference")+ token_state_id = self._value_from_object(token, "state_id", "session_id")+ if token_state_id not in (None, "", execution_ref.state_id):+ raise ValueError("Execution token belongs to another graph execution state")++ self._validate_execution_frame(self._value_from_object(token, "frame"), execution_ref, "Execution token")+ token_frame_id = self._value_from_object(token, "frame_id")+ if token_frame_id not in (None, "", execution_ref.frame.frame_id):+ raise ValueError("Execution token belongs to another execution frame")+ token_path = self._value_from_object(token, "iteration_path", "frame_path")+ if token_path is not None and tuple(token_path) != execution_ref.frame.iteration_path:+ raise ValueError("Execution token belongs to another execution frame")+ token_depth = self._value_from_object(token, "workflow_call_depth", "call_depth")+ if token_depth not in (None, execution_ref.frame.workflow_call_depth):+ raise ValueError("Execution token belongs to another workflow-call depth")+def _validate_execution_ref(self, execution_ref: ExecutionReference | str | Any) -> ExecutionReference:ref = self._coerce_execution_ref(execution_ref)expected = self._expected_execution_ref(ref.exec_node_id)@@ -4370,6 +4416,15 @@ class GraphExecutionState(BaseModel):output_fields = type(node).get_output_annotation().model_fieldsfor effect in effects:effect_kind = self._value_from_object(effect, "kind", "effect_type", "type")+ token = self._value_from_object(effect, "token")+ if effect_kind == "close_stream":+ token_kind = self._value_from_object(token, "token_kind")+ token_port = self._value_from_object(token, "field", "port", "output", "output_name")+ if token is None or token_port in (None, LOOP_LINKAGE_FIELD):+ raise ValueError("Close-stream effect requires a data output token")+ if token_kind != "stream_end":+ raise ValueError("Close-stream effect requires a stream_end token")+owner = self._value_from_object(effect,"execution_ref",@@ -4386,28 +4441,17 @@ class GraphExecutionState(BaseModel):owner = self._value_from_object(effect, "target", "source", "token")if owner is None or not self._same_execution_owner(owner, execution_ref):raise ValueError("Execution effect is not owned by execution reference")- if effect_kind is not None and effect_kind != "emit":+ if effect_kind is not None and effect_kind not in {"emit", "close_stream"}:raise ValueError(f"Unsupported execution effect kind: {effect_kind}")effect_state_id = self._value_from_object(effect, "state_id", "session_id")if effect_state_id is not None and effect_state_id != execution_ref.state_id:raise ValueError("Execution effect belongs to another graph execution state")- effect_frame = self._value_from_object(effect, "frame")- if effect_frame is not None:- frame_id = self._value_from_object(effect_frame, "frame_id", "id")- if frame_id not in (None, "", execution_ref.frame.frame_id):- raise ValueError("Execution effect belongs to another execution frame")- frame_state_id = self._value_from_object(effect_frame, "state_id", "session_id")- if frame_state_id not in (None, "", execution_ref.frame.state_id):- raise ValueError("Execution effect belongs to another graph execution state")- frame_path = self._value_from_object(effect_frame, "iteration_path", "frame_path")- if frame_path is not None and tuple(frame_path) != execution_ref.frame.iteration_path:- raise ValueError("Execution effect belongs to another execution frame")- frame_depth = self._value_from_object(effect_frame, "workflow_call_depth", "call_depth")- if frame_depth not in (None, execution_ref.frame.workflow_call_depth):- raise ValueError("Execution effect belongs to another workflow-call depth")+ self._validate_execution_frame(self._value_from_object(effect, "frame"), execution_ref)source_ref = self._value_from_object(effect, "source", "target", "token")+ if token is not None:+ self._validate_execution_token(token, execution_ref)destination_ref = self._value_from_object(effect, "destination")source_port = self._value_from_object(effect, "source_port", "output_port", "source_field", "port")if source_port is None:@@ -4480,7 +4524,8 @@ class GraphExecutionState(BaseModel):value=copydeep(getattr(output, port)),)for effect in effects:- if self._value_from_object(effect, "kind", "effect_type", "type") != "emit":+ effect_kind = self._value_from_object(effect, "kind", "effect_type", "type")+ if effect_kind not in {"emit", "close_stream"}:continuetoken = self._value_from_object(effect, "token")port = self._value_from_object(token, "field", "port", "output", "output_name")@@ -4494,7 +4539,13 @@ class GraphExecutionState(BaseModel):token_value = self._value_from_object(token, "value")token_kind = self._value_from_object(token, "token_kind") or "data"sequence = self._value_from_object(token, "sequence")- token_id_base = f"{execution_ref.reference_id}:{port}:{sequence if sequence is not None else 'effect'}"+ if effect_kind == "close_stream":+ token_id_base = (+ f"{execution_ref.reference_id}:{port}:stream_end:"+ f"{sequence if sequence is not None else 'effect'}"+ )+ else:+ token_id_base = f"{execution_ref.reference_id}:{port}:{sequence if sequence is not None else 'effect'}"token_id = token_id_baseduplicate_index = 1while token_id in tokens:@@ -4507,11 +4558,61 @@ class GraphExecutionState(BaseModel):port=port,frame=execution_ref.frame,value=copydeep(token_value),- token_kind=token_kind,+ token_kind="stream_end" if effect_kind == "close_stream" else token_kind,sequence=sequence,)return tokens+ def _snapshot_apply_state(self) -> dict[str, dict[str, Any]]:+ public_fields = (+ "execution_graph",+ "executed",+ "executed_history",+ "results",+ "prepared_source_mapping",+ "source_prepared_mapping",+ "finalized_loop_contexts",+ "prepared_iteration_paths",+ "execution_refs",+ "execution_tokens",+ "execution_effects",+ "indegree",+ )+ private_fields = (+ "_ready_queues",+ "_ready_node_ids",+ "_active_class",+ "_if_branch_exclusive_sources",+ "_resolved_if_exec_branches",+ "_prepared_exec_metadata",+ "_for_parent_iteration_paths_cache",+ "_all_for_contexts_finalized_cache",+ "_prepared_for_index",+ "_final_prepared_for_index",+ "_prepared_for_index_by_exec",+ "_completed_source_ids_cache",+ )+ return {+ "public": {name: copy.deepcopy(getattr(self, name)) for name in public_fields},+ "private": {name: copy.deepcopy(getattr(self, name)) for name in private_fields},+ }++ def _restore_apply_state(self, snapshot: dict[str, dict[str, Any]]) -> None:+ for field_name, value in snapshot["public"].items():+ object.__setattr__(self, field_name, value)+ for field_name, value in snapshot["private"].items():+ object.__setattr__(self, field_name, value)++ # Helpers and derived graph indexes must not retain references to the failed transaction.+ object.__setattr__(self, "_prepared_exec_registry", None)+ object.__setattr__(self, "_if_branch_scheduler", None)+ object.__setattr__(self, "_execution_materializer", None)+ object.__setattr__(self, "_execution_scheduler", None)+ object.__setattr__(self, "_execution_runtime", None)+ object.__setattr__(self, "_source_graph_flat", None)+ object.__setattr__(self, "_execution_graph_flat", None)+ object.__setattr__(self, "_for_source_by_return_id", None)+def apply(self,execution_ref: ExecutionReference | str | Any,@@ -4523,6 +4624,8 @@ class GraphExecutionState(BaseModel):"""Apply output/effects through current scheduler while retaining old ``complete()`` behavior."""ref = self._validate_execution_ref(execution_ref)+ if ref.exec_node_id in self.executed or ref.reference_id in self.execution_effects:+ raise ValueError(f"Execution reference {ref.reference_id} has already been applied")result_effects = self._value_from_object(output, "effects", "effect_batch")result_output = self._value_from_object(output, "output", "invocation_output", "result")if result_output is not None:@@ -4539,13 +4642,19 @@ class GraphExecutionState(BaseModel):tokens = self._build_execution_tokens(ref, output_value, effect_values)persisted_effects = copydeep(effect_values)- # All validation above is side-effect free. Preserve complete() as the scheduler compatibility boundary.- finalized_outputs = self.complete(ref.exec_node_id, output_value)- ref.effect_count = effect_count if effect_count is not None else ref.effect_count- self.execution_refs[ref.exec_node_id] = ref- self.execution_tokens.update(tokens)- self.execution_effects[ref.reference_id] = persisted_effects- return finalized_outputs+ # All validation above is side-effect free. Preserve complete() as the scheduler compatibility boundary,+ # but make the scheduler transition and ledger update one atomic operation.+ state_snapshot = self._snapshot_apply_state()+ try:+ finalized_outputs = self.complete(ref.exec_node_id, output_value)+ ref.effect_count = effect_count if effect_count is not None else ref.effect_count+ self.execution_refs[ref.exec_node_id] = ref+ self.execution_tokens.update(tokens)+ self.execution_effects[ref.reference_id] = persisted_effects+ return finalized_outputs+ except Exception:+ self._restore_apply_state(state_snapshot)+ raisedef _invalidate_loop_caches_for_source(self, source_node_id: str) -> None:self._all_for_contexts_finalized_cache.pop(source_node_id, None)diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 40d7f89a52..2849580ba4 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -287,7 +287,7 @@ def test_graph_state_apply_rejects_invalid_input_before_mutation():@pytest.mark.parametrize("effect_kind",- ["set_value", "add_edge", "remove_edge", "spawn_execution", "await", "fail", "close_stream", "unknown"],+ ["set_value", "add_edge", "remove_edge", "spawn_execution", "await", "fail", "unknown"],)def test_graph_state_apply_rejects_unsupported_effect_kinds(effect_kind: str):graph = Graph()@@ -333,6 +333,59 @@ def test_graph_state_apply_rejects_owned_unsupported_lifecycle_effects(effect_kiassert not state.execution_effects+def test_graph_state_apply_accepts_close_stream_effect():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)++ state.apply(+ ref,+ output,+ effects=[+ {+ "kind": "close_stream",+ "token": {"node_id": node.id, "field": "value", "token_kind": "stream_end"},+ }+ ],+ )++ token = state.execution_tokens[f"{ref.reference_id}:value:stream_end:effect"]+ assert token.token_kind == "stream_end"+++ "token",+ [+ {"node_id": "add", "field": "value", "token_kind": "data"},+ {"node_id": "add", "token_kind": "stream_end"},+ ],+)+def test_graph_state_apply_rejects_malformed_close_stream_token(token: dict[str, object]):+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)++ with pytest.raises(ValueError, match="Close-stream effect"):+ state.apply(+ ref,+ output,+ effects=[{"kind": "close_stream", "owner_node_id": node.id, "token": token}],+ )++ assert not state.executed+ assert not state.results+ assert not state.execution_tokens+ assert not state.execution_effects++def test_graph_state_apply_accepts_emit_effect():graph = Graph()graph.add_node(AddInvocation(id="add", a=1, b=2))@@ -427,6 +480,41 @@ def test_graph_state_apply_rejects_effect_from_another_state_before_mutation():assert not state.execution_effects+ "token_frame",+ [+ {"state_id": "other-state"},+ {"iteration_path": [99]},+ {"workflow_call_depth": 1},+ ],+)+def test_graph_state_apply_rejects_emit_token_from_another_frame(token_frame: dict[str, object]):+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)++ with pytest.raises(ValueError, match="another"):+ state.apply(+ ref,+ output,+ effects=[+ {+ "kind": "emit",+ "token": {"node_id": node.id, "field": "value", "value": 3, "frame": token_frame},+ }+ ],+ )++ assert not state.executed+ assert not state.results+ assert not state.execution_tokens+ assert not state.execution_effects++def test_graph_state_apply_does_not_complete_when_effect_persistence_preparation_fails():class Uncopyable:def __deepcopy__(self, memo):@@ -457,6 +545,68 @@ def test_graph_state_apply_does_not_complete_when_effect_persistence_preparationassert state.execution_refs == refs_before_apply+def test_graph_state_apply_rolls_back_scheduler_mutation_on_completion_failure():+ graph = Graph()+ graph.add_node(AddInvocation(id="first", a=1, b=2))+ graph.add_node(AddInvocation(id="second", a=0, b=4))+ graph.add_edge(create_edge("first", "value", "second", "a"))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id)+ state.indegree.pop(next(exec_id for exec_id in state.execution_graph.nodes if exec_id != node.id))+ state_before = {+ "execution_graph": state.execution_graph.model_dump(mode="json", warnings=False),+ "executed": state.executed.copy(),+ "executed_history": state.executed_history.copy(),+ "results": state.results.copy(),+ "prepared_source_mapping": state.prepared_source_mapping.copy(),+ "source_prepared_mapping": {key: value.copy() for key, value in state.source_prepared_mapping.items()},+ "prepared_iteration_paths": state.prepared_iteration_paths.copy(),+ "indegree": state.indegree.copy(),+ }++ with pytest.raises(KeyError, match="indegree missing"):+ state.apply(ref, output)++ assert state.execution_graph.model_dump(mode="json", warnings=False) == state_before["execution_graph"]+ assert state.executed == state_before["executed"]+ assert state.executed_history == state_before["executed_history"]+ assert state.results == state_before["results"]+ assert state.prepared_source_mapping == state_before["prepared_source_mapping"]+ assert state.source_prepared_mapping == state_before["source_prepared_mapping"]+ assert state.prepared_iteration_paths == state_before["prepared_iteration_paths"]+ assert state.indegree == state_before["indegree"]+ assert not state.execution_tokens+ assert not state.execution_effects+++def test_graph_state_apply_rejects_duplicate_execution_reference():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)+ effects = [{"owner_node_id": node.id, "source_port": "value"}]++ state.apply(ref, output, effects=effects)+ tokens_before = {key: value.model_dump(mode="json", warnings=False) for key, value in state.execution_tokens.items()}+ effects_before = state.execution_effects.copy()+ results_before = state.results.copy()++ with pytest.raises(ValueError, match="already been applied"):+ state.apply(ref, output, effects=effects)++ assert {+ key: value.model_dump(mode="json", warnings=False) for key, value in state.execution_tokens.items()+ } == tokens_before+ assert state.execution_effects == effects_before+ assert state.results == results_before++def test_graph_state_rehydrates_execution_refs_for_legacy_state():graph = Graph()graph.add_node(AddInvocation(id="add", a=1, b=2))