Skip to content

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.

refactor(graph): classify loop shapes once per graph (#9940)

Josh Corbett33f170207835
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 90a5717fc3..c3c561ea50 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -130,6 +130,9 @@ not admit sibling iterators, fan-in, or additional control-flow nodes.
Unsupported shapes, including independent iterator-derived body inputs, mixed nested `For`/`Iterate` bodies, escaping
body paths, ambiguous returns, and arbitrary cyclic graphs, are rejected before execution.
+The backend classifies each `For` body once per graph in `invokeai/app/services/shared/graph_loop_topology.py`.
+Validation and scheduling use the same classifier, so the shape validation accepts is the shape the scheduler runs.
+
## Generic `For` routing matrix
`_GenericForPlanner` owns these fresh shapes. `_ExecutionMaterializer` remains the compatibility facade for every other
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 2be4ec6ae6..49d19429b7 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -590,6 +590,13 @@ Workflow-call note:
- Private `graph_iterate_planner.py` expands the supported direct and body-mediated Iterate/Collect shapes. Graph-state
method wrappers preserve the admission, copy creation, edge attachment, and atomic preparation entry points. The
planner continues to use the graph state's journal, mappings, caches, and scheduler.
+- Private `graph_loop_topology.py` classifies every `For` once per graph: its body path to the linked `ForReturn`, and
+ its supported nested body shape (`NestedForBody`, `NestedIterateBody`, or `NestedIterateChain`). It also recognizes
+ the whole-graph serial `Iterate` chain (`NestedIterateSequence`). Graph validation rejects nested `For` and
+ `Iterate`-in-`For` bodies without a shape. Graph state, both schedulers, the nested planner, and the materializer
+ read `GraphExecutionState._loop_topology()` instead of re-recognizing shapes per completed node. Classification
+ reads only node types and edges, so it is dropped with the cached flat source graph (graph mutation, transaction
+ rollback, or a runtime-cache reset) and rebuilt from the next one.
- `_IfActivationController` Owns fallback runtime `If` admission and compiles opaque, frame-local activation dependency
records for unsupported fresh shapes and legacy prepared nodes. Fresh ordinary-node single-`If` graphs, the bounded
nested pair, the exact bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain, and exactly
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 0e204659a3..743b51d13f 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -108,6 +108,7 @@ from invokeai.app.services.shared.graph_iterate_planner import (
_prepare_direct_iterate_collect_fan_in_unchecked,
_prepare_direct_iterate_collect_unchecked,
)
+from invokeai.app.services.shared.graph_loop_topology import LoopTopology
from invokeai.app.services.shared.graph_materializer import _ExecutionMaterializer
from invokeai.app.services.shared.graph_models import (
Edge, # noqa: F401
@@ -163,8 +164,6 @@ from invokeai.app.services.shared.graph_validation import (
_EdgeListMutationResult, # noqa: F401
_invalidates_edge_indexes, # noqa: F401
_LazyNetworkX, # noqa: F401
- _SupportedNestedForBody, # noqa: F401
- _SupportedNestedIterateBody, # noqa: F401
are_connection_types_compatible, # noqa: F401
are_connections_compatible, # noqa: F401
copydeep,
@@ -248,7 +247,7 @@ class _GraphExecutionStateRuntime:
"execution_graph_flat",
"completed_source_ids_cache",
"unexecuted_prepared_counts",
- "for_source_by_return_id",
+ "loop_topology",
"apply_transaction",
"generic_execution_runtime",
"generic_graph_scheduler",
@@ -299,7 +298,7 @@ class _GraphExecutionStateRuntime:
self.execution_graph_flat: Any | None = None
self.completed_source_ids_cache: Optional[set[str]] = None
self.unexecuted_prepared_counts: Optional[dict[str, int]] = None
- self.for_source_by_return_id: Optional[dict[str, str]] = None
+ self.loop_topology: Optional[LoopTopology] = None
self.apply_transaction: Optional[_ApplyTransaction] = None
self.generic_execution_runtime: Optional[ExecutionEngineRuntime] = None
self.generic_graph_scheduler: Optional[_GenericGraphSchedulerAdapter] = None
@@ -572,10 +571,10 @@ class GraphExecutionState(BaseModel):
self._selected_if_frames_for_preparation = {}
self._execution_runtime = None
self._source_graph_flat = None
+ self.__pydantic_private__["_runtime_state"].loop_topology = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
self._unexecuted_prepared_counts = None
- self._for_source_by_return_id = None
self._for_parent_iteration_paths_cache = {}
self._all_for_contexts_finalized_cache = {}
self._prepared_for_index = None
@@ -653,6 +652,16 @@ class GraphExecutionState(BaseModel):
runtime.source_graph_flat = self.graph.nx_graph_flat()
return runtime.source_graph_flat
+ def _loop_topology(self) -> LoopTopology:
+ """Return the loop shapes of the source graph, classified once per flat source graph."""
+ runtime = self.__pydantic_private__["_runtime_state"]
+ source_graph = self._get_source_graph_flat()
+ topology = runtime.loop_topology
+ # Every site that drops the flat graph also drops the topology; the identity check covers any other rebuild.
+ if topology is None or topology.flat_graph is not source_graph:
+ topology = runtime.loop_topology = LoopTopology.classify(self.graph, source_graph)
+ return topology
+
def _get_fresh_if_nodes(self) -> tuple[IfInvocation, ...]:
return graph_if_dependencies._get_fresh_if_nodes(self)
@@ -836,25 +845,13 @@ class GraphExecutionState(BaseModel):
}
return runtime.completed_source_ids_cache
- def _get_for_source_by_return_id(self) -> dict[str, str]:
- if self._for_source_by_return_id is None:
- source_graph = self._get_source_graph_flat()
- self._for_source_by_return_id = {
- body_path_to_return[1]: source_for_id
- for source_for_id, source_for_node in self.graph.nodes.items()
- if isinstance(source_for_node, ForInvocation)
- and (body_path_to_return := self.graph._get_for_body_path_to_return(source_for_id, source_graph))
- is not None
- }
- return self._for_source_by_return_id
-
def _invalidate_source_graph_cache(self) -> None:
runtime = self.__pydantic_private__["_runtime_state"]
self._invalidate_selected_if_frames_for_preparation()
runtime.source_graph_flat = None
+ runtime.loop_topology = None
runtime.fresh_flat_if_activation = None
runtime.if_iteration_axes_validated = False
- runtime.for_source_by_return_id = None
runtime.if_branch_sources_cache = {}
runtime.if_activation_dependencies_by_source = {}
runtime.if_activation_dependencies_by_exec = {}
@@ -893,7 +890,7 @@ class GraphExecutionState(BaseModel):
def _get_for_parent(self, exec_node_id: str) -> Optional[str]:
source_return_id = self._prepared_registry().get_source_node_id(exec_node_id)
iteration_path = self._get_iteration_path(exec_node_id)
- source_for_id = self._get_for_source_by_return_id().get(source_return_id)
+ source_for_id = self._loop_topology().for_id_by_return_id.get(source_return_id)
if source_for_id is not None:
prepared_for_id = self._get_prepared_for_index().get((source_for_id, iteration_path))
if prepared_for_id is not None:
@@ -1051,7 +1048,7 @@ class GraphExecutionState(BaseModel):
return self._apply_for_continuation(exec_node_id, output, self._materializer())
def _can_use_generic_two_sibling_nested_for_scheduler(
- self, for_nodes: list[ForInvocation], return_nodes: list[ForReturnInvocation], source_graph: Any
+ self, for_nodes: list[ForInvocation], return_nodes: list[ForReturnInvocation], loop_topology: LoopTopology
) -> bool:
if len(for_nodes) != 3 or len(return_nodes) != 3 or len(self.graph.nodes) != 10 or len(self.graph.edges) != 13:
return False
@@ -1059,7 +1056,7 @@ class GraphExecutionState(BaseModel):
outer_candidates = []
nested_bodies = {}
for node in for_nodes:
- nested_body = self.graph._get_supported_for_nested_for_body(node.id, source_graph)
+ nested_body = loop_topology.nested_for_body(node.id)
if nested_body is not None:
nested_bodies[node.id] = nested_body
if len(nested_body.inner_for_ids) == 2 and len(nested_body.continuation_nodes) == 1:
@@ -1118,7 +1115,7 @@ class GraphExecutionState(BaseModel):
child_return_id = self.graph._get_linked_for_return_id(child_id)
if child_return_id is None:
return False
- child_body_path = self.graph._get_for_body_path_to_return(child_id, source_graph)
+ child_body_path = loop_topology.for_body_paths.get(child_id)
if child_body_path is None or len(child_body_path[0]) != 2 or child_body_path[1] != child_return_id:
return False
child_body_ids = child_body_path[0] - {child_return_id}
@@ -1162,7 +1159,7 @@ class GraphExecutionState(BaseModel):
self,
for_nodes: list[ForInvocation],
return_nodes: list[ForReturnInvocation],
- source_graph: Any,
+ loop_topology: LoopTopology,
*,
nested_level: Literal[3, 4] = 3,
) -> bool:
@@ -1174,7 +1171,7 @@ class GraphExecutionState(BaseModel):
outer_candidates: list[ForInvocation] = []
for_node_bodies: dict[str, Any] = {}
for node in for_nodes:
- nested_body = self.graph._get_supported_for_nested_for_body(node.id, source_graph)
+ nested_body = loop_topology.nested_for_body(node.id)
if nested_body is not None:
for_node_bodies[node.id] = nested_body
nested_child_ids = {
@@ -1262,16 +1259,16 @@ class GraphExecutionState(BaseModel):
return_nodes = [node for node in self.graph.nodes.values() if isinstance(node, ForReturnInvocation)]
if any(isinstance(node, (IterateInvocation, CollectInvocation)) for node in self.graph.nodes.values()):
return self._can_use_generic_nested_iterate_scheduler(for_nodes, return_nodes)
- source_graph = self._get_source_graph_flat()
+ loop_topology = self._loop_topology()
if len(for_nodes) == 3 and len(return_nodes) == 3:
- if self._can_use_generic_two_sibling_nested_for_scheduler(for_nodes, return_nodes, source_graph):
+ if self._can_use_generic_two_sibling_nested_for_scheduler(for_nodes, return_nodes, loop_topology):
return True
- return self._can_use_generic_serial_nested_for_scheduler(for_nodes, return_nodes, source_graph)
+ return self._can_use_generic_serial_nested_for_scheduler(for_nodes, return_nodes, loop_topology)
if len(for_nodes) == 4 and len(return_nodes) == 4:
return self._can_use_generic_serial_nested_for_scheduler(
for_nodes,
return_nodes,
- source_graph,
+ loop_topology,
nested_level=4,
)
if len(for_nodes) == 2 and len(return_nodes) == 2:
@@ -1279,7 +1276,7 @@ class GraphExecutionState(BaseModel):
(
node
for node in for_nodes
- if (nested_body := self.graph._get_supported_for_nested_for_body(node.id, source_graph)) is not None
+ if (nested_body := loop_topology.nested_for_body(node.id)) is not None
and len(nested_body.inner_for_ids) == 1
and not nested_body.continuation_nodes
),
@@ -1289,7 +1286,7 @@ class GraphExecutionState(BaseModel):
not self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD) and not outer_for.collection
):
return False
- nested_body = self.graph._get_supported_for_nested_for_body(outer_for.id, source_graph)
+ nested_body = loop_topology.nested_for_body(outer_for.id)
assert nested_body is not None
outer_collection_edges = self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD)
if outer_collection_edges:
@@ -1347,7 +1344,7 @@ class GraphExecutionState(BaseModel):
and not collection_value
):
empty_collection_source = collection_source
- body_path = self.graph._get_for_body_path_to_return(for_nodes[0].id, self._get_source_graph_flat())
+ body_path = loop_topology.for_body_paths.get(for_nodes[0].id)
if body_path is None:
return False
body_node_ids, return_node_id = body_path
@@ -1417,9 +1414,9 @@ 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()
+ loop_topology = self._loop_topology()
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)
+ serial_chain = loop_topology.nested_iterate_chain(outer_for.id)
if (
can_use_nested_iterate_planner(self)
and serial_chain is not None
@@ -1448,10 +1445,7 @@ class GraphExecutionState(BaseModel):
collect_node = collect_nodes[0]
return_node = return_nodes[0]
- if (
- not can_use_nested_iterate_planner(self)
- or self.graph._get_supported_for_nested_iterate_body(outer_for.id, source_graph) is None
- ):
+ if not can_use_nested_iterate_planner(self) or loop_topology.nested_iterate_body(outer_for.id) is None:
return False
iterate_collection_edges = self.graph._get_input_edges(iterate_node.id, COLLECTION_FIELD)
@@ -2049,9 +2043,7 @@ class GraphExecutionState(BaseModel):
and final_for_id == node.id
and self._is_loop_context_finalized(source_node_id, parent_iteration_path)
):
- body_path_to_return = self.graph._get_for_body_path_to_return(
- source_node_id, self._get_source_graph_flat()
- )
+ body_path_to_return = self._loop_topology().for_body_paths.get(source_node_id)
if body_path_to_return is not None:
_body_path_nodes, source_return_id = body_path_to_return
return_outputs = self._get_ordered_for_return_outputs(node.id, source_return_id)
@@ -3387,7 +3379,7 @@ class GraphExecutionState(BaseModel):
return
source_node_ids = {source_for_id}
- body_path_to_return = self.graph._get_for_body_path_to_return(source_for_id, self._get_source_graph_flat())
+ body_path_to_return = self._loop_topology().for_body_paths.get(source_for_id)
if body_path_to_return is not None:
body_path_nodes, _return_node_id = body_path_to_return
source_node_ids.update(body_path_nodes)
@@ -3601,6 +3593,7 @@ class GraphExecutionState(BaseModel):
self._prepared_if_exec_indexed_sources = set()
self._selected_if_frames_for_preparation = {}
self._source_graph_flat = None
+ self.__pydantic_private__["_runtime_state"].loop_topology = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
self._unexecuted_prepared_counts = None
@@ -4362,7 +4355,6 @@ _GRAPH_RUNTIME_ATTRIBUTE_NAMES = (
"execution_graph_flat",
"completed_source_ids_cache",
"unexecuted_prepared_counts",
- "for_source_by_return_id",
"apply_transaction",
"generic_execution_runtime",
"generic_graph_scheduler",
diff --git a/invokeai/app/services/shared/graph_if_activation.py b/invokeai/app/services/shared/graph_if_activation.py
index 1de7345e1d..86db0eb3c1 100644
--- a/invokeai/app/services/shared/graph_if_activation.py
+++ b/invokeai/app/services/shared/graph_if_activation.py
@@ -51,7 +51,7 @@ class _IfActivationController:
for_by_return_id: dict[str, str] = {}
if any(isinstance(self._state.graph.nodes.get(node_id), ForInvocation) for node_id in branch_sources):
return_id_by_for = {
- for_id: return_id for return_id, for_id in self._state._get_for_source_by_return_id().items()
+ for_id: return_id for return_id, for_id in self._state._loop_topology().for_id_by_return_id.items()
}
body_ids_by_for = {
for_id: nx.ancestors(source_graph, return_id) & nx.descendants(source_graph, for_id)
diff --git a/invokeai/app/services/shared/graph_loop_topology.py b/invokeai/app/services/shared/graph_loop_topology.py
new file mode 100644
index 0000000000..0618c0f8b2
--- /dev/null
+++ b/invokeai/app/services/shared/graph_loop_topology.py
@@ -0,0 +1,657 @@
+"""Loop topology: the For and nested-Iterate shapes of one source graph, classified once.
+
+Validation rejects For bodies whose shape is not classified here. Graph state, the schedulers, and the planners read the
+classification instead of re-running the recognizers for every completed node. The recognizers read only graph
+structure (node types and edges), so a topology stays valid exactly as long as the graph and the flat source graph it
+was built from.
+"""
+
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Callable, Mapping
+
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation
+from invokeai.app.services.shared.graph_validation import (
+ COLLECTION_FIELD,
+ ITEM_FIELD,
+ CollectInvocation,
+ Graph,
+ IterateInvocation,
+ nx,
+)
+
+if TYPE_CHECKING:
+ import networkx
+
+BodyPath = tuple[frozenset[str], str]
+"""The For body nodes on a path to the linked ForReturn (return included), and that ForReturn's id."""
+
+
+@dataclass(frozen=True)
+class NestedForBody:
+ """A For whose body contains direct child For loops, each with its own ForReturn."""
+
+ body_path_nodes: frozenset[str]
+ outer_return_id: str
+ inner_for_ids: tuple[str, ...]
+ continuation_nodes: frozenset[str]
+
+
+@dataclass(frozen=True)
+class NestedIterateBody:
+ """A For whose body is one internal Iterate collapsed by one Collect before the ForReturn."""
+
+ body_path_nodes: frozenset[str]
+ return_node_id: str
+ iterate_node_id: str
+ collect_node_id: str
+
+
+@dataclass(frozen=True)
+class NestedIterateChain:
+ """A For whose body is exactly two serial preparation/Iterate pairs, one body node, and one Collect."""
+
+ body_path_nodes: frozenset[str]
+ return_node_id: str
+ iterate_node_ids: tuple[str, str]
+ collect_node_id: str
+
+
+@dataclass(frozen=True)
+class NestedIterateSequence:
+ """A whole graph that is one source feeding a serial chain of preparation/Iterate pairs and one body node."""
+
+ body_path_nodes: frozenset[str]
+ source_node_id: str
+ iterate_node_ids: tuple[str, ...]
+ preparation_node_ids: tuple[str, ...]
+ body_node_id: str
+
+
+ForBodyShape = NestedForBody | NestedIterateBody | NestedIterateChain
+
+_CONTROL_TYPES = (
+ CallSavedWorkflowInvocation,
+ IfInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IterateInvocation,
+ CollectInvocation,
+)
+
+
+@dataclass(frozen=True, eq=False)
+class LoopTopology:
+ """Loop shapes of one source graph. `flat_graph` is the cache key: a state reuses a topology only while its flat
+ source graph is the one the topology was built from."""
+
+ flat_graph: "networkx.DiGraph"
+ for_body_paths: Mapping[str, BodyPath]
+ """Body path of every For whose linked ForReturn is reachable from an iteration output."""
+ for_body_shapes: Mapping[str, ForBodyShape]
+ """Supported nested body of each For that has one, in source node order."""
+ nested_iterate_sequence: NestedIterateSequence | None
+ for_id_by_return_id: Mapping[str, str]
+
+ @classmethod
+ def classify(cls, graph: Graph, flat_graph: "networkx.DiGraph") -> "LoopTopology":
+ """Classify every For once. `flat_graph` must be `graph.nx_graph_flat()` and acyclic."""
+ for_ids = [node_id for node_id, node in graph.nodes.items() if isinstance(node, ForInvocation)]
+ for_body_paths: dict[str, BodyPath] = {}
+ for for_id in for_ids:
+ body_path = graph._get_for_body_path_to_return(for_id, flat_graph)
+ if body_path is not None:
+ for_body_paths[for_id] = (frozenset(body_path[0]), body_path[1])
+
+ nested_for_bodies: dict[str, NestedForBody | None] = {}
+
+ def nested_for_body(for_id: str) -> NestedForBody | None:
+ if for_id not in nested_for_bodies:
+ nested_for_bodies[for_id] = _recognize_nested_for_body(
+ graph, flat_graph, for_id, for_body_paths, nested_for_body
+ )
+ return nested_for_bodies[for_id]
+
+ # The three shapes are mutually exclusive: the chain has two Iterates on its body path, the Iterate body one,
+ # and a nested For body none anywhere in its reachable body.
+ for_body_shapes: dict[str, ForBodyShape] = {}
+ for for_id in for_ids:
+ body_path = for_body_paths.get(for_id)
+ shape = (
+ (_recognize_nested_iterate_chain(graph, flat_graph, for_id, body_path) if body_path else None)
+ or (_recognize_nested_iterate_body(graph, flat_graph, for_id, body_path) if body_path else None)
+ or nested_for_body(for_id)
+ )
+ if shape is not None:
+ for_body_shapes[for_id] = shape
+
+ return cls(
+ flat_graph=flat_graph,
+ for_body_paths=MappingProxyType(for_body_paths),
+ for_body_shapes=MappingProxyType(for_body_shapes),
+ nested_iterate_sequence=_recognize_nested_iterate_sequence(graph),
+ for_id_by_return_id=MappingProxyType(
+ {return_id: for_id for for_id, (_, return_id) in for_body_paths.items()}
+ ),
+ )
+
+ # Immutable, and mappingproxy cannot be copied or pickled. A deep-copied state keeps this instance until its own
+ # flat graph (a copy) fails the cache-key check and it reclassifies.
+ def __copy__(self) -> "LoopTopology":
+ return self
+
+ def __deepcopy__(self, memo: dict[int, object]) -> "LoopTopology":
+ return self
+
+ def __reduce__(self) -> tuple[Callable[..., "LoopTopology"], tuple[object, ...]]:
+ # Pickling flat_graph alongside the state's flat graph keeps them one object, so the cache key still matches.
+ return _restore_loop_topology, (
+ self.flat_graph,
+ dict(self.for_body_paths),
+ dict(self.for_body_shapes),
+ self.nested_iterate_sequence,
+ dict(self.for_id_by_return_id),
+ )
+
+ def nested_for_body(self, for_id: str) -> NestedForBody | None:
+ shape = self.for_body_shapes.get(for_id)
+ return shape if isinstance(shape, NestedForBody) else None
+
+ def nested_iterate_body(self, for_id: str) -> NestedIterateBody | None:
+ shape = self.for_body_shapes.get(for_id)
+ return shape if isinstance(shape, NestedIterateBody) else None
+
+ def nested_iterate_chain(self, for_id: str) -> NestedIterateChain | None:
+ shape = self.for_body_shapes.get(for_id)
+ return shape if isinstance(shape, NestedIterateChain) else None
+
+
+def _restore_loop_topology(
+ flat_graph: "networkx.DiGraph",
+ for_body_paths: dict[str, BodyPath],
+ for_body_shapes: dict[str, ForBodyShape],
+ nested_iterate_sequence: NestedIterateSequence | None,
+ for_id_by_return_id: dict[str, str],
+) -> LoopTopology:
+ return LoopTopology(
+ flat_graph=flat_graph,
+ for_body_paths=MappingProxyType(for_body_paths),
+ for_body_shapes=MappingProxyType(for_body_shapes),
+ nested_iterate_sequence=nested_iterate_sequence,
+ for_id_by_return_id=MappingProxyType(for_id_by_return_id),
+ )
+
+
+def _recognize_nested_iterate_body(
+ graph: Graph, flat_graph: "networkx.DiGraph", node_id: str, body_path: BodyPath
+) -> NestedIterateBody | None:
+ """Recognize the bounded internal Iterate body.
+
+ Supported shape::
+
+ For.item -> Iterate.item -> body -> Collect.item
+ Collect.collection -> ForReturn.output
+
+ The Iterate and Collect nodes are scheduler-managed, so no other branch or final For output may escape this
+ body contract.
+ """
+ body_path_nodes, return_node_id = body_path
+ iterate_node_ids = [
+ body_node_id for body_node_id in body_path_nodes if isinstance(graph.get_node(body_node_id), IterateInvocation)
+ ]
+ collect_node_ids = [
+ body_node_id for body_node_id in body_path_nodes if isinstance(graph.get_node(body_node_id), CollectInvocation)
+ ]
+ if len(iterate_node_ids) != 1 or len(collect_node_ids) != 1:
+ return None
+
+ iterate_node_id = iterate_node_ids[0]
+ collect_node_id = collect_node_ids[0]
+ if not nx.has_path(flat_graph, iterate_node_id, collect_node_id):
+ return None
+ iterate_input_edges = graph._get_input_edges(iterate_node_id, COLLECTION_FIELD)
+ if len(iterate_input_edges) != 1:
+ return None
+ iterate_input_source_id = iterate_input_edges[0].source.node_id
+ if iterate_input_source_id != node_id and iterate_input_source_id not in body_path_nodes:
+ return None
+
+ return_output_edges = graph._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 any(
+ edge.destination.field != "output"
+ and edge.destination.field != "continue_condition"
+ and (edge.destination.field != "state" or edge.source.node_id != node_id or edge.source.field != "state")
+ for edge in graph._get_input_edges(return_node_id)
+ ):
+ return None
+
+ if graph._get_input_edges(collect_node_id, COLLECTION_FIELD):
+ return None
+ collect_item_edges = graph._get_input_edges(collect_node_id, ITEM_FIELD)
+ if len(collect_item_edges) != 1:
+ return None
+ collect_item_source_id = collect_item_edges[0].source.node_id
+ if not nx.has_path(flat_graph, iterate_node_id, collect_item_source_id):
+ return None
+
+ for body_node_id in body_path_nodes:
+ if body_node_id in {iterate_node_id, collect_node_id, return_node_id}:
+ continue
+ if not nx.has_path(flat_graph, body_node_id, collect_node_id):
+ return None
+ if not (
+ nx.has_path(flat_graph, body_node_id, iterate_node_id)
+ or nx.has_path(flat_graph, iterate_node_id, body_node_id)
+ ):
+ return None
+
+ return NestedIterateBody(
+ body_path_nodes=body_path_nodes,
+ return_node_id=return_node_id,
+ iterate_node_id=iterate_node_id,
+ collect_node_id=collect_node_id,
+ )
+
+
+def _recognize_nested_iterate_chain(
+ graph: Graph, flat_graph: "networkx.DiGraph", node_id: str, body_path: BodyPath
+) -> NestedIterateChain | None:
+ """Recognize the exact two-level serial Iterate body.
+
+ 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_nodes, return_node_id = body_path
+ iterate_node_ids = tuple(
+ body_node_id for body_node_id in body_path_nodes if isinstance(graph.get_node(body_node_id), IterateInvocation)
+ )
+ collect_node_ids = tuple(
+ body_node_id for body_node_id in body_path_nodes if isinstance(graph.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 = graph._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 graph._get_input_edges(collect_node_id, COLLECTION_FIELD):
+ return None
+ collect_item_edges = graph._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(flat_graph, node_id, iterate_id)
+ )
+ if not nx.has_path(flat_graph, first_iterate_id, second_iterate_id) or not nx.has_path(
+ flat_graph, second_iterate_id, collect_node_id
+ ):
+ return None
+ first_input_edges = graph._get_input_edges(first_iterate_id, COLLECTION_FIELD)
+ second_input_edges = graph._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
+
+ ordinary_nodes = {first_preparation_id, second_preparation_id, body_node_id}
+ if any(isinstance(graph.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 = graph._get_input_edges(first_preparation_id)
+ second_preparation_inputs = graph._get_input_edges(second_preparation_id)
+ body_inputs = graph._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 graph._get_output_edges(node_id, ITEM_FIELD) != first_preparation_inputs:
+ return None
+ if graph._get_output_edges(first_iterate_id, ITEM_FIELD) != second_preparation_inputs:
+ return None
+ if graph._get_output_edges(second_iterate_id, ITEM_FIELD) != body_inputs:
+ return None
+ if graph._get_output_edges(body_node_id) != collect_item_edges:
+ return None
+
+ return NestedIterateChain(
+ body_path_nodes=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 _recognize_nested_iterate_sequence(graph: Graph) -> NestedIterateSequence | None:
+ """Recognize a whole graph that is one exact serial nested-Iterate chain of two or more Iterates."""
+ # An n-Iterate chain has 2n + 1 nodes and 2n edges, so the edge count alone fixes the only possible depth.
+ if len(graph.edges) % 2:
+ return None
+ iterate_count = len(graph.edges) // 2
+ if iterate_count < 2 or len(graph.nodes) != iterate_count * 2 + 1:
+ return None
+ iterate_node_ids = tuple(node_id for node_id, node in graph.nodes.items() if isinstance(node, IterateInvocation))
+ if len(iterate_node_ids) != iterate_count:
+ return None
+ outer_candidates = [
+ node_id
+ for node_id in iterate_node_ids
+ if graph._get_input_edges(node_id, COLLECTION_FIELD)
+ and not graph._get_input_edges(graph._get_input_edges(node_id, COLLECTION_FIELD)[0].source.node_id)
+ ]
+ if len(outer_candidates) != 1:
+ return None
+
+ ordered_iterate_ids = [outer_candidates[0]]
+ preparation_node_ids: list[str] = []
+ source_node_id = graph._get_input_edges(ordered_iterate_ids[0], COLLECTION_FIELD)[0].source.node_id
+ remaining_iterate_ids = set(iterate_node_ids) - set(ordered_iterate_ids)
+ for _ in range(iterate_count - 1):
+ candidates: list[tuple[str, str]] = []
+ for candidate_id in remaining_iterate_ids:
+ collection_edges = graph._get_input_edges(candidate_id, COLLECTION_FIELD)
+ if len(collection_edges) != 1:
+ continue
+ preparation_id = collection_edges[0].source.node_id
+ preparation_inputs = graph._get_input_edges(preparation_id)
+ if (
+ len(preparation_inputs) == 1
+ and preparation_inputs[0].source.node_id == ordered_iterate_ids[-1]
+ and preparation_inputs[0].source.field == ITEM_FIELD
+ ):
+ candidates.append((candidate_id, preparation_id))
+ if len(candidates) != 1:
+ return None
+ next_iterate_id, preparation_id = candidates[0]
+ ordered_iterate_ids.append(next_iterate_id)
+ preparation_node_ids.append(preparation_id)
+ remaining_iterate_ids.remove(next_iterate_id)
+ if remaining_iterate_ids:
+ return None
+
+ body_candidates = [
+ node_id
+ for node_id in graph.nodes
+ if node_id not in set(ordered_iterate_ids) | set(preparation_node_ids) | {source_node_id}
+ ]
+ if len(body_candidates) != 1:
+ return None
+ body_node_id = body_candidates[0]
+ if any(
+ isinstance(graph.get_node(node_id), _CONTROL_TYPES)
+ for node_id in {source_node_id, *preparation_node_ids, body_node_id}
+ ):
+ return None
+ outer_collection_edges = graph._get_input_edges(ordered_iterate_ids[0], COLLECTION_FIELD)
+ body_inputs = graph._get_input_edges(body_node_id)
+ if graph._get_input_edges(source_node_id) or len(outer_collection_edges) != 1 or len(body_inputs) != 1:
+ return None
+ if graph._get_output_edges(source_node_id) != outer_collection_edges:
+ return None
+ for index, preparation_id in enumerate(preparation_node_ids):
+ preparation_inputs = graph._get_input_edges(preparation_id)
+ next_collection_edges = graph._get_input_edges(ordered_iterate_ids[index + 1], COLLECTION_FIELD)
+ if (
+ len(preparation_inputs) != 1
+ or preparation_inputs[0].source.node_id != ordered_iterate_ids[index]
+ or preparation_inputs[0].source.field != ITEM_FIELD
+ or len(next_collection_edges) != 1
+ or next_collection_edges[0].source.node_id != preparation_id
+ or graph._get_output_edges(ordered_iterate_ids[index], ITEM_FIELD) != preparation_inputs
+ or graph._get_output_edges(preparation_id) != next_collection_edges
+ ):
+ return None
+ if (
+ body_inputs[0].source.node_id != ordered_iterate_ids[-1]
+ or body_inputs[0].source.field != ITEM_FIELD
+ or graph._get_output_edges(ordered_iterate_ids[-1], ITEM_FIELD) != body_inputs
+ or graph._get_output_edges(body_node_id)
+ ):
+ return None
+ return NestedIterateSequence(
+ body_path_nodes=frozenset(graph.nodes),
+ source_node_id=source_node_id,
+ iterate_node_ids=tuple(ordered_iterate_ids),
+ preparation_node_ids=tuple(preparation_node_ids),
+ body_node_id=body_node_id,
+ )
+
+
+def _recognize_nested_for_body(
+ graph: Graph,
+ flat_graph: "networkx.DiGraph",
+ node_id: str,
+ for_body_paths: Mapping[str, BodyPath],
+ nested_for_body: Callable[[str], "NestedForBody | None"],
+) -> NestedForBody | None:
+ """Recognize the supported recursive nested For body.
+
+ Each direct child loop has its own ForReturn. A single child may close the parent directly or through a
+ continuation. Multiple independent child loops must all feed an ordinary parent-scoped continuation, which acts
+ as an explicit fan-in barrier after every child has finalized for the current parent iteration.
+
+ Accepted shape (the child body can recursively contain this same shape)::
+
+ outer For -> preparation -> inner For(s) -> continuation -> outer ForReturn
+ | ^
+ v |
+ child body -> inner ForReturn
+
+ Preparation, child bodies, and continuation partition the reachable outer body. Only finalized child outputs
+ may cross into the continuation; iteration outputs stay inside their owning child body. `nested_for_body`
+ resolves a child For's own nested body.
+ """
+ iteration_edges = graph._get_for_iteration_output_edges(node_id)
+ if len(iteration_edges) == 0:
+ return None
+ reachable_body_nodes = graph._get_for_reachable_body_nodes(iteration_edges, flat_graph)
+ reachable_return_ids = [
+ body_node_id
+ for body_node_id in reachable_body_nodes
+ if isinstance(graph.get_node(body_node_id), ForReturnInvocation)
+ ]
+ outer_return_id = graph._get_linked_for_return_id(node_id)
+ if outer_return_id is None or outer_return_id not in reachable_return_ids:
+ return None
+
+ nested_for_ids = [
+ body_node_id
+ for body_node_id in reachable_body_nodes
+ if isinstance(graph.get_node(body_node_id), ForInvocation) and body_node_id != node_id
+ ]
+ direct_nested_for_ids = [
+ nested_for_id
+ for nested_for_id in nested_for_ids
+ if not any(
+ other_nested_for_id != nested_for_id and nx.has_path(flat_graph, other_nested_for_id, nested_for_id)
+ for other_nested_for_id in nested_for_ids
+ )
+ ]
+ if not direct_nested_for_ids:
+ return None
+ direct_nested_for_ids = tuple(
+ nested_for_id for nested_for_id in nx.topological_sort(flat_graph) if nested_for_id in direct_nested_for_ids
+ )
+
+ inner_body_path_nodes: set[str] = set()
+ for inner_for_id in direct_nested_for_ids:
+ inner_return_id = graph._get_linked_for_return_id(inner_for_id)
+ if inner_return_id is None:
+ return None
+
+ inner_body_path_to_return = for_body_paths.get(inner_for_id)
+ if inner_body_path_to_return is None:
+ return None
+ child_body_path_nodes, resolved_inner_return_id = inner_body_path_to_return
+ if resolved_inner_return_id != inner_return_id:
+ return None
+ if inner_return_id not in reachable_return_ids:
+ return None
+
+ inner_nested_for_ids = [
+ body_node_id
+ for body_node_id in child_body_path_nodes
+ if isinstance(graph.get_node(body_node_id), ForInvocation)
+ ]
+ if any(isinstance(graph.get_node(body_node_id), IterateInvocation) for body_node_id in child_body_path_nodes):
+ return None
+ inner_nested_body = nested_for_body(inner_for_id) if inner_nested_for_ids else None
+ if inner_nested_for_ids and inner_nested_body is None:
+ return None
+ if inner_nested_body is not None:
+ child_body_path_nodes = child_body_path_nodes | inner_nested_body.body_path_nodes
+ if any(
+ edge.destination.field == "state"
+ and edge.source.node_id != inner_for_id
+ and edge.source.node_id not in child_body_path_nodes
+ for edge in graph._get_input_edges(inner_return_id)
+ ):
+ return None
+
+ inner_collection_edges = graph._get_input_edges(inner_for_id, COLLECTION_FIELD)
+ if len(inner_collection_edges) != 1:
+ return None
+ inner_collection_source_id = inner_collection_edges[0].source.node_id
+ if inner_collection_source_id != node_id and inner_collection_source_id not in reachable_body_nodes:
+ return None
+
+ inner_body_path_nodes.update(child_body_path_nodes)
+
+ if set(reachable_return_ids) - inner_body_path_nodes != {outer_return_id}:
+ return None
+
+ outer_output_edges = graph._get_input_edges(outer_return_id, "output")
+ if len(outer_output_edges) != 1:
+ return None
+ if any(
+ edge.destination.field != "output"
+ and edge.destination.field != "continue_condition"
+ and (edge.destination.field != "state" or edge.source.node_id != node_id or edge.source.field != "state")
+ for edge in graph._get_input_edges(outer_return_id)
+ ):
+ return None
+
+ outer_preparation_nodes = {
+ body_node_id
+ for inner_for_id in direct_nested_for_ids
+ for body_node_id in reachable_body_nodes & nx.ancestors(flat_graph, inner_for_id)
+ } | set(direct_nested_for_ids)
+ inner_final_descendants: set[str] = set()
+ for inner_for_id in direct_nested_for_ids:
+ for edge in graph._get_for_final_output_edges(inner_for_id):
+ inner_final_descendants.add(edge.destination.node_id)
+ inner_final_descendants.update(nx.descendants(flat_graph, edge.destination.node_id))
+ continuation_nodes = reachable_body_nodes - outer_preparation_nodes - inner_body_path_nodes - {outer_return_id}
+ if any(
+ edge.destination.field == "continue_condition"
+ and edge.source.node_id != node_id
+ and edge.source.node_id not in continuation_nodes
+ and not (
+ edge.source.node_id in direct_nested_for_ids and edge.source.field in {"output_collection", "final_state"}
+ )
+ for edge in graph._get_input_edges(outer_return_id)
+ ):
+ return None
+ if not continuation_nodes <= inner_final_descendants:
+ return None
+ if any(not nx.has_path(flat_graph, body_node_id, outer_return_id) for body_node_id in continuation_nodes):
+ return None
+ if any(
+ isinstance(graph.get_node(body_node_id), (ForInvocation, IterateInvocation, ForReturnInvocation))
+ for body_node_id in continuation_nodes
+ ):
+ return None
+ if any(
+ edge.source.node_id in inner_body_path_nodes
+ or (edge.source.node_id in direct_nested_for_ids and edge.source.field != "output_collection")
+ for body_node_id in continuation_nodes
+ for edge in graph._get_input_edges(body_node_id)
+ ):
+ return None
+ output_source_id = outer_output_edges[0].source.node_id
+ if output_source_id in direct_nested_for_ids:
+ if (
+ len(direct_nested_for_ids) != 1
+ or outer_output_edges[0].source.field != "output_collection"
+ or continuation_nodes
+ ):
+ return None
+ elif output_source_id not in continuation_nodes:
+ return None
+
+ if any(
+ not any(
+ edge.destination.node_id in continuation_nodes or edge.destination.node_id == outer_return_id
+ for edge in graph._get_for_final_output_edges(inner_for_id)
+ )
+ for inner_for_id in direct_nested_for_ids
+ ):
+ return None
+
+ allowed_body_nodes = outer_preparation_nodes | inner_body_path_nodes | continuation_nodes | {outer_return_id}
+ if reachable_body_nodes != allowed_body_nodes:
+ return None
+
+ if any(
+ isinstance(graph.get_node(body_node_id), (ForInvocation, IterateInvocation))
+ for body_node_id in outer_preparation_nodes
+ if body_node_id not in direct_nested_for_ids
+ ):
+ return None
+
+ for body_node_id in allowed_body_nodes - {outer_return_id, *direct_nested_for_ids}:
+ if body_node_id in inner_body_path_nodes or body_node_id in continuation_nodes:
+ continue
+ if not any(nx.has_path(flat_graph, body_node_id, inner_for_id) for inner_for_id in direct_nested_for_ids):
+ return None
+ return NestedForBody(
+ body_path_nodes=frozenset(allowed_body_nodes),
+ outer_return_id=outer_return_id,
+ inner_for_ids=direct_nested_for_ids,
+ continuation_nodes=frozenset(continuation_nodes),
+ )
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
index 5d8c8c1267..816fd4ddee 100644
--- a/invokeai/app/services/shared/graph_materializer.py
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -16,15 +16,13 @@ from invokeai.app.invocations.loops import (
from invokeai.app.services.shared import graph_if_runtime
from invokeai.app.services.shared.execution_engine.primitives import ActivationGate
from invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestry
+from invokeai.app.services.shared.graph_loop_topology import NestedForBody, NestedIterateBody, NestedIterateChain
from invokeai.app.services.shared.graph_models import Edge, EdgeConnection
from invokeai.app.services.shared.graph_validation import (
COLLECTION_FIELD,
ITEM_FIELD,
CollectInvocation,
IterateInvocation,
- _SupportedNestedForBody,
- _SupportedNestedIterateBody,
- _SupportedNestedIterateChain,
copydeep,
get_output_field_scope,
nx,
@@ -460,25 +458,24 @@ class _ExecutionNodeBuilder:
return new_node.id
def create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
- graph = self._state._get_source_graph_flat()
+ loop_topology = self._state._loop_topology()
+ graph = loop_topology.flat_graph
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:
+ body_shape = loop_topology.for_body_shapes.get(source_for_id)
+ if isinstance(body_shape, NestedIterateChain):
return self._create_serial_nested_iterate_body_iteration(
- source_for_id, prepared_for_id, graph, execution_graph, serial_nested_body
+ source_for_id, prepared_for_id, graph, execution_graph, body_shape
)
- nested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)
- if nested_body is not None:
+ if isinstance(body_shape, NestedIterateBody):
return self._create_nested_iterate_body_iteration(
- source_for_id, prepared_for_id, graph, execution_graph, nested_body
+ source_for_id, prepared_for_id, graph, execution_graph, body_shape
)
- nested_for_body = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
- if nested_for_body is not None:
+ if isinstance(body_shape, NestedForBody):
return self._create_nested_for_body_iteration(
- source_for_id, prepared_for_id, graph, execution_graph, nested_for_body
+ source_for_id, prepared_for_id, graph, execution_graph, body_shape
)
- body_path_to_return = self._state.graph._get_for_body_path_to_return(source_for_id, graph)
+ body_path_to_return = loop_topology.for_body_paths.get(source_for_id)
if body_path_to_return is None:
return None
@@ -529,12 +526,10 @@ class _ExecutionNodeBuilder:
return prepared_return_id
- def _is_deferred_nested_for_return(self, node_id: str, graph: "nx.DiGraph") -> bool:
+ def _is_deferred_nested_for_return(self, node_id: str) -> bool:
return any(
- (nested_body := self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)) is not None
- and nested_body.outer_return_id == node_id
- for source_for_id, source_node in self._state.graph.nodes.items()
- if isinstance(source_node, ForInvocation)
+ isinstance(body_shape, NestedForBody) and body_shape.outer_return_id == node_id
+ for body_shape in self._state._loop_topology().for_body_shapes.values()
)
def _get_final_prepared_for_id(self, source_for_id: str, parent_iteration_path: tuple[int, ...]) -> str:
@@ -546,15 +541,13 @@ class _ExecutionNodeBuilder:
return prepared_for_id
def create_nested_for_return(self, inner_for_id: str, prepared_inner_for_id: str) -> Optional[str]:
- graph = self._state._get_source_graph_flat()
+ loop_topology = self._state._loop_topology()
+ graph = loop_topology.flat_graph
inner_iteration_path = self._state._get_iteration_path(prepared_inner_for_id)
outer_for_id: Optional[str] = None
- nested_body: Optional[_SupportedNestedForBody] = None
- for source_for_id, source_node in self._state.graph.nodes.items():
- if not isinstance(source_node, ForInvocation):
- continue
- candidate = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
- if candidate is not None and inner_for_id in candidate.inner_for_ids:
+ nested_body: Optional[NestedForBody] = None
+ for source_for_id, candidate in loop_topology.for_body_shapes.items():
+ if isinstance(candidate, NestedForBody) and inner_for_id in candidate.inner_for_ids:
outer_for_id = source_for_id
nested_body = candidate
break
@@ -591,7 +584,7 @@ class _ExecutionNodeBuilder:
if existing_return_ids:
return existing_return_ids[0]
- continuation_nodes = self._state.graph._get_for_nested_for_continuation_nodes(nested_body)
+ continuation_nodes = nested_body.continuation_nodes
prepared_inner_ids: dict[str, str] = {inner_for_id: prepared_inner_for_id}
if any(
not self._state._is_loop_context_finalized(inner_id, outer_iteration_path)
@@ -720,7 +713,7 @@ class _ExecutionNodeBuilder:
self,
source_for_id: str,
prepared_for_id: str,
- nested_body: _SupportedNestedIterateChain,
+ nested_body: NestedIterateChain,
outer_iteration_path: tuple[int, ...],
body_prepared_ids: list[str],
) -> str:
@@ -781,7 +774,7 @@ class _ExecutionNodeBuilder:
prepared_for_id: str,
graph: "nx.DiGraph",
execution_graph: "nx.DiGraph",
- nested_body: _SupportedNestedIterateChain,
+ nested_body: NestedIterateChain,
) -> Optional[str]:
del execution_graph
outer_iteration_path = self._get_serial_nested_outer_path(prepared_for_id)
@@ -904,7 +897,7 @@ class _ExecutionNodeBuilder:
prepared_for_id: str,
graph: "nx.DiGraph",
execution_graph: "nx.DiGraph",
- nested_body: _SupportedNestedForBody,
+ nested_body: NestedForBody,
) -> Optional[str]:
"""Materialize one nested-For body at the owning outer iteration path.
@@ -1027,7 +1020,7 @@ class _ExecutionNodeBuilder:
prepared_for_id: str,
graph: "nx.DiGraph",
execution_graph: "nx.DiGraph",
- nested_body: _SupportedNestedIterateBody,
+ nested_body: NestedIterateBody,
) -> Optional[str]:
body_path_nodes = nested_body.body_path_nodes
source_return_id = nested_body.return_node_id
@@ -2424,7 +2417,7 @@ class _ExecutionNodeBuilder:
and node_id not in self._state.executed
and not (
isinstance(self._state.graph.get_node(node_id), ForReturnInvocation)
- and self._is_deferred_nested_for_return(node_id, g)
+ and self._is_deferred_nested_for_return(node_id)
)
and not self._has_unmaterializable_for_final_input(node_id)
and node_id not in deferred_root_collect_if_descendants
diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.py
index b75e684e91..81ae83f625 100644
--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py
+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py
@@ -10,12 +10,9 @@ from invokeai.app.services.shared.graph_iterate_planner import (
_create_direct_execution_node_copy,
_initialize_direct_execution_node,
)
+from invokeai.app.services.shared.graph_loop_topology import NestedIterateChain
from invokeai.app.services.shared.graph_models import Edge, EdgeConnection
-from invokeai.app.services.shared.graph_validation import (
- COLLECTION_FIELD,
- ITEM_FIELD,
- _SupportedNestedIterateChain,
-)
+from invokeai.app.services.shared.graph_validation import COLLECTION_FIELD, ITEM_FIELD
if TYPE_CHECKING:
from invokeai.app.services.shared.graph import GraphExecutionState
@@ -32,10 +29,9 @@ def _get_exact_nested_iterate_body(state: "GraphExecutionState"):
input_driven_outer = bool(outer_collection_edges)
expected_node_count = 8 if input_driven_outer else 7
expected_edge_count = 8 if input_driven_outer else 7
+ loop_topology = state._loop_topology()
if not input_driven_outer:
- serial_chain = state.graph._get_supported_for_serial_nested_iterate_chain(
- for_node.id, state._get_source_graph_flat()
- )
+ serial_chain = loop_topology.nested_iterate_chain(for_node.id)
if serial_chain is not None and len(state.graph.nodes) == 9 and len(state.graph.edges) == 9:
return for_node.id, serial_chain
if len(state.graph.nodes) != expected_node_count or len(state.graph.edges) != expected_edge_count:
@@ -59,7 +55,7 @@ def _get_exact_nested_iterate_body(state: "GraphExecutionState"):
or state.graph._get_output_edges(producer.id) != [outer_collection_edge]
):
return None
- nested_body = state.graph._get_supported_for_nested_iterate_body(for_node.id, state._get_source_graph_flat())
+ nested_body = loop_topology.nested_iterate_body(for_node.id)
if nested_body is None or len(nested_body.body_path_nodes) != 5:
return None
return for_node.id, nested_body
@@ -77,11 +73,10 @@ def get_nested_iterate_sequence_depth(state: "GraphExecutionState") -> int | Non
"""Return the exact supported fresh Iterate-only chain depth, if any."""
if state._legacy_snapshot_loaded:
return None
- source_graph = state._get_source_graph_flat()
- for depth in _SUPPORTED_NESTED_ITERATE_SEQUENCE_DEPTHS:
- if state.graph._get_supported_nested_iterate_sequence(source_graph, iterate_count=depth) is not None:
- return depth
- return None
+ sequence = state._loop_topology().nested_iterate_sequence
+ if sequence is None or len(sequence.iterate_node_ids) not in _SUPPORTED_NESTED_ITERATE_SEQUENCE_DEPTHS:
+ return None
+ return len(sequence.iterate_node_ids)
def _outer_iteration_path(state: "GraphExecutionState", prepared_for_id: str) -> tuple[int, ...]:
@@ -103,7 +98,7 @@ 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):
+ if isinstance(nested_body, NestedIterateChain):
_prepare_serial_nested_iterate_chain_for_outer(state, source_for_id, prepared_for_id, nested_body)
return
outer_path = _outer_iteration_path(state, prepared_for_id)
@@ -213,7 +208,7 @@ def _prepare_serial_nested_iterate_chain_for_outer(
state: "GraphExecutionState",
source_for_id: str,
prepared_for_id: str,
- nested_body: _SupportedNestedIterateChain,
+ nested_body: NestedIterateChain,
) -> None:
"""Prepare one exact serial two-level nested iterator body incrementally."""
outer_path = _outer_iteration_path(state, prepared_for_id)
@@ -396,11 +391,10 @@ def prepare_nested_iterate_bodies(state: "GraphExecutionState") -> None:
_prepare_nested_iterate_body_for_outer(state, source_for_id, prepared_for_id)
-def _prepare_nested_iterate_sequence(state: "GraphExecutionState", *, iterate_count: int) -> None:
- nested = state.graph._get_supported_nested_iterate_sequence(
- state._get_source_graph_flat(), iterate_count=iterate_count
- )
+def _prepare_nested_iterate_sequence(state: "GraphExecutionState") -> None:
+ nested = state._loop_topology().nested_iterate_sequence
assert nested is not None
+ iterate_count = len(nested.iterate_node_ids)
def prepared_at_path(source_node_id: str, path: tuple[int, ...]) -> str | None:
return state._prepared_registry().get_prepared_id_at_path(source_node_id, path)
@@ -517,4 +511,4 @@ def prepare_nested_iterate_sequence(state: "GraphExecutionState", *, depth: int
if depth is None:
depth = get_nested_iterate_sequence_depth(state)
if depth is not None:
- _prepare_nested_iterate_sequence(state, iterate_count=depth)
+ _prepare_nested_iterate_sequence(state)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index f910a1e3e9..af98a39df8 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -10,6 +10,7 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionPlan,
ExecutionScheduler,
)
+from invokeai.app.services.shared.graph_loop_topology import NestedForBody, NestedIterateChain
from invokeai.app.services.shared.graph_nested_iterate_planner import (
can_use_nested_iterate_planner,
get_nested_iterate_sequence_depth,
@@ -32,13 +33,12 @@ def _prepare_deferred_nested_for_body(
"""Prepare a deferred nested For body through the caller's node planner."""
completed_source_id = state._prepared_registry().get_source_node_id(exec_node_id)
- graph = state._get_source_graph_flat()
- for source_for_id, source_node in state.graph.nodes.items():
- if not isinstance(source_node, ForInvocation):
- continue
- serial_nested_body = 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:
+ loop_topology = state._loop_topology()
+ graph = loop_topology.flat_graph
+ # Fors without a nested body shape have nothing deferred.
+ for source_for_id, body_shape in loop_topology.for_body_shapes.items():
+ if isinstance(body_shape, NestedIterateChain):
+ if completed_source_id not in body_shape.body_path_nodes:
continue
prepared_exec_path = state._get_iteration_path(exec_node_id)
for prepared_for_id in state._prepared_registry().get_prepared_ids(source_for_id):
@@ -52,18 +52,12 @@ def _prepare_deferred_nested_for_body(
if prepared_exec_path[: len(prepared_for_path)] == prepared_for_path:
planner.create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=prepared_for_id)
return
- nested_body = state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)
- nested_for_body = state.graph._get_supported_for_nested_for_body(source_for_id, graph)
- if nested_body is not None:
- body_path_nodes = nested_body.body_path_nodes
- deferred_node_ids = (nested_body.iterate_node_id,)
- elif nested_for_body is None:
continue
- else:
- body_path_nodes = nested_for_body.body_path_nodes
- deferred_node_ids = nested_for_body.inner_for_ids
+ deferred_node_ids = (
+ body_shape.inner_for_ids if isinstance(body_shape, NestedForBody) else (body_shape.iterate_node_id,)
+ )
if completed_source_id != source_for_id and (
- completed_source_id not in body_path_nodes
+ completed_source_id not in body_shape.body_path_nodes
or not any(
nx.has_path(graph, completed_source_id, deferred_node_id) for deferred_node_id in deferred_node_ids
)
@@ -79,7 +73,7 @@ def _prepare_deferred_nested_for_body(
)
if prepared_for_path != state._get_iteration_path(exec_node_id):
continue
- if nested_for_body is not None:
+ if isinstance(body_shape, NestedForBody):
if not all(
any(
state._get_for_parent_iteration_path(prepared_child_id) == prepared_for_path
@@ -310,9 +304,7 @@ class _ExecutionScheduler:
completed_node = self._state.execution_graph.get_node(exec_node_id)
if isinstance(completed_node, ForInvocation) and completed_node.index >= 0:
source_for_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
- nested_body = self._state.graph._get_supported_for_nested_iterate_body(
- source_for_id, self._state._get_source_graph_flat()
- )
+ nested_body = self._state._loop_topology().nested_iterate_body(source_for_id)
prepared_for_node = self._state.execution_graph.get_node(exec_node_id)
prepared_for_path = self._state._get_iteration_path(exec_node_id)
if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index da48151e76..4e3a3e956e 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -3,7 +3,6 @@ import itertools
import sys
import weakref
from contextvars import ContextVar
-from dataclasses import dataclass
from functools import wraps
from types import UnionType
from typing import (
@@ -53,6 +52,8 @@ load_all_modules()
if TYPE_CHECKING:
import networkx as nx
+
+ from invokeai.app.services.shared.graph_loop_topology import LoopTopology
else:
_FACADE_MODULE_NAME = "invokeai.app.services.shared.graph"
@@ -119,39 +120,6 @@ def _get_facade_override(name: str, implementation: Callable[..., Any]) -> Calla
return dispatch
-@dataclass(frozen=True)
-class _SupportedNestedForBody:
- body_path_nodes: frozenset[str]
- outer_return_id: str
- inner_for_ids: tuple[str, ...]
- continuation_nodes: frozenset[str]
-
-
-@dataclass(frozen=True)
-class _SupportedNestedIterateBody:
- body_path_nodes: set[str]
- return_node_id: str
- iterate_node_id: str
- 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
-
-
-@dataclass(frozen=True)
-class _SupportedNestedIterateSequence:
- body_path_nodes: frozenset[str]
- source_node_id: str
- iterate_node_ids: tuple[str, ...]
- preparation_node_ids: tuple[str, ...]
- body_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:
@@ -977,6 +945,17 @@ class Graph(BaseModel):
def _validate_special_nodes(self, collector_input_types_cache: _CollectorInputTypesCache) -> None:
# TODO: may need to validate all iterators & collectors in subgraphs so edge connections in parent graphs will be available
self._validate_for_loop_linkages()
+ loop_topology: "LoopTopology | None" = None
+
+ def get_loop_topology() -> "LoopTopology":
+ nonlocal loop_topology
+ if loop_topology is None:
+ # Imported here only to break the cycle: graph_loop_topology imports this module.
+ from invokeai.app.services.shared.graph_loop_topology import LoopTopology
+
+ loop_topology = LoopTopology.classify(self, self.nx_graph_flat())
+ return loop_topology
+
for node in self.nodes.values():
if isinstance(node, IterateInvocation):
err = self._is_iterator_connection_valid(
@@ -991,11 +970,11 @@ class Graph(BaseModel):
if err is not None:
raise InvalidEdgeError(f"Invalid collector node ({node.id}): {err}")
if isinstance(node, ForInvocation):
- err = self._is_for_connection_valid(node.id)
+ err = self._is_for_connection_valid(node.id, get_loop_topology())
if err is not None:
raise InvalidEdgeError(f"Invalid For node ({node.id}): {err}")
if isinstance(node, ForReturnInvocation):
- err = self._is_for_return_connection_valid(node.id)
+ err = self._is_for_return_connection_valid(node.id, get_loop_topology())
if err is not None:
raise InvalidEdgeError(f"Invalid ForReturn node ({node.id}): {err}")
@@ -1371,511 +1350,7 @@ class Graph(BaseModel):
return self._get_for_body_path_nodes(reachable_body_nodes, return_node_id, graph), return_node_id
- def _get_supported_for_nested_iterate_body(
- self, node_id: str, graph: "nx.DiGraph"
- ) -> _SupportedNestedIterateBody | None:
- """Return the bounded internal Iterate body contract, if this For uses it.
-
- Supported shape::
-
- For.item -> Iterate.item -> body -> Collect.item
- Collect.collection -> ForReturn.output
-
- The Iterate and Collect nodes are scheduler-managed, so no other branch or final For output may escape this
- body contract.
- """
- 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 = [
- body_node_id
- for body_node_id in body_path_nodes
- if isinstance(self.get_node(body_node_id), IterateInvocation)
- ]
- collect_node_ids = [
- 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) != 1 or len(collect_node_ids) != 1:
- return None
-
- iterate_node_id = iterate_node_ids[0]
- collect_node_id = collect_node_ids[0]
- if not nx.has_path(graph, iterate_node_id, collect_node_id):
- return None
- iterate_input_edges = self._get_input_edges(iterate_node_id, COLLECTION_FIELD)
- if len(iterate_input_edges) != 1:
- return None
- iterate_input_source_id = iterate_input_edges[0].source.node_id
- if iterate_input_source_id != node_id and iterate_input_source_id not in body_path_nodes:
- 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 any(
- edge.destination.field != "output"
- and edge.destination.field != "continue_condition"
- and (edge.destination.field != "state" or edge.source.node_id != node_id or edge.source.field != "state")
- for edge in self._get_input_edges(return_node_id)
- ):
- 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
- collect_item_source_id = collect_item_edges[0].source.node_id
- if not nx.has_path(graph, iterate_node_id, collect_item_source_id):
- return None
-
- for body_node_id in body_path_nodes:
- if body_node_id in {iterate_node_id, collect_node_id, return_node_id}:
- continue
- if not nx.has_path(graph, body_node_id, collect_node_id):
- return None
- if not (
- nx.has_path(graph, body_node_id, iterate_node_id) or nx.has_path(graph, iterate_node_id, body_node_id)
- ):
- return None
-
- return _SupportedNestedIterateBody(
- body_path_nodes=body_path_nodes,
- return_node_id=return_node_id,
- iterate_node_id=iterate_node_id,
- 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_nested_iterate_sequence(
- self, graph: "nx.DiGraph", *, iterate_count: int = 2
- ) -> _SupportedNestedIterateSequence | None:
- """Return exact serial nested-Iterate chain of requested depth, if present."""
- if iterate_count < 2 or len(self.nodes) != iterate_count * 2 + 1 or len(self.edges) != iterate_count * 2:
- return None
- iterate_node_ids = tuple(node_id for node_id, node in self.nodes.items() if isinstance(node, IterateInvocation))
- if len(iterate_node_ids) != iterate_count:
- return None
- outer_candidates = [
- node_id
- for node_id in iterate_node_ids
- if self._get_input_edges(node_id, COLLECTION_FIELD)
- and not self._get_input_edges(self._get_input_edges(node_id, COLLECTION_FIELD)[0].source.node_id)
- ]
- if len(outer_candidates) != 1:
- return None
-
- ordered_iterate_ids = [outer_candidates[0]]
- preparation_node_ids: list[str] = []
- source_node_id = self._get_input_edges(ordered_iterate_ids[0], COLLECTION_FIELD)[0].source.node_id
- remaining_iterate_ids = set(iterate_node_ids) - set(ordered_iterate_ids)
- for _ in range(iterate_count - 1):
- candidates: list[tuple[str, str]] = []
- for candidate_id in remaining_iterate_ids:
- collection_edges = self._get_input_edges(candidate_id, COLLECTION_FIELD)
- if len(collection_edges) != 1:
- continue
- preparation_id = collection_edges[0].source.node_id
- preparation_inputs = self._get_input_edges(preparation_id)
- if (
- len(preparation_inputs) == 1
- and preparation_inputs[0].source.node_id == ordered_iterate_ids[-1]
- and preparation_inputs[0].source.field == ITEM_FIELD
- ):
- candidates.append((candidate_id, preparation_id))
- if len(candidates) != 1:
- return None
- next_iterate_id, preparation_id = candidates[0]
- ordered_iterate_ids.append(next_iterate_id)
- preparation_node_ids.append(preparation_id)
- remaining_iterate_ids.remove(next_iterate_id)
- if remaining_iterate_ids:
- return None
-
- body_candidates = [
- node_id
- for node_id in self.nodes
- if node_id not in set(ordered_iterate_ids) | set(preparation_node_ids) | {source_node_id}
- ]
- if len(body_candidates) != 1:
- return None
- body_node_id = body_candidates[0]
- control_types = (
- CallSavedWorkflowInvocation,
- IfInvocation,
- ForInvocation,
- ForReturnInvocation,
- CollectInvocation,
- IterateInvocation,
- )
- if any(
- isinstance(self.get_node(node_id), control_types)
- for node_id in {source_node_id, *preparation_node_ids, body_node_id}
- ):
- return None
- outer_collection_edges = self._get_input_edges(ordered_iterate_ids[0], COLLECTION_FIELD)
- body_inputs = self._get_input_edges(body_node_id)
- if self._get_input_edges(source_node_id) or len(outer_collection_edges) != 1 or len(body_inputs) != 1:
- return None
- if self._get_output_edges(source_node_id) != outer_collection_edges:
- return None
- for index, preparation_id in enumerate(preparation_node_ids):
- preparation_inputs = self._get_input_edges(preparation_id)
- next_collection_edges = self._get_input_edges(ordered_iterate_ids[index + 1], COLLECTION_FIELD)
- if (
- len(preparation_inputs) != 1
- or preparation_inputs[0].source.node_id != ordered_iterate_ids[index]
- or preparation_inputs[0].source.field != ITEM_FIELD
- or len(next_collection_edges) != 1
- or next_collection_edges[0].source.node_id != preparation_id
- or self._get_output_edges(ordered_iterate_ids[index], ITEM_FIELD) != preparation_inputs
- or self._get_output_edges(preparation_id) != next_collection_edges
- ):
- return None
- if (
- body_inputs[0].source.node_id != ordered_iterate_ids[-1]
- or body_inputs[0].source.field != ITEM_FIELD
- or self._get_output_edges(ordered_iterate_ids[-1], ITEM_FIELD) != body_inputs
- or self._get_output_edges(body_node_id)
- ):
- return None
- return _SupportedNestedIterateSequence(
- body_path_nodes=frozenset(self.nodes),
- source_node_id=source_node_id,
- iterate_node_ids=tuple(ordered_iterate_ids),
- preparation_node_ids=tuple(preparation_node_ids),
- body_node_id=body_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.
-
- Each direct child loop has its own ForReturn. A single child may close the parent directly or through a
- continuation. Multiple independent child loops must all feed an ordinary parent-scoped continuation, which acts
- as an explicit fan-in barrier after every child has finalized for the current parent iteration.
-
- Accepted shape (the child body can recursively contain this same shape)::
-
- outer For -> preparation -> inner For(s) -> continuation -> outer ForReturn
- | ^
- v |
- child body -> inner ForReturn
-
- Preparation, child bodies, and continuation partition the reachable outer body. Only finalized child outputs
- may cross into the continuation; iteration outputs stay inside their owning child body.
- """
- outer_node = self.get_node(node_id)
- if not isinstance(outer_node, ForInvocation):
- return None
-
- iteration_edges = self._get_for_iteration_output_edges(node_id)
- if len(iteration_edges) == 0:
- return None
- reachable_body_nodes = self._get_for_reachable_body_nodes(iteration_edges, graph)
- reachable_return_ids = [
- body_node_id
- for body_node_id in reachable_body_nodes
- if isinstance(self.get_node(body_node_id), ForReturnInvocation)
- ]
- outer_return_id = self._get_linked_for_return_id(node_id)
- if outer_return_id is None or outer_return_id not in reachable_return_ids:
- return None
-
- nested_for_ids = [
- body_node_id
- for body_node_id in reachable_body_nodes
- if isinstance(self.get_node(body_node_id), ForInvocation) and body_node_id != node_id
- ]
- direct_nested_for_ids = [
- nested_for_id
- for nested_for_id in nested_for_ids
- if not any(
- other_nested_for_id != nested_for_id and nx.has_path(graph, other_nested_for_id, nested_for_id)
- for other_nested_for_id in nested_for_ids
- )
- ]
- if not direct_nested_for_ids:
- return None
- direct_nested_for_ids = tuple(
- nested_for_id for nested_for_id in nx.topological_sort(graph) if nested_for_id in direct_nested_for_ids
- )
-
- inner_body_path_nodes: set[str] = set()
- for inner_for_id in direct_nested_for_ids:
- inner_for = self.get_node(inner_for_id)
- assert isinstance(inner_for, ForInvocation)
- inner_return_id = self._get_linked_for_return_id(inner_for_id)
- if inner_return_id is None:
- return None
-
- inner_body_path_to_return = self._get_for_body_path_to_return(inner_for_id, graph)
- if inner_body_path_to_return is None:
- return None
- child_body_path_nodes, resolved_inner_return_id = inner_body_path_to_return
- if resolved_inner_return_id != inner_return_id:
- return None
- if inner_return_id not in reachable_return_ids:
- return None
-
- inner_nested_for_ids = [
- body_node_id
- for body_node_id in child_body_path_nodes
- if isinstance(self.get_node(body_node_id), ForInvocation)
- ]
- if any(
- isinstance(self.get_node(body_node_id), IterateInvocation) for body_node_id in child_body_path_nodes
- ):
- return None
- inner_nested_body = (
- self._get_supported_for_nested_for_body(inner_for_id, graph) if inner_nested_for_ids else None
- )
- if inner_nested_for_ids and inner_nested_body is None:
- return None
- if inner_nested_body is not None:
- child_body_path_nodes = child_body_path_nodes | inner_nested_body.body_path_nodes
- if any(
- edge.destination.field == "state"
- and edge.source.node_id != inner_for_id
- and edge.source.node_id not in child_body_path_nodes
- for edge in self._get_input_edges(inner_return_id)
- ):
- return None
-
- inner_collection_edges = self._get_input_edges(inner_for_id, COLLECTION_FIELD)
- if len(inner_collection_edges) != 1:
- return None
- inner_collection_source_id = inner_collection_edges[0].source.node_id
- if inner_collection_source_id != node_id and inner_collection_source_id not in reachable_body_nodes:
- return None
-
- inner_body_path_nodes.update(child_body_path_nodes)
-
- if set(reachable_return_ids) - inner_body_path_nodes != {outer_return_id}:
- return None
-
- outer_output_edges = self._get_input_edges(outer_return_id, "output")
- if len(outer_output_edges) != 1:
- return None
- if any(
- edge.destination.field != "output"
- and edge.destination.field != "continue_condition"
- and (edge.destination.field != "state" or edge.source.node_id != node_id or edge.source.field != "state")
- for edge in self._get_input_edges(outer_return_id)
- ):
- return None
-
- outer_preparation_nodes = {
- body_node_id
- for inner_for_id in direct_nested_for_ids
- for body_node_id in reachable_body_nodes & nx.ancestors(graph, inner_for_id)
- } | set(direct_nested_for_ids)
- inner_final_descendants: set[str] = set()
- for inner_for_id in direct_nested_for_ids:
- for edge in self._get_for_final_output_edges(inner_for_id):
- inner_final_descendants.add(edge.destination.node_id)
- inner_final_descendants.update(nx.descendants(graph, edge.destination.node_id))
- continuation_nodes = reachable_body_nodes - outer_preparation_nodes - inner_body_path_nodes - {outer_return_id}
- if any(
- edge.destination.field == "continue_condition"
- and edge.source.node_id != node_id
- and edge.source.node_id not in continuation_nodes
- and not (
- edge.source.node_id in direct_nested_for_ids
- and edge.source.field in {"output_collection", "final_state"}
- )
- for edge in self._get_input_edges(outer_return_id)
- ):
- return None
- if not continuation_nodes <= inner_final_descendants:
- return None
- if any(not nx.has_path(graph, body_node_id, outer_return_id) for body_node_id in continuation_nodes):
- return None
- if any(
- isinstance(self.get_node(body_node_id), (ForInvocation, IterateInvocation, ForReturnInvocation))
- for body_node_id in continuation_nodes
- ):
- return None
- if any(
- edge.source.node_id in inner_body_path_nodes
- or (edge.source.node_id in direct_nested_for_ids and edge.source.field != "output_collection")
- for body_node_id in continuation_nodes
- for edge in self._get_input_edges(body_node_id)
- ):
- return None
- output_source_id = outer_output_edges[0].source.node_id
- if output_source_id in direct_nested_for_ids:
- if (
- len(direct_nested_for_ids) != 1
- or outer_output_edges[0].source.field != "output_collection"
- or continuation_nodes
- ):
- return None
- elif output_source_id not in continuation_nodes:
- return None
-
- if any(
- not any(
- edge.destination.node_id in continuation_nodes or edge.destination.node_id == outer_return_id
- for edge in self._get_for_final_output_edges(inner_for_id)
- )
- for inner_for_id in direct_nested_for_ids
- ):
- return None
-
- allowed_body_nodes = outer_preparation_nodes | inner_body_path_nodes | continuation_nodes | {outer_return_id}
- if reachable_body_nodes != allowed_body_nodes:
- return None
-
- if any(
- isinstance(self.get_node(body_node_id), (ForInvocation, IterateInvocation))
- for body_node_id in outer_preparation_nodes
- if body_node_id not in direct_nested_for_ids
- ):
- return None
-
- for body_node_id in allowed_body_nodes - {outer_return_id, *direct_nested_for_ids}:
- if body_node_id in inner_body_path_nodes or body_node_id in continuation_nodes:
- continue
- if not any(nx.has_path(graph, body_node_id, inner_for_id) for inner_for_id in direct_nested_for_ids):
- return None
- return _SupportedNestedForBody(
- body_path_nodes=frozenset(allowed_body_nodes),
- outer_return_id=outer_return_id,
- inner_for_ids=direct_nested_for_ids,
- continuation_nodes=frozenset(continuation_nodes),
- )
-
- def _get_for_nested_for_continuation_nodes(self, nested_body: _SupportedNestedForBody) -> set[str]:
- return set(nested_body.continuation_nodes)
-
- def _is_for_connection_valid(self, node_id: str) -> str | None:
+ def _is_for_connection_valid(self, node_id: str, loop_topology: "LoopTopology") -> str | None:
if len(self._get_input_edges(node_id, COLLECTION_FIELD)) > 1:
return "For loop may have only one collection input edge"
if len(self._get_input_edges(node_id, "state")) > 1:
@@ -1885,7 +1360,7 @@ class Graph(BaseModel):
if len(iteration_edges) == 0:
return "For loop must have at least one iteration output edge"
- graph = self.nx_graph_flat()
+ graph = loop_topology.flat_graph
reachable_body_nodes = self._get_for_reachable_body_nodes(iteration_edges, graph)
nested_for_node_ids = [
@@ -1900,7 +1375,7 @@ class Graph(BaseModel):
for other_body_node_id in reachable_body_nodes
)
]
- nested_body = self._get_supported_for_nested_for_body(node_id, graph) if nested_for_node_ids else None
+ nested_body = loop_topology.nested_for_body(node_id) if nested_for_node_ids else None
if nested_for_node_ids and nested_body is None:
return "Nested For loops require one linked inner For with a matching ForReturn"
@@ -1919,8 +1394,8 @@ class Graph(BaseModel):
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
- and self._get_supported_for_serial_nested_iterate_chain(node_id, graph) is None
+ loop_topology.nested_iterate_body(node_id) is None
+ and loop_topology.nested_iterate_chain(node_id) is None
):
return "Iterate nodes inside For loop bodies are unsupported"
@@ -1948,19 +1423,12 @@ class Graph(BaseModel):
return None
- def _is_for_return_connection_valid(self, node_id: str) -> str | None:
- graph = self.nx_graph_flat()
- matching_for_node_ids = []
- for loop_node_id, loop_node in self.nodes.items():
- if not isinstance(loop_node, ForInvocation):
- continue
- body_path_to_return = self._get_for_body_path_to_return(loop_node_id, graph)
- if body_path_to_return is None:
- continue
- body_path_nodes, return_node_id = body_path_to_return
- if node_id == return_node_id and node_id in body_path_nodes:
- matching_for_node_ids.append(loop_node_id)
-
+ def _is_for_return_connection_valid(self, node_id: str, loop_topology: "LoopTopology") -> str | None:
+ matching_for_node_ids = [
+ loop_node_id
+ for loop_node_id, (_body_path_nodes, return_node_id) in loop_topology.for_body_paths.items()
+ if return_node_id == node_id
+ ]
if len(matching_for_node_ids) != 1:
return "ForReturn must belong to exactly one matching For"
diff --git a/tests/app/services/session_processor/test_if_processor_sqlite.py b/tests/app/services/session_processor/test_if_processor_sqlite.py
index effa5ea349..8353409530 100644
--- a/tests/app/services/session_processor/test_if_processor_sqlite.py
+++ b/tests/app/services/session_processor/test_if_processor_sqlite.py
@@ -23,6 +23,9 @@ from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from tests.fixtures.sqlite_database import sqlite_cursor_of
from tests.test_nodes import create_edge
+# These waits bound hangs, not processor latency on contended CI workers.
+_PROCESSOR_TIMEOUT = 30
+
class _RecordingRegisteredEventService(EventServiceBase):
def __init__(self) -> None:
@@ -35,7 +38,7 @@ class _RecordingRegisteredEventService(EventServiceBase):
self._events_condition.notify_all()
asyncio.run(local_handler.handle((event.__event_name__, event)))
- def wait_for_status(self, item_id: int, status: str, timeout: float = 5) -> bool:
+ def wait_for_status(self, item_id: int, status: str, timeout: float = _PROCESSOR_TIMEOUT) -> bool:
def has_status() -> bool:
return any(
isinstance(event, QueueItemStatusChangedEvent) and event.item_id == item_id and event.status == status
@@ -127,7 +130,7 @@ def _stop_processor(processor: DefaultSessionProcessor) -> None:
processor.stop()
for worker in processor._workers:
assert worker.thread is not None
- worker.thread.join(timeout=5)
+ worker.thread.join(timeout=_PROCESSOR_TIMEOUT)
assert not worker.thread.is_alive()
@@ -156,7 +159,6 @@ def test_if_cancellation_preserves_activation_and_never_resumes_unselected_branc
unselected_branch: str,
selected_field: str,
) -> None:
- test_timeout = 30
queue = SessionQueue(mock_sqlite_database)
mock_invoker.services.events = registered_event_bus
mock_invoker.services.session_queue = queue
@@ -183,8 +185,8 @@ def test_if_cancellation_preserves_activation_and_never_resumes_unselected_branc
)
try:
processor.start(mock_invoker)
- assert registered_event_bus.wait_for_status(item_id, "canceled", timeout=test_timeout)
- assert session_persisted.wait(timeout=test_timeout)
+ assert registered_event_bus.wait_for_status(item_id, "canceled", timeout=_PROCESSOR_TIMEOUT)
+ assert session_persisted.wait(timeout=_PROCESSOR_TIMEOUT)
queue_item = queue.get_queue_item(item_id)
assert queue_item.status == "canceled"
@@ -248,7 +250,7 @@ def test_if_retry_starts_fresh_and_preserves_selected_output_without_stale_activ
try:
processor.start(mock_invoker)
assert registered_event_bus.wait_for_status(item_id, "canceled")
- assert session_persisted.wait(timeout=5)
+ assert session_persisted.wait(timeout=_PROCESSOR_TIMEOUT)
finally:
_stop_processor(processor)
@@ -324,7 +326,7 @@ def test_if_early_cancellation_before_resolution_does_not_run_any_branch_continu
try:
processor.start(mock_invoker)
assert registered_event_bus.wait_for_status(item_id, "canceled")
- assert session_persisted.wait(timeout=5)
+ assert session_persisted.wait(timeout=_PROCESSOR_TIMEOUT)
finally:
_stop_processor(processor)
diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.py
index 74b8f59cc5..a5ccc3a12f 100644
--- a/tests/app/services/shared/test_for_scheduler_performance.py
+++ b/tests/app/services/shared/test_for_scheduler_performance.py
@@ -25,7 +25,14 @@ from invokeai.app.services.shared.graph import (
_ExecutionScheduler,
_GenericGraphSchedulerAdapter,
)
-from tests.test_nodes import AnyTypeTestInvocation, FixedCollectionTestInvocation, create_edge, create_loop_linkage
+from invokeai.app.services.shared.graph_loop_topology import LoopTopology
+from tests.test_nodes import (
+ AnyTypeTestInvocation,
+ FixedCollectionTestInvocation,
+ PolymorphicStringTestInvocation,
+ create_edge,
+ create_loop_linkage,
+)
class _MappingTraversalCounter:
@@ -521,6 +528,66 @@ def test_prepared_execution_count_scans_each_source_once() -> None:
assert counter.visits_by_mapping == {"source_prepared_mapping": 1, "prepared_node_ids": 3}
+def _nested_loop_graph(body_type: str, outer_count: int) -> Graph:
+ graph = Graph()
+ graph.add_node(ForInvocation(id="outer", collection=[["a", "b"]] * outer_count))
+ graph.add_node(ForReturnInvocation(id="outer_return"))
+ if body_type == "for":
+ graph.add_node(ForInvocation(id="inner"))
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+ graph.add_node(ForReturnInvocation(id="inner_return"))
+ graph.add_edge(create_edge("outer", "item", "inner", "collection"))
+ graph.add_edge(create_edge("inner", "item", "body", "value"))
+ graph.add_edge(create_edge("body", "value", "inner_return", "output"))
+ graph.add_edge(create_edge("inner", "output_collection", "outer_return", "output"))
+ graph.add_edge(create_loop_linkage("inner", "inner_return"))
+ else:
+ graph.add_node(PolymorphicStringTestInvocation(id="prep"))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("outer", "item", "prep", "value"))
+ graph.add_edge(create_edge("prep", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "body", "value"))
+ graph.add_edge(create_edge("body", "value", "collect", "item"))
+ graph.add_edge(create_edge("collect", "collection", "outer_return", "output"))
+ graph.add_edge(create_loop_linkage("outer", "outer_return"))
+ graph.add_node(AnyTypeTestInvocation(id="after"))
+ graph.add_edge(create_edge("outer", "output_collection", "after", "value"))
+ return graph
+
+
[email protected]_independent
[email protected]("body_type", ["for", "iterate"])
[email protected]("force_compatibility_scheduler", [False, True])
+def test_loop_shapes_are_classified_once_per_execution(
+ monkeypatch: pytest.MonkeyPatch, body_type: str, force_compatibility_scheduler: bool
+) -> None:
+ classify = LoopTopology.classify.__func__
+ classifications = 0
+
+ def counted_classify(cls: type[LoopTopology], *args: object) -> LoopTopology:
+ nonlocal classifications
+ classifications += 1
+ return classify(cls, *args)
+
+ # Counts LoopTopology.classify calls; each one runs every shape recognizer for every For.
+ monkeypatch.setattr(LoopTopology, "classify", classmethod(counted_classify))
+ counts: dict[int, int] = {}
+ for outer_count in (2, 20):
+ classifications = 0
+ state = GraphExecutionState(graph=_nested_loop_graph(body_type, outer_count))
+ if force_compatibility_scheduler:
+ state._execution_scheduler = _ExecutionScheduler(state)
+ while (node := state.next()) is not None:
+ state.complete(node.id, node.invoke(Mock()))
+ assert state.is_complete()
+ counts[outer_count] = classifications
+
+ # Graph validation classifies once and the execution state once, however many loop nodes complete.
+ assert counts == {2: 2, 20: 2}
+
+
@pytest.mark.slow
@pytest.mark.parametrize("loop_type", ["for", "iterate"])
def test_trivial_loop_scheduler_overhead(loop_type: str) -> None:
diff --git a/tests/app/services/shared/test_graph_loop_topology.py b/tests/app/services/shared/test_graph_loop_topology.py
new file mode 100644
index 0000000000..c153bbe6c6
--- /dev/null
+++ b/tests/app/services/shared/test_graph_loop_topology.py
@@ -0,0 +1,419 @@
+import pickle
+import re
+
+import pytest
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.collections import CollectionConcatInvocation
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.graph_loop_topology import (
+ LoopTopology,
+ NestedForBody,
+ NestedIterateBody,
+ NestedIterateChain,
+ NestedIterateSequence,
+)
+from invokeai.app.services.shared.graph_validation import CollectInvocation, InvalidEdgeError, IterateInvocation
+from tests.test_nodes import AnyTypeTestInvocation, PolymorphicStringTestInvocation, create_edge, create_loop_linkage
+
+_Connection = tuple[str, str, str, str]
+
+
+def _graph(
+ nodes: list[BaseInvocation], connections: list[_Connection], linkages: tuple[tuple[str, str], ...] = ()
+) -> Graph:
+ graph = Graph()
+ for node in nodes:
+ graph.add_node(node)
+ for connection in connections:
+ graph.add_edge(create_edge(*connection))
+ for for_id, return_id in linkages:
+ graph.add_edge(create_loop_linkage(for_id, return_id))
+ return graph
+
+
+def _classify(graph: Graph) -> LoopTopology:
+ return LoopTopology.classify(graph, graph.nx_graph_flat())
+
+
+def _for_iterate_collect_graph(
+ *, extra_collect_item: bool = False, extra_connections: tuple[_Connection, ...] = ()
+) -> Graph:
+ nodes: list[BaseInvocation] = [
+ ForInvocation(id="for", collection=[["a"]]),
+ PolymorphicStringTestInvocation(id="prep"),
+ IterateInvocation(id="iterate"),
+ AnyTypeTestInvocation(id="body"),
+ CollectInvocation(id="collect"),
+ ForReturnInvocation(id="return"),
+ ]
+ connections = [
+ ("for", "item", "prep", "value"),
+ ("prep", "collection", "iterate", "collection"),
+ ("iterate", "item", "body", "value"),
+ ("body", "value", "collect", "item"),
+ ("collect", "collection", "return", "output"),
+ ]
+ if extra_collect_item:
+ nodes.append(AnyTypeTestInvocation(id="second_body"))
+ connections += [("iterate", "item", "second_body", "value"), ("second_body", "value", "collect", "item")]
+ return _graph(nodes, [*connections, *extra_connections], (("for", "return"),))
+
+
+def _assert_rejected(graph: Graph, message: str) -> None:
+ with pytest.raises(InvalidEdgeError, match=re.escape(message)):
+ graph.validate_self()
+
+
+def _iterate_sequence_graph(*, body_input: str = "inner") -> Graph:
+ nodes: list[BaseInvocation] = [
+ CollectionConcatInvocation(id="source", first=[["a"]]),
+ IterateInvocation(id="outer"),
+ PolymorphicStringTestInvocation(id="prep"),
+ IterateInvocation(id="inner"),
+ AnyTypeTestInvocation(id="body"),
+ ]
+ connections = [
+ ("source", "collection", "outer", "collection"),
+ ("outer", "item", "prep", "value"),
+ ("prep", "collection", "inner", "collection"),
+ (body_input, "item", "body", "value"),
+ ]
+ return _graph(nodes, connections)
+
+
+def test_flat_for_has_a_body_path_but_no_nested_shape() -> None:
+ graph = _graph(
+ [ForInvocation(id="for", collection=[1]), AnyTypeTestInvocation(id="body"), ForReturnInvocation(id="return")],
+ [("for", "item", "body", "value"), ("body", "value", "return", "output")],
+ (("for", "return"),),
+ )
+
+ topology = _classify(graph)
+
+ assert topology.for_body_paths == {"for": (frozenset({"body", "return"}), "return")}
+ assert topology.for_id_by_return_id == {"return": "for"}
+ assert topology.for_body_shapes == {}
+ assert topology.nested_iterate_sequence is None
+
+
+def test_for_with_one_internal_iterate_is_a_nested_iterate_body() -> None:
+ topology = _classify(_for_iterate_collect_graph())
+
+ assert topology.for_body_shapes == {
+ "for": NestedIterateBody(
+ body_path_nodes=frozenset({"prep", "iterate", "body", "collect", "return"}),
+ return_node_id="return",
+ iterate_node_id="iterate",
+ collect_node_id="collect",
+ )
+ }
+ assert topology.nested_iterate_chain("for") is None
+ assert topology.nested_for_body("for") is None
+
+
+def test_iterate_body_with_two_collect_items_is_unsupported() -> None:
+ topology = _classify(_for_iterate_collect_graph(extra_collect_item=True))
+
+ assert topology.for_body_shapes == {}
+ assert "for" in topology.for_body_paths
+
+
+def test_iterate_body_whose_body_node_feeds_the_return_state_is_rejected() -> None:
+ graph = _for_iterate_collect_graph(extra_connections=(("body", "value", "return", "state"),))
+
+ _assert_rejected(graph, "Invalid For node (for): Iterate nodes inside For loop bodies are unsupported")
+
+
+def test_iterate_body_node_unrelated_to_the_iterate_is_rejected() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="for", collection=[["a"]]),
+ PolymorphicStringTestInvocation(id="prep"),
+ IterateInvocation(id="iterate"),
+ AnyTypeTestInvocation(id="side"),
+ CollectionConcatInvocation(id="mix"),
+ CollectInvocation(id="collect"),
+ ForReturnInvocation(id="return"),
+ ],
+ [
+ ("for", "item", "prep", "value"),
+ ("prep", "collection", "iterate", "collection"),
+ ("iterate", "item", "mix", "first"),
+ ("for", "item", "side", "value"),
+ ("side", "value", "mix", "second"),
+ ("mix", "collection", "collect", "item"),
+ ("collect", "collection", "return", "output"),
+ ],
+ (("for", "return"),),
+ )
+
+ _assert_rejected(graph, "Invalid For node (for): Iterate nodes inside For loop bodies are unsupported")
+
+
+def test_for_return_outside_its_for_body_is_rejected() -> None:
+ # The ForReturn comes first, so its own check runs before the For's.
+ graph = _graph(
+ [ForReturnInvocation(id="return"), ForInvocation(id="for", collection=[1]), AnyTypeTestInvocation(id="body")],
+ [("for", "item", "body", "value")],
+ (("for", "return"),),
+ )
+
+ _assert_rejected(graph, "Invalid ForReturn node (return): ForReturn must belong to exactly one matching For")
+
+
+def test_for_with_two_serial_iterates_is_a_nested_iterate_chain() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="for", collection=[["a"]]),
+ PolymorphicStringTestInvocation(id="prep_1"),
+ IterateInvocation(id="iterate_1"),
+ PolymorphicStringTestInvocation(id="prep_2"),
+ IterateInvocation(id="iterate_2"),
+ AnyTypeTestInvocation(id="body"),
+ CollectInvocation(id="collect"),
+ ForReturnInvocation(id="return"),
+ ],
+ [
+ ("for", "item", "prep_1", "value"),
+ ("prep_1", "collection", "iterate_1", "collection"),
+ ("iterate_1", "item", "prep_2", "value"),
+ ("prep_2", "collection", "iterate_2", "collection"),
+ ("iterate_2", "item", "body", "value"),
+ ("body", "value", "collect", "item"),
+ ("collect", "collection", "return", "output"),
+ ],
+ (("for", "return"),),
+ )
+
+ assert _classify(graph).for_body_shapes == {
+ "for": NestedIterateChain(
+ body_path_nodes=frozenset({"prep_1", "iterate_1", "prep_2", "iterate_2", "body", "collect", "return"}),
+ return_node_id="return",
+ iterate_node_ids=("iterate_1", "iterate_2"),
+ collect_node_id="collect",
+ )
+ }
+
+
+def test_three_level_nested_for_is_classified_recursively() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="outer", collection=[[["a"]]]),
+ ForInvocation(id="middle"),
+ ForInvocation(id="inner"),
+ AnyTypeTestInvocation(id="body"),
+ ForReturnInvocation(id="inner_return"),
+ ForReturnInvocation(id="middle_return"),
+ ForReturnInvocation(id="outer_return"),
+ ],
+ [
+ ("outer", "item", "middle", "collection"),
+ ("middle", "item", "inner", "collection"),
+ ("inner", "item", "body", "value"),
+ ("body", "value", "inner_return", "output"),
+ ("inner", "output_collection", "middle_return", "output"),
+ ("middle", "output_collection", "outer_return", "output"),
+ ],
+ (("outer", "outer_return"), ("middle", "middle_return"), ("inner", "inner_return")),
+ )
+
+ topology = _classify(graph)
+
+ assert topology.for_body_shapes == {
+ "outer": NestedForBody(
+ body_path_nodes=frozenset({"middle", "inner", "body", "inner_return", "middle_return", "outer_return"}),
+ outer_return_id="outer_return",
+ inner_for_ids=("middle",),
+ continuation_nodes=frozenset(),
+ ),
+ "middle": NestedForBody(
+ body_path_nodes=frozenset({"inner", "body", "inner_return", "middle_return"}),
+ outer_return_id="middle_return",
+ inner_for_ids=("inner",),
+ continuation_nodes=frozenset(),
+ ),
+ }
+ assert topology.for_id_by_return_id == {"outer_return": "outer", "middle_return": "middle", "inner_return": "inner"}
+
+
+def test_sibling_nested_fors_join_through_a_continuation() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="outer", collection=[["a"]]),
+ ForInvocation(id="left"),
+ ForInvocation(id="right"),
+ AnyTypeTestInvocation(id="left_body"),
+ AnyTypeTestInvocation(id="right_body"),
+ ForReturnInvocation(id="left_return"),
+ ForReturnInvocation(id="right_return"),
+ CollectionConcatInvocation(id="join"),
+ ForReturnInvocation(id="outer_return"),
+ ],
+ [
+ ("outer", "item", "left", "collection"),
+ ("outer", "item", "right", "collection"),
+ ("left", "item", "left_body", "value"),
+ ("right", "item", "right_body", "value"),
+ ("left_body", "value", "left_return", "output"),
+ ("right_body", "value", "right_return", "output"),
+ ("left", "output_collection", "join", "first"),
+ ("right", "output_collection", "join", "second"),
+ ("join", "collection", "outer_return", "output"),
+ ],
+ (("outer", "outer_return"), ("left", "left_return"), ("right", "right_return")),
+ )
+
+ shape = _classify(graph).nested_for_body("outer")
+
+ assert shape is not None
+ assert shape.inner_for_ids == ("left", "right")
+ assert shape.continuation_nodes == {"join"}
+ assert shape.outer_return_id == "outer_return"
+ assert shape.body_path_nodes == {
+ "left",
+ "right",
+ "left_body",
+ "right_body",
+ "left_return",
+ "right_return",
+ "join",
+ "outer_return",
+ }
+
+
+def test_nested_for_continuation_fed_from_outside_the_inner_loop_is_rejected() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="outer", collection=[["a"]]),
+ ForInvocation(id="inner"),
+ AnyTypeTestInvocation(id="inner_body"),
+ ForReturnInvocation(id="inner_return"),
+ AnyTypeTestInvocation(id="side"),
+ CollectionConcatInvocation(id="join"),
+ ForReturnInvocation(id="outer_return"),
+ ],
+ [
+ ("outer", "item", "inner", "collection"),
+ ("inner", "item", "inner_body", "value"),
+ ("inner_body", "value", "inner_return", "output"),
+ ("outer", "item", "side", "value"),
+ ("inner", "output_collection", "join", "first"),
+ ("side", "value", "join", "second"),
+ ("join", "collection", "outer_return", "output"),
+ ],
+ (("outer", "outer_return"), ("inner", "inner_return")),
+ )
+
+ _assert_rejected(
+ graph, "Invalid For node (outer): Nested For loops require one linked inner For with a matching ForReturn"
+ )
+
+
+def test_nested_for_around_an_iterate_body_classifies_only_the_inner_loop() -> None:
+ graph = _graph(
+ [
+ ForInvocation(id="outer", collection=[[["a"]]]),
+ ForInvocation(id="inner"),
+ PolymorphicStringTestInvocation(id="prep"),
+ IterateInvocation(id="iterate"),
+ AnyTypeTestInvocation(id="body"),
+ CollectInvocation(id="collect"),
+ ForReturnInvocation(id="inner_return"),
+ ForReturnInvocation(id="outer_return"),
+ ],
+ [
+ ("outer", "item", "inner", "collection"),
+ ("inner", "item", "prep", "value"),
+ ("prep", "collection", "iterate", "collection"),
+ ("iterate", "item", "body", "value"),
+ ("body", "value", "collect", "item"),
+ ("collect", "collection", "inner_return", "output"),
+ ("inner", "output_collection", "outer_return", "output"),
+ ],
+ (("outer", "outer_return"), ("inner", "inner_return")),
+ )
+
+ topology = _classify(graph)
+
+ assert set(topology.for_body_shapes) == {"inner"}
+ assert topology.nested_iterate_body("inner") is not None
+ assert topology.nested_for_body("outer") is None
+
+
+def test_whole_graph_iterate_chain_is_a_nested_iterate_sequence() -> None:
+ assert _classify(_iterate_sequence_graph()).nested_iterate_sequence == NestedIterateSequence(
+ body_path_nodes=frozenset({"source", "outer", "prep", "inner", "body"}),
+ source_node_id="source",
+ iterate_node_ids=("outer", "inner"),
+ preparation_node_ids=("prep",),
+ body_node_id="body",
+ )
+
+
+def test_iterate_chain_whose_body_skips_the_inner_iterate_is_not_a_sequence() -> None:
+ assert _classify(_iterate_sequence_graph(body_input="outer")).nested_iterate_sequence is None
+
+
+def test_iterate_chain_ending_in_a_collect_is_not_a_sequence() -> None:
+ graph = _graph(
+ [
+ CollectionConcatInvocation(id="source", first=[["a"]]),
+ IterateInvocation(id="outer"),
+ PolymorphicStringTestInvocation(id="prep"),
+ IterateInvocation(id="inner"),
+ CollectInvocation(id="body"),
+ ],
+ [
+ ("source", "collection", "outer", "collection"),
+ ("outer", "item", "prep", "value"),
+ ("prep", "collection", "inner", "collection"),
+ ("inner", "item", "body", "item"),
+ ],
+ )
+
+ assert _classify(graph).nested_iterate_sequence is None
+
+
+def test_execution_state_reclassifies_after_its_source_graph_changes() -> None:
+ graph = _graph(
+ [ForInvocation(id="for", collection=[1]), AnyTypeTestInvocation(id="body"), ForReturnInvocation(id="return")],
+ [("for", "item", "body", "value"), ("body", "value", "return", "output")],
+ (("for", "return"),),
+ )
+ state = GraphExecutionState(graph=graph)
+ first = state._loop_topology()
+ assert state._loop_topology() is first
+
+ state.delete_edge(create_edge("body", "value", "return", "output"))
+ state.add_node(AnyTypeTestInvocation(id="second_body"))
+ state.add_edge(create_edge("body", "value", "second_body", "value"))
+ state.add_edge(create_edge("second_body", "value", "return", "output"))
+
+ assert state._loop_topology().for_body_paths["for"] == (
+ frozenset({"body", "second_body", "return"}),
+ "return",
+ )
+
+
+def test_topology_and_execution_state_survive_pickling() -> None:
+ topology = _classify(_for_iterate_collect_graph())
+
+ restored = pickle.loads(pickle.dumps(topology))
+
+ assert restored.for_body_paths == topology.for_body_paths
+ assert restored.for_body_shapes == topology.for_body_shapes
+ assert restored.for_id_by_return_id == topology.for_id_by_return_id
+ assert restored.nested_iterate_sequence == topology.nested_iterate_sequence
+ with pytest.raises(TypeError):
+ restored.for_body_shapes["other"] = topology.for_body_shapes["for"] # type: ignore[index]
+
+ state = GraphExecutionState(graph=_for_iterate_collect_graph())
+ built = state._loop_topology()
+ restored_state = pickle.loads(pickle.dumps(state))
+ restored_topology = restored_state.__pydantic_private__["_runtime_state"].loop_topology
+
+ # The topology and the state's flat graph unpickle as one graph, so the restored topology is still the cache entry.
+ assert restored_topology.for_body_shapes == built.for_body_shapes
+ assert restored_state._loop_topology() is restored_topology
diff --git a/tests/app/services/shared/test_graph_models.py b/tests/app/services/shared/test_graph_models.py
index 9ab948b1db..6ea1544c02 100644
--- a/tests/app/services/shared/test_graph_models.py
+++ b/tests/app/services/shared/test_graph_models.py
@@ -72,8 +72,6 @@ def test_graph_facade_reexports_authoring_graph_boundary() -> None:
"UnknownGraphValidationError",
"NodeInputError",
"loc_to_dot_sep",
- "_SupportedNestedForBody",
- "_SupportedNestedIterateBody",
"nx",
)