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
refactor(execution): route serial nested iterates
JPPhotoa4e2728c8e09
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 1d99b18b1a..c8b42f9415 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -89,6 +89,13 @@ and one ordinary outer-output consumer—is also generic-routed. It owns outerinput hydration, per-outer-frame stream expansion, checkpoint rehydration, andfailure parity; input-driven inner preparation, deeper or multiple nesting,mixed control flow, and legacy snapshots remain compatibility-owned.+The exact serial two-level extension—`For.item -> preparation1 -> Iterate1 ->+preparation2 -> Iterate2 -> ordinary body -> Collect -> linked ForReturn`, plus+one ordinary outer-output consumer—is also generic-routed. Its planner and+compatibility adapter preserve ordered nested frame paths, close empty streams,+resume from checkpoints, and stop downstream completion on failure/retry. Fan-in,+sibling iterators, input-driven inner preparation, mixed control flow, deeper+nesting, and legacy snapshots remain compatibility-owned.Three or more body-mediated branches, fan-in with four or more direct branches,nested iterators, and all mixed control flow retain materializer copy expansion,grouping, and empty-source handling on the legacy compatibility route.diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex b2dd63186d..090c1a5e14 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -814,13 +814,37 @@ class GraphExecutionState(BaseModel):iterate_nodes = [node for node in self.graph.nodes.values() if isinstance(node, IterateInvocation)]collect_nodes = [node for node in self.graph.nodes.values() if isinstance(node, CollectInvocation)]+ source_graph = self._get_source_graph_flat()+ if len(iterate_nodes) == 2 and len(collect_nodes) == 1:+ serial_chain = self.graph._get_supported_for_serial_nested_iterate_chain(outer_for.id, source_graph)+ if (+ can_use_nested_iterate_planner(self)+ and serial_chain is not None+ and len(self.graph.nodes) == 9+ and len(self.graph.edges) == 9+ ):+ body_nodes = set(serial_chain.body_path_nodes)+ outer_consumers = [+ node for node in self.graph.nodes.values() if node.id not in body_nodes and node.id != outer_for.id+ ]+ if len(outer_consumers) != 1:+ return False+ consumer = outer_consumers[0]+ output_edges = self.graph._get_output_edges(outer_for.id, "output_collection")+ consumer_inputs = self.graph._get_input_edges(consumer.id)+ return (+ not isinstance(consumer, (ForInvocation, ForReturnInvocation, IterateInvocation, CollectInvocation))+ and len(output_edges) == 1+ and output_edges[0].destination.node_id == consumer.id+ and output_edges[0].destination.field == "value"+ and consumer_inputs == output_edges+ )if len(iterate_nodes) != 1 or len(collect_nodes) != 1:return Falseiterate_node = iterate_nodes[0]collect_node = collect_nodes[0]return_node = return_nodes[0]- source_graph = self._get_source_graph_flat()if (not can_use_nested_iterate_planner(self)or self.graph._get_supported_for_nested_iterate_body(outer_for.id, source_graph) is Nonediff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.pyindex e988b4f6f7..38639b5212 100644--- a/invokeai/app/services/shared/graph_materializer.py+++ b/invokeai/app/services/shared/graph_materializer.py@@ -21,6 +21,7 @@ from invokeai.app.services.shared.graph_validation import (IterateInvocation,_SupportedNestedForBody,_SupportedNestedIterateBody,+ _SupportedNestedIterateChain,copydeep,get_output_field_scope,nx,@@ -270,6 +271,11 @@ class _ExecutionMaterializer:def create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:graph = self._state._get_source_graph_flat()execution_graph = self._state._get_execution_graph_flat()+ serial_nested_body = self._state.graph._get_supported_for_serial_nested_iterate_chain(source_for_id, graph)+ if serial_nested_body is not None:+ return self._create_serial_nested_iterate_body_iteration(+ source_for_id, prepared_for_id, graph, execution_graph, serial_nested_body+ )nested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)if nested_body is not None:return self._create_nested_iterate_body_iteration(@@ -469,6 +475,229 @@ class _ExecutionMaterializer:self._initialize_execution_node(prepared_return_node.id, attached_return_edges)return prepared_return_node.id+ def _create_serial_nested_iterate_copy(+ self,+ source_node_id: str,+ input_source_id: str,+ input_source_field: str,+ input_destination_field: str,+ iteration_path: tuple[int, ...],+ ) -> str:+ new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)+ self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)+ attached_edges = self._attach_execution_edges(+ new_node.id,+ [+ Edge(+ source=EdgeConnection(node_id=input_source_id, field=input_source_field),+ destination=EdgeConnection(node_id="", field=input_destination_field),+ )+ ],+ )+ self._initialize_execution_node(new_node.id, attached_edges)+ return new_node.id++ def _get_serial_nested_outer_path(self, prepared_for_id: str) -> tuple[int, ...]:+ prepared_for = self._state.execution_graph.get_node(prepared_for_id)+ iteration_path = self._state._get_iteration_path(prepared_for_id)+ if isinstance(prepared_for, ForInvocation) and prepared_for.index >= 0:+ return (*self._state._get_for_parent_iteration_path(prepared_for_id), prepared_for.index)+ return iteration_path++ def _get_serial_nested_prepared_at_path(+ self, source_node_id: str, iteration_path: tuple[int, ...]+ ) -> Optional[str]:+ matching_ids = [+ prepared_id+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_node_id)+ if self._state._get_iteration_path(prepared_id) == iteration_path+ ]+ if len(matching_ids) > 1:+ raise RuntimeError(f"Multiple prepared nested nodes exist for {source_node_id} at {iteration_path}")+ return matching_ids[0] if matching_ids else None++ def _create_serial_nested_collect_and_return(+ self,+ source_for_id: str,+ prepared_for_id: str,+ nested_body: _SupportedNestedIterateChain,+ outer_iteration_path: tuple[int, ...],+ body_prepared_ids: list[str],+ ) -> str:+ source_collect_id = nested_body.collect_node_id+ source_return_id = nested_body.return_node_id+ prepared_collect_id = self._get_serial_nested_prepared_at_path(source_collect_id, outer_iteration_path)+ if prepared_collect_id is None:+ collect_item_edge = self._state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]+ collect_edges = [+ Edge(+ source=EdgeConnection(node_id=body_prepared_id, field=collect_item_edge.source.field),+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),+ )+ for body_prepared_id in body_prepared_ids+ ]+ self._state._discard_source_executed(source_collect_id)+ prepared_collect_node = self._create_execution_node_copy(+ self._state.graph.get_node(source_collect_id), source_collect_id, -1+ )+ self._state._prepared_registry().set_iteration_path(prepared_collect_node.id, outer_iteration_path)+ attached_collect_edges = self._attach_execution_edges(prepared_collect_node.id, collect_edges)+ self._initialize_execution_node(prepared_collect_node.id, attached_collect_edges)+ prepared_collect_id = prepared_collect_node.id++ prepared_return_id = self._get_serial_nested_prepared_at_path(source_return_id, outer_iteration_path)+ if prepared_return_id is not None:+ return prepared_return_id++ self._state._discard_source_executed(source_return_id)+ return_edges: list[Edge] = []+ for edge in self._state.graph._get_input_edges(source_return_id):+ if edge.destination.field == "output":+ prepared_source_id = prepared_collect_id+ source_field = COLLECTION_FIELD+ elif edge.source.node_id == source_for_id:+ prepared_source_id = prepared_for_id+ source_field = edge.source.field+ else:+ raise RuntimeError(f"Unable to rematerialize serial nested ForReturn input {edge}")+ return_edges.append(+ Edge(+ source=EdgeConnection(node_id=prepared_source_id, field=source_field),+ destination=EdgeConnection(node_id="", field=edge.destination.field),+ )+ )++ prepared_return_node = self._create_execution_node_copy(+ self._state.graph.get_node(source_return_id), source_return_id, -1+ )+ self._state._prepared_registry().set_iteration_path(prepared_return_node.id, outer_iteration_path)+ attached_return_edges = self._attach_execution_edges(prepared_return_node.id, return_edges)+ self._initialize_execution_node(prepared_return_node.id, attached_return_edges)+ return prepared_return_node.id++ def _create_serial_nested_iterate_body_iteration(+ self,+ source_for_id: str,+ prepared_for_id: str,+ graph: "nx.DiGraph",+ execution_graph: "nx.DiGraph",+ nested_body: _SupportedNestedIterateChain,+ ) -> Optional[str]:+ del execution_graph+ outer_iteration_path = self._get_serial_nested_outer_path(prepared_for_id)+ first_iterate_id, second_iterate_id = nested_body.iterate_node_ids+ first_preparation_id = self._state.graph._get_input_edges(first_iterate_id, COLLECTION_FIELD)[0].source.node_id+ first_preparation_edge = self._state.graph._get_input_edges(first_preparation_id)[0]++ prepared_first_preparation_id = self._get_serial_nested_prepared_at_path(+ first_preparation_id, outer_iteration_path+ )+ if prepared_first_preparation_id is None:+ prepared_first_preparation_id = self._create_serial_nested_iterate_copy(+ first_preparation_id,+ prepared_for_id,+ first_preparation_edge.source.field,+ first_preparation_edge.destination.field,+ outer_iteration_path,+ )+ self._state._discard_source_executed(first_preparation_id)++ if prepared_first_preparation_id not in self._state.results:+ return None++ first_prepared_ids = [+ prepared_id+ for prepared_id in self._state._prepared_registry().get_prepared_ids(first_iterate_id)+ if self._state._get_iteration_path(prepared_id)[: len(outer_iteration_path)] == outer_iteration_path+ ]+ if not first_prepared_ids:+ self._state._discard_source_executed(first_iterate_id)+ first_prepared_ids = self.create_execution_node(+ first_iterate_id,+ [(first_preparation_id, prepared_first_preparation_id)],+ iteration_path=outer_iteration_path,+ )+ if not first_prepared_ids:+ self._state._record_empty_iterate_stream(first_iterate_id, outer_iteration_path)+ return self._create_serial_nested_collect_and_return(+ source_for_id, prepared_for_id, nested_body, outer_iteration_path, []+ )+ return first_prepared_ids[0]++ second_preparation_id = self._state.graph._get_input_edges(second_iterate_id, COLLECTION_FIELD)[+ 0+ ].source.node_id+ second_preparation_edge = self._state.graph._get_input_edges(second_preparation_id)[0]+ prepared_second_preparation_ids: list[str] = []+ for first_prepared_id in first_prepared_ids:+ if first_prepared_id not in self._state.results:+ continue+ prepared_id = self._get_serial_nested_prepared_at_path(+ second_preparation_id, self._state._get_iteration_path(first_prepared_id)+ )+ if prepared_id is not None and prepared_id in self._state.results:+ prepared_second_preparation_ids.append(prepared_id)+ if len(prepared_second_preparation_ids) != len(first_prepared_ids):+ self._state._discard_source_executed(second_preparation_id)+ created_ids: list[str] = []+ for first_prepared_id in first_prepared_ids:+ iteration_path = self._state._get_iteration_path(first_prepared_id)+ if self._get_serial_nested_prepared_at_path(second_preparation_id, iteration_path) is not None:+ continue+ created_ids.append(+ self._create_serial_nested_iterate_copy(+ second_preparation_id,+ first_prepared_id,+ second_preparation_edge.source.field,+ second_preparation_edge.destination.field,+ iteration_path,+ )+ )+ return created_ids[0] if created_ids else None++ second_prepared_ids: list[str] = []+ body_prepared_ids: list[str] = []+ body_node_id = self._state.graph._get_input_edges(nested_body.collect_node_id, ITEM_FIELD)[0].source.node_id+ body_input_edge = self._state.graph._get_input_edges(body_node_id)[0]+ self._state._discard_source_executed(second_iterate_id)+ for prepared_second_preparation_id in prepared_second_preparation_ids:+ iteration_path = self._state._get_iteration_path(prepared_second_preparation_id)+ second_ids = [+ prepared_id+ for prepared_id in self._state._prepared_registry().get_prepared_ids(second_iterate_id)+ if self._state._get_iteration_path(prepared_id)[: len(iteration_path)] == iteration_path+ and len(self._state._get_iteration_path(prepared_id)) == len(iteration_path) + 1+ ]+ if not second_ids:+ second_ids = self.create_execution_node(+ second_iterate_id,+ [(second_preparation_id, prepared_second_preparation_id)],+ iteration_path=iteration_path,+ )+ second_prepared_ids.extend(second_ids)+ for prepared_second_id in second_ids:+ prepared_body_id = self._get_serial_nested_prepared_at_path(+ body_node_id, self._state._get_iteration_path(prepared_second_id)+ )+ if prepared_body_id is None:+ prepared_body_id = self._create_serial_nested_iterate_copy(+ body_node_id,+ prepared_second_id,+ body_input_edge.source.field,+ body_input_edge.destination.field,+ self._state._get_iteration_path(prepared_second_id),+ )+ body_prepared_ids.append(prepared_body_id)+ if not second_ids:+ self._state._record_empty_iterate_stream(second_iterate_id, iteration_path)++ if not second_prepared_ids:+ self._state._mark_source_node_empty(second_iterate_id, outer_iteration_path)+ self._state._mark_source_node_empty(body_node_id, outer_iteration_path)+ return self._create_serial_nested_collect_and_return(+ source_for_id, prepared_for_id, nested_body, outer_iteration_path, body_prepared_ids+ )+def _create_nested_for_body_iteration(self,source_for_id: str,diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.pyindex 7a05d3678e..62c6dc5348 100644--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py@@ -14,6 +14,7 @@ from invokeai.app.services.shared.graph_models import Edge, EdgeConnectionfrom invokeai.app.services.shared.graph_validation import (COLLECTION_FIELD,ITEM_FIELD,+ _SupportedNestedIterateChain,)if TYPE_CHECKING:@@ -31,6 +32,12 @@ def _get_exact_nested_iterate_body(state: "GraphExecutionState"):input_driven_outer = bool(outer_collection_edges)expected_node_count = 8 if input_driven_outer else 7expected_edge_count = 8 if input_driven_outer else 7+ if not input_driven_outer:+ serial_chain = state.graph._get_supported_for_serial_nested_iterate_chain(+ for_node.id, state._get_source_graph_flat()+ )+ if serial_chain is not None and len(state.graph.nodes) == 9 and len(state.graph.edges) == 9:+ return for_node.id, serial_chainif len(state.graph.nodes) != expected_node_count or len(state.graph.edges) != expected_edge_count:return Noneif input_driven_outer:@@ -89,6 +96,9 @@ def _prepare_nested_iterate_body_for_outer(if exact is None or exact[0] != source_for_id:return_, nested_body = exact+ if isinstance(nested_body, _SupportedNestedIterateChain):+ _prepare_serial_nested_iterate_chain_for_outer(state, source_for_id, prepared_for_id, nested_body)+ returnouter_path = _outer_iteration_path(state, prepared_for_id)source_iterate_id = nested_body.iterate_node_idsource_collect_id = nested_body.collect_node_id@@ -192,6 +202,180 @@ def _prepare_nested_iterate_body_for_outer(_initialize_direct_execution_node(state, return_node.id, attached_return_edges)+def _prepare_serial_nested_iterate_chain_for_outer(+ state: "GraphExecutionState",+ source_for_id: str,+ prepared_for_id: str,+ nested_body: _SupportedNestedIterateChain,+) -> None:+ """Prepare one exact serial two-level nested iterator body incrementally."""+ outer_path = _outer_iteration_path(state, prepared_for_id)+ first_iterate_id, second_iterate_id = nested_body.iterate_node_ids+ source_collect_id = nested_body.collect_node_id+ source_return_id = nested_body.return_node_id++ first_input_edge = state.graph._get_input_edges(first_iterate_id, COLLECTION_FIELD)[0]+ first_preparation_id = first_input_edge.source.node_id+ first_preparation_input = state.graph._get_input_edges(first_preparation_id)[0]+ second_input_edge = state.graph._get_input_edges(second_iterate_id, COLLECTION_FIELD)[0]+ second_preparation_id = second_input_edge.source.node_id+ second_preparation_input = state.graph._get_input_edges(second_preparation_id)[0]+ body_input = state.graph._get_input_edges(+ state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0].source.node_id+ )[0]+ body_node_id = body_input.destination.node_id+ collect_item_edge = state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]++ def create_copy(+ source_node_id: str,+ iteration_path: tuple[int, ...],+ input_edges: list[Edge],+ iteration_index: int = -1,+ ) -> str:+ node = _create_direct_execution_node_copy(+ state, source_node_id, iteration_index=iteration_index, iteration_path=iteration_path+ )+ attached_edges = _attach_direct_execution_edges(state, node.id, input_edges)+ _initialize_direct_execution_node(state, node.id, attached_edges)+ return node.id++ preparation_exec_id = _prepared_at_path(state, first_preparation_id, outer_path)+ if preparation_exec_id is None:+ create_copy(+ first_preparation_id,+ outer_path,+ [+ Edge(+ source=EdgeConnection(node_id=prepared_for_id, field=first_preparation_input.source.field),+ destination=EdgeConnection(node_id="", field=first_preparation_input.destination.field),+ )+ ],+ )+ return+ if preparation_exec_id not in state.results:+ return++ collection = getattr(state.results[preparation_exec_id], first_input_edge.source.field)+ if not isinstance(collection, list):+ raise ValueError("Nested Iterate collection source must produce a list")++ state._discard_source_executed(first_iterate_id)+ for first_index in range(len(collection)):+ first_path = (*outer_path, first_index)+ first_exec_id = _prepared_at_path(state, first_iterate_id, first_path)+ if first_exec_id is None:+ first_exec_id = create_copy(+ first_iterate_id,+ first_path,+ [+ Edge(+ source=EdgeConnection(node_id=preparation_exec_id, field=first_input_edge.source.field),+ destination=EdgeConnection(node_id="", field=first_input_edge.destination.field),+ )+ ],+ iteration_index=first_index,+ )+ second_preparation_exec_id = _prepared_at_path(state, second_preparation_id, first_path)+ if second_preparation_exec_id is None:+ create_copy(+ second_preparation_id,+ first_path,+ [+ Edge(+ source=EdgeConnection(node_id=first_exec_id, field=second_preparation_input.source.field),+ destination=EdgeConnection(node_id="", field=second_preparation_input.destination.field),+ )+ ],+ )++ if not collection:+ state._record_empty_iterate_stream(first_iterate_id, outer_path)++ second_preparation_exec_ids = [+ _prepared_at_path(state, second_preparation_id, (*outer_path, first_index))+ for first_index in range(len(collection))+ ]+ if any(exec_id is None or exec_id not in state.results for exec_id in second_preparation_exec_ids):+ return++ body_exec_ids: list[str] = []+ state._discard_source_executed(second_iterate_id)+ for first_index, second_preparation_exec_id in enumerate(second_preparation_exec_ids):+ assert second_preparation_exec_id is not None+ second_path = (*outer_path, first_index)+ second_collection = getattr(state.results[second_preparation_exec_id], second_input_edge.source.field)+ if not isinstance(second_collection, list):+ raise ValueError("Nested Iterate collection source must produce a list")+ for second_index in range(len(second_collection)):+ inner_path = (*second_path, second_index)+ second_exec_id = _prepared_at_path(state, second_iterate_id, inner_path)+ if second_exec_id is None:+ second_exec_id = create_copy(+ second_iterate_id,+ inner_path,+ [+ Edge(+ source=EdgeConnection(+ node_id=second_preparation_exec_id, field=second_input_edge.source.field+ ),+ destination=EdgeConnection(node_id="", field=second_input_edge.destination.field),+ )+ ],+ iteration_index=second_index,+ )+ body_exec_id = _prepared_at_path(state, body_node_id, inner_path)+ if body_exec_id is None:+ body_exec_id = create_copy(+ body_node_id,+ inner_path,+ [+ Edge(+ source=EdgeConnection(node_id=second_exec_id, field=body_input.source.field),+ destination=EdgeConnection(node_id="", field=body_input.destination.field),+ )+ ],+ )+ body_exec_ids.append(body_exec_id)+ if not second_collection:+ state._record_empty_iterate_stream(second_iterate_id, second_path)++ if _prepared_at_path(state, source_collect_id, outer_path) is not None:+ return+ state._discard_source_executed(source_collect_id)+ collect_node = _create_direct_execution_node_copy(state, source_collect_id, iteration_path=outer_path)+ attached_collect_edges = _attach_direct_execution_edges(+ state,+ collect_node.id,+ [+ Edge(+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),+ )+ for body_exec_id in body_exec_ids+ ],+ )+ _initialize_direct_execution_node(state, collect_node.id, attached_collect_edges)++ state._discard_source_executed(source_return_id)+ return_node = _create_direct_execution_node_copy(state, source_return_id, iteration_path=outer_path)+ return_input_edges = state.graph._get_input_edges(source_return_id, "output")+ _initialize_direct_execution_node(+ state,+ return_node.id,+ _attach_direct_execution_edges(+ state,+ return_node.id,+ [+ Edge(+ source=EdgeConnection(node_id=collect_node.id, field=COLLECTION_FIELD),+ destination=EdgeConnection(node_id="", field=edge.destination.field),+ )+ for edge in return_input_edges+ ],+ ),+ )++def prepare_nested_iterate_bodies(state: "GraphExecutionState") -> None:"""Prepare the exact nested stream body for every outer For execution path."""if not can_use_nested_iterate_planner(state):diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.pyindex cf716853ba..1da04da7a2 100644--- a/invokeai/app/services/shared/graph_scheduler.py+++ b/invokeai/app/services/shared/graph_scheduler.py@@ -122,6 +122,24 @@ class _ExecutionScheduler:for source_for_id, source_node in self._state.graph.nodes.items():if not isinstance(source_node, ForInvocation):continue+ serial_nested_body = self._state.graph._get_supported_for_serial_nested_iterate_chain(source_for_id, graph)+ if serial_nested_body is not None:+ if completed_source_id not in serial_nested_body.body_path_nodes:+ continue+ prepared_exec_path = self._state._get_iteration_path(exec_node_id)+ for prepared_for_id in self._state._prepared_registry().get_prepared_ids(source_for_id):+ prepared_for_path = self._state._get_iteration_path(prepared_for_id)+ prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)+ if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:+ prepared_for_path = (+ *self._state._get_for_parent_iteration_path(prepared_for_id),+ prepared_for_node.index,+ )+ if prepared_exec_path[: len(prepared_for_path)] == prepared_for_path:+ self._state._materializer().create_for_body_iteration(+ source_for_id=source_for_id, prepared_for_id=prepared_for_id+ )+ returnnested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)nested_for_body = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)if nested_body is not None:diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.pyindex da2bab8f4f..754d6d16b0 100644--- a/invokeai/app/services/shared/graph_validation.py+++ b/invokeai/app/services/shared/graph_validation.py@@ -39,6 +39,7 @@ from invokeai.app.invocations.call_saved_workflow import (is_call_saved_workflow_dynamic_input,)from invokeai.app.invocations.fields import Input, InputField, OutputField, OutputScope, UIType+from invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import (LOOP_LINKAGE_FIELD,ForInvocation,@@ -110,6 +111,14 @@ class _SupportedNestedIterateBody:collect_node_id: str+@dataclass(frozen=True)+class _SupportedNestedIterateChain:+ body_path_nodes: frozenset[str]+ return_node_id: str+ iterate_node_ids: tuple[str, str]+ collect_node_id: str++def get_output_field_type(node: BaseInvocation, field: str) -> Any:implementation = _get_facade_override("get_output_field_type", get_output_field_type)if implementation is not get_output_field_type:@@ -1237,6 +1246,127 @@ class Graph(BaseModel):collect_node_id=collect_node_id,)+ def _get_supported_for_serial_nested_iterate_chain(+ self, node_id: str, graph: "nx.DiGraph"+ ) -> _SupportedNestedIterateChain | None:+ """Return the exact two-level serial Iterate contract, if present.++ Supported shape::++ For.item -> prep1 -> Iterate1.item -> prep2 -> Iterate2.item -> body -> Collect.item+ Collect.collection -> ForReturn.output++ This intentionally excludes sibling iterators, fan-in, and additional control-flow nodes. Those shapes must+ remain on the compatibility path until separately proven equivalent.+ """+ body_path_to_return = self._get_for_body_path_to_return(node_id, graph)+ if body_path_to_return is None:+ return None+ body_path_nodes, return_node_id = body_path_to_return+ iterate_node_ids = tuple(+ body_node_id+ for body_node_id in body_path_nodes+ if isinstance(self.get_node(body_node_id), IterateInvocation)+ )+ collect_node_ids = tuple(+ body_node_id+ for body_node_id in body_path_nodes+ if isinstance(self.get_node(body_node_id), CollectInvocation)+ )+ if len(iterate_node_ids) != 2 or len(collect_node_ids) != 1:+ return None++ collect_node_id = collect_node_ids[0]+ if len(body_path_nodes) != 7:+ return None+ return_output_edges = self._get_input_edges(return_node_id, "output")+ if len(return_output_edges) != 1 or (+ return_output_edges[0].source.node_id != collect_node_id+ or return_output_edges[0].source.field != COLLECTION_FIELD+ ):+ return None+ if self._get_input_edges(collect_node_id, COLLECTION_FIELD):+ return None+ collect_item_edges = self._get_input_edges(collect_node_id, ITEM_FIELD)+ if len(collect_item_edges) != 1:+ return None++ first_iterate_id, second_iterate_id = sorted(+ iterate_node_ids, key=lambda iterate_id: nx.shortest_path_length(graph, node_id, iterate_id)+ )+ if not nx.has_path(graph, first_iterate_id, second_iterate_id) or not nx.has_path(+ graph, second_iterate_id, collect_node_id+ ):+ return None+ first_input_edges = self._get_input_edges(first_iterate_id, COLLECTION_FIELD)+ second_input_edges = self._get_input_edges(second_iterate_id, COLLECTION_FIELD)+ if len(first_input_edges) != 1 or len(second_input_edges) != 1:+ return None+ first_preparation_id = first_input_edges[0].source.node_id+ second_preparation_id = second_input_edges[0].source.node_id+ body_node_id = collect_item_edges[0].source.node_id+ expected_nodes = {+ first_preparation_id,+ first_iterate_id,+ second_preparation_id,+ second_iterate_id,+ body_node_id,+ collect_node_id,+ return_node_id,+ }+ if body_path_nodes != expected_nodes or first_preparation_id == second_preparation_id:+ return None++ control_types = (+ CallSavedWorkflowInvocation,+ IfInvocation,+ ForInvocation,+ ForReturnInvocation,+ IterateInvocation,+ CollectInvocation,+ )+ ordinary_nodes = {first_preparation_id, second_preparation_id, body_node_id}+ if any(isinstance(self.get_node(candidate_id), control_types) for candidate_id in ordinary_nodes):+ return None+ if (+ first_input_edges[0].source.node_id != first_preparation_id+ or first_input_edges[0].source.field != COLLECTION_FIELD+ or second_input_edges[0].source.node_id != second_preparation_id+ or second_input_edges[0].source.field != COLLECTION_FIELD+ ):+ return None++ first_preparation_inputs = self._get_input_edges(first_preparation_id)+ second_preparation_inputs = self._get_input_edges(second_preparation_id)+ body_inputs = self._get_input_edges(body_node_id)+ if (+ len(first_preparation_inputs) != 1+ or first_preparation_inputs[0].source.node_id != node_id+ or first_preparation_inputs[0].source.field != ITEM_FIELD+ or len(second_preparation_inputs) != 1+ or second_preparation_inputs[0].source.node_id != first_iterate_id+ or second_preparation_inputs[0].source.field != ITEM_FIELD+ or len(body_inputs) != 1+ or body_inputs[0].source.node_id != second_iterate_id+ or body_inputs[0].source.field != ITEM_FIELD+ ):+ return None+ if self._get_output_edges(node_id, ITEM_FIELD) != first_preparation_inputs:+ return None+ if self._get_output_edges(first_iterate_id, ITEM_FIELD) != second_preparation_inputs:+ return None+ if self._get_output_edges(second_iterate_id, ITEM_FIELD) != body_inputs:+ return None+ if self._get_output_edges(body_node_id) != collect_item_edges:+ return None++ return _SupportedNestedIterateChain(+ body_path_nodes=frozenset(body_path_nodes),+ return_node_id=return_node_id,+ iterate_node_ids=(first_iterate_id, second_iterate_id),+ collect_node_id=collect_node_id,+ )+def _get_supported_for_nested_for_body(self, node_id: str, graph: "nx.DiGraph") -> _SupportedNestedForBody | None:"""Returns the supported recursive nested For contract, if this For uses it.@@ -1481,7 +1611,10 @@ class Graph(BaseModel):return "For loop body paths must terminate at the matching ForReturn and not escape the loop body"if any(isinstance(self.get_node(body_node_id), IterateInvocation) for body_node_id in body_path_nodes):- if self._get_supported_for_nested_iterate_body(node_id, graph) is None:+ if (+ self._get_supported_for_nested_iterate_body(node_id, graph) is None+ and self._get_supported_for_serial_nested_iterate_chain(node_id, graph) is None+ ):return "Iterate nodes inside For loop bodies are unsupported"for body_node_id in body_path_nodes:diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 4573e2ec66..b2ed757437 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -575,6 +575,33 @@ def _input_driven_nested_for_iterate_collect_graph() -> Graph:return graph+def _serial_two_level_nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | None = None) -> Graph:+ graph = Graph()+ graph.add_node(ForInvocation(id="outer_for", collection=outer_collection or [["a", "b"], ["c"]]))+ graph.add_node(PolymorphicStringTestInvocation(id="nested_collection_1"))+ graph.add_node(IterateInvocation(id="nested_iterate_1"))+ graph.add_node(PolymorphicStringTestInvocation(id="nested_collection_2"))+ graph.add_node(IterateInvocation(id="nested_iterate_2"))+ graph.add_node(AnyTypeTestInvocation(id="nested_body"))+ graph.add_node(CollectInvocation(id="nested_collect"))+ graph.add_node(ForReturnInvocation(id="outer_return"))+ graph.add_node(AnyTypeTestInvocation(id="after"))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))++ connect("outer_for", "item", "nested_collection_1", "value")+ connect("nested_collection_1", "collection", "nested_iterate_1", "collection")+ connect("nested_iterate_1", "item", "nested_collection_2", "value")+ connect("nested_collection_2", "collection", "nested_iterate_2", "collection")+ connect("nested_iterate_2", "item", "nested_body", "value")+ connect("nested_body", "value", "nested_collect", "item")+ connect("nested_collect", "collection", "outer_return", "output")+ connect("outer_for", "output_collection", "after", "value")+ graph.add_edge(create_loop_linkage("outer_for", "outer_return"))+ return graph++def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, with_after: bool = False, downstream_count: int | None = None) -> Graph:@@ -1950,6 +1977,101 @@ def test_input_driven_nested_for_iterate_collect_failure_matches_compatibility()assert _state_projection(generic_state) == _state_projection(compatibility_state)+def test_serial_two_level_nested_for_iterate_collect_uses_generic_planner() -> None:+ compatibility_state = GraphExecutionState(graph=_serial_two_level_nested_for_iterate_collect_graph())+ compatibility_trace, compatibility_state = _run(+ compatibility_state,+ force_compatibility_scheduler=True,+ )+ state = GraphExecutionState(graph=_serial_two_level_nested_for_iterate_collect_graph())+ assert state._can_use_generic_scheduler()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "_create_nested_iterate_body_iteration",+ side_effect=AssertionError("serial nested Iterate/Collect used materializer copy creation"),+ ):+ trace, state = _run(state)+ assert state.is_complete()+ assert compatibility_state.is_complete()+ assert trace == compatibility_trace+++def test_serial_two_level_nested_for_iterate_collect_generic_closes_empty_streams() -> None:+ graph = _serial_two_level_nested_for_iterate_collect_graph(outer_collection=[[], ["c"]])+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )+ state = GraphExecutionState(graph=graph)+ trace, state = _run(state)++ assert state.is_complete()+ assert compatibility_state.is_complete()+ assert trace == compatibility_trace+ assert _state_projection(state) == _state_projection(compatibility_state)+ assert trace[-1] == "after"+ runtime = state._generic_runtime()+ assert runtime.streams[state._iteration_stream_id("nested_iterate_1", (0,))].values == ()+ assert runtime.streams[state._iteration_stream_id("nested_iterate_2", (1, 0))].values == ("c",)+ assert _source_output(state, "after").value == [[], ["c"]]+++def test_serial_two_level_nested_for_iterate_collect_generic_rehydrates() -> None:+ graph = _serial_two_level_nested_for_iterate_collect_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=5)++ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )+ assert compatibility_trace == expected_trace+ assert _state_projection(compatibility_state) == _state_projection(expected_state)+++def test_serial_two_level_nested_for_iterate_collect_generic_failure_stops_outer_return() -> None:+ graph = _serial_two_level_nested_for_iterate_collect_graph()+ trace, state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="nested_body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="nested_body",+ )++ assert state.has_error()+ assert state.is_complete()+ assert compatibility_state.has_error()+ assert compatibility_state.is_complete()+ assert trace == compatibility_trace+ assert "nested_collect" not in trace+ assert "outer_return" not in trace+ assert "after" not in trace+++def test_serial_two_level_nested_for_iterate_collect_retry_isolated() -> None:+ graph = _serial_two_level_nested_for_iterate_collect_graph()+ canceled_trace, canceled_state = _run_until_source(+ GraphExecutionState(graph=graph),+ "nested_collection_2",+ )+ retry_trace, retry_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))++ assert canceled_trace[:3] == ["outer_for", "nested_collection_1", "nested_iterate_1"]+ assert not canceled_state.is_complete()+ assert retry_trace[-2:] == ["outer_return", "after"]+ assert retry_state.id != canceled_state.id+ assert _source_output(retry_state, "after").value == [["a", "b"], ["c"]]+ assert retry_state.is_complete()++@pytest.mark.parametrize("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))