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(execution): route three-level nested For generically

JPPhotoa237b612028b
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 8b374db00e..ad4f45ed2a 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -105,9 +105,9 @@ iteration, and finalizes the aggregate. An empty literal collection completes th
`For` result without running the body or `ForReturn`. The generic scheduler remains opaque and never receives a literal
successor node ID. The compatibility continuation bridge is retained only for unsupported loop shapes and explicitly
legacy-loaded snapshots. Empty input-driven shapes outside the exact four-node/four-edge bounded topology, unsupported
-input-driven outer collections, deeper or multiple nested loops, and unsupported mixed control flow remain on the
-compatibility scheduler; the narrow canonical two-level
-nested-`For` shape and the exact
+input-driven outer collections, four-level-or-deeper or sibling nested loops, and unsupported mixed control flow remain on the
+compatibility scheduler; the narrow canonical two-level and exact fresh three-level serial nested-`For` shapes
+(one literal outer collection, one direct child at each level, no continuation nodes) and the exact
bounded outer-`For`/`Iterate`/`Collect` shape are now generic-routed. This additive effect seam does not claim generic
scheduling for the remaining shapes. `Iterate` records ordered item tokens in
a closed `StreamBuffer`; an empty `Iterate` records an
@@ -204,7 +204,7 @@ lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or
graph JSON.
Exact fresh serial nested-`Iterate` chains through eight levels use the generic planner for ordered frame expansion,
empty-stream closure, checkpoint rehydration, source completion, and failure parity. Nine-level or deeper chains,
-other deeper or multiple nested loops, and unsupported mixed shapes remain compatibility-owned. This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing
+other four-level-or-deeper or sibling nested loops, and unsupported mixed shapes remain compatibility-owned. This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing
frontend/backend external interface remains frozen. Branch-membership analysis remains internal, while fresh execution
no longer creates skipped-state projection and old snapshots retain it for compatibility.
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index b8bf7b329a..f0322876a9 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -93,7 +93,7 @@ with one ordinary `outer For.output_collection` consumer, is also generic-routed
The nested planner owns per-outer-frame stream expansion, parent-frame stream
identity, empty closure, `Collect` readiness/hydration, checkpoint rehydration,
and failure parity for this shape without calling the materializer's nested-copy
-helper. Ordinary nested `For`, deeper or multiple nested iterators,
+helper. Four-level-or-deeper or sibling nested `For`, deeper or multiple nested iterators,
other input-driven outer collections, other mixed control flow, and legacy snapshots retain
compatibility materializer ownership.
The exact eight-node producer-driven extension—one inputless ordinary
@@ -142,16 +142,19 @@ The exact seventeen-node/sixteen-edge serial chain extends the same planner to
eight `Iterate` nodes and eight-component frame paths, with the same
empty-stream, checkpoint, source-completion, and failure-parity guarantees.
Nine-level or deeper chains and all other expanded, fan-in, sibling, mixed,
-`For`, `Collect`, and legacy shapes remain compatibility-owned.
+four-level-or-deeper `For`, `Collect`, and legacy shapes remain compatibility-owned.
A fresh graph with exactly one flat `For`/`ForReturn` pair and ordinary body nodes also uses the generic adapter for a
literal collection, a supported non-empty input-driven collection, or the exact four-node/four-edge empty input-driven
shape with one inputless producer and no downstream node. It projects readiness and invokes the graph-state
continuation boundary, which selects the next iteration or finalizes the aggregate without exposing a successor node ID
to the generic scheduler. The materializer still owns execution-node copies, input hydration, iteration paths, and body
-expansion. Other empty/input-driven shapes, deeper or multiple loops, mixed control flow, and saved-workflow calls remain
+ expansion. Other empty/input-driven shapes, four-level-or-deeper or sibling loops, mixed control flow, and saved-workflow calls remain
on the compatibility scheduler until their own differential gates are complete. One narrow fresh two-level nested-`For` shape (one non-empty literal outer
collection, one inner `For` sourced from `outer.item`, and no continuation nodes) now uses the generic adapter;
-deeper, multiple-child, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.
+deeper-than-three-level, multiple-child, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.
+The exact fresh three-level serial nested-`For` shape (one literal outer collection,
+one direct child at each level, no continuation nodes) also uses the generic adapter;
+four-level-or-deeper and sibling nested-`For` shapes remain compatibility-owned.
The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and
authorized child-dependency records are stored in
`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while
@@ -273,7 +276,7 @@ completion mirrors Iterate outputs into the stream ledger. A fresh graph with on
including a supported non-empty input-driven collection producer or the exact bounded empty input-driven producer
shape, also uses the adapter for readiness and continuation transitions; graph state owns the invocation-specific
continuation boundary while the generic scheduler remains opaque. Other empty or unsupported input-driven shapes,
-deeper or multiple loops, saved-workflow calls, and unsupported mixed control-flow shapes outside the bounded per-item
+four-level-or-deeper or sibling loops, saved-workflow calls, and unsupported mixed control-flow shapes outside the bounded per-item
topology continue to use
the legacy compatibility scheduler until their differential coverage is complete. The narrow canonical two-level
nested-`For` shape, the canonical outer-`For`/bounded-`Iterate`/`Collect` shape,
@@ -286,7 +289,8 @@ including an empty inner collection, remains isolated by its frame path. `Iterat
for this exact seven-node shape, the private nested planner owns per-outer-frame
copy expansion, stream identity, empty closure, `Collect` readiness/hydration,
checkpoint rehydration, and failure parity. The exact producer-driven outer
-extension described above is also generic-routed. Ordinary nested `For`, nine-level
+extension described above is also generic-routed. The exact fresh three-level serial nested-`For` shape is also
+generic-routed; four-level-or-deeper or sibling nested `For`, nine-level
or deeper nested iterators, other input-driven outer collections, mixed control
flow, and legacy snapshots retain compatibility materializer ownership. The
exact nested-`Iterate` chains above do not admit `For`, `Collect`, fan-in, sibling,
@@ -424,7 +428,7 @@ the generic path completes through the existing synthetic terminal `For` result
The generic scheduler receives only opaque node IDs and dependencies; it never receives a literal next node ID. The
compatibility continuation bridge remains available only for unsupported loop shapes and explicitly legacy-loaded snapshots.
The exact four-node/four-edge empty input-driven shape with one inputless static-list producer is also generic-routed.
-Other input-driven outer collections, deeper, multiple, or unsupported mixed loop shapes remain compatibility-owned; the narrow canonical two-level nested-`For` shape, the canonical bounded
+Other input-driven outer collections, four-level-or-deeper or sibling nested loops, or unsupported mixed loop shapes remain compatibility-owned; the narrow canonical two-level and exact fresh three-level serial nested-`For` shapes, the canonical bounded
internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension, and the bounded two- through
six-, seven-, and eight-level serial nested-`Iterate` chains are generic-routed. On
rehydration, the generic adapter restores the active class-drain
@@ -492,10 +496,10 @@ compatibility loader. `For` start payloads must match the prepared index, collec
seam: the generic adapter calls the graph-state generic continuation boundary,
which creates the next prepared iteration, aggregates outputs, and finalizes the
supported flat loop. The compatibility bridge remains for other unsupported input-driven,
-deeper/multiple nested, mixed-loop, and legacy-snapshot execution; those paths
+four-level-or-deeper/sibling nested, mixed-loop, and legacy-snapshot execution; those paths
retain their existing materialization and linkage ownership. The supported
fresh static flat `For`/`ForReturn` shape, the exact bounded empty input-driven
-flat shape, the narrow canonical two-level
+flat shape, the narrow canonical two-level and exact fresh three-level serial nested-`For`
nested-`For` shape, and the canonical bounded internal `Iterate`/`Collect`
shape use the generic adapter. For
`If`, generic readiness consumes opaque frame-local plan dependencies and requires
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 0ca39ea60c..bdd881b1e5 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -763,6 +763,72 @@ class GraphExecutionState(BaseModel):
return self._apply_generic_for_continuation(exec_node_id, output)
+ def _can_use_generic_three_level_nested_for_scheduler(
+ self, for_nodes: list[ForInvocation], return_nodes: list[ForReturnInvocation], source_graph: Any
+ ) -> bool:
+ if len(for_nodes) != 3 or len(return_nodes) != 3:
+ return False
+
+ 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)
+ if nested_body is not None:
+ for_node_bodies[node.id] = nested_body
+ nested_child_ids = {
+ inner_for_id for nested_body in for_node_bodies.values() for inner_for_id in nested_body.inner_for_ids
+ }
+ outer_candidates = [
+ node
+ for node in for_nodes
+ if node.id not in nested_child_ids
+ and (nested_body := for_node_bodies.get(node.id)) is not None
+ and len(nested_body.inner_for_ids) == 1
+ and not nested_body.continuation_nodes
+ ]
+ if len(outer_candidates) != 1:
+ return False
+
+ outer_for = outer_candidates[0]
+ if self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD) or not outer_for.collection:
+ return False
+
+ chain = [outer_for]
+ while len(chain) < 3:
+ parent_for = chain[-1]
+ nested_body = for_node_bodies.get(parent_for.id)
+ if nested_body is None or len(nested_body.inner_for_ids) != 1 or nested_body.continuation_nodes:
+ return False
+ child_for = self.graph.get_node(nested_body.inner_for_ids[0])
+ if not isinstance(child_for, ForInvocation):
+ return False
+ collection_edges = self.graph._get_input_edges(child_for.id, COLLECTION_FIELD)
+ if len(collection_edges) != 1 or (
+ collection_edges[0].source.node_id != parent_for.id
+ or collection_edges[0].source.field != ITEM_FIELD
+ or self.graph._get_output_edges(parent_for.id, ITEM_FIELD) != collection_edges
+ ):
+ return False
+ chain.append(child_for)
+
+ if len(chain) != 3 or {node.id for node in chain} != {node.id for node in for_nodes}:
+ return False
+ if chain[-1].id in for_node_bodies:
+ return False
+
+ linked_return_ids = {self.graph._get_linked_for_return_id(node.id) for node in chain}
+ if None in linked_return_ids or linked_return_ids != {node.id for node in return_nodes}:
+ return False
+
+ final_output_edges = self.graph._get_for_final_output_edges(outer_for.id)
+ if len(final_output_edges) > 1:
+ return False
+ if final_output_edges:
+ final_consumer = self.graph.get_node(final_output_edges[0].destination.node_id)
+ if isinstance(final_consumer, (ForInvocation, ForReturnInvocation, IterateInvocation, CollectInvocation)):
+ return False
+ return True
+
def _can_use_generic_for_scheduler(self) -> bool:
"""Allow generic routing only for the explicitly supported fresh For shapes."""
@@ -774,8 +840,10 @@ 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()
+ if len(for_nodes) == 3 and len(return_nodes) == 3:
+ return self._can_use_generic_three_level_nested_for_scheduler(for_nodes, return_nodes, source_graph)
if len(for_nodes) == 2 and len(return_nodes) == 2:
- source_graph = self._get_source_graph_flat()
outer_for = next(
(
node
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index b3b9a94898..6c71ce3c9a 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -540,6 +540,99 @@ def _nested_for_graph(*, outer_collection: list[list[str]] | None = None) -> Gra
return graph
+def _three_level_nested_for_graph(*, outer_collection: list[list[list[str]]] | None = None) -> Graph:
+ graph = Graph()
+ graph.add_node(
+ ForInvocation(
+ id="outer_for",
+ collection=[[["a", "b"], ["c"]], [["d"]]] if outer_collection is None else outer_collection,
+ )
+ )
+ graph.add_node(ForInvocation(id="middle_for"))
+ graph.add_node(ForInvocation(id="inner_for"))
+ graph.add_node(AnyTypeTestInvocation(id="inner_body"))
+ graph.add_node(ForReturnInvocation(id="inner_return"))
+ graph.add_node(ForReturnInvocation(id="middle_return"))
+ graph.add_node(ForReturnInvocation(id="outer_return"))
+ graph.add_node(AnyTypeTestInvocation(id="after"))
+
+ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:
+ graph.add_edge(create_edge(source, source_field, destination, destination_field))
+
+ connect("outer_for", "item", "middle_for", "collection")
+ connect("middle_for", "item", "inner_for", "collection")
+ connect("inner_for", "item", "inner_body", "value")
+ connect("inner_body", "value", "inner_return", "output")
+ connect("inner_for", "output_collection", "middle_return", "output")
+ connect("middle_for", "output_collection", "outer_return", "output")
+ connect("outer_for", "output_collection", "after", "value")
+ graph.add_edge(create_loop_linkage("outer_for", "outer_return"))
+ graph.add_edge(create_loop_linkage("middle_for", "middle_return"))
+ graph.add_edge(create_loop_linkage("inner_for", "inner_return"))
+ return graph
+
+
+def _four_level_nested_for_graph() -> Graph:
+ graph = _three_level_nested_for_graph()
+ graph.delete_node("inner_body")
+ graph.add_node(ForInvocation(id="deep_for"))
+ graph.add_node(AnyTypeTestInvocation(id="deep_body"))
+ graph.add_node(ForReturnInvocation(id="deep_return"))
+
+ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:
+ graph.add_edge(create_edge(source, source_field, destination, destination_field))
+
+ connect("inner_for", "item", "deep_for", "collection")
+ connect("deep_for", "item", "deep_body", "value")
+ connect("deep_body", "value", "deep_return", "output")
+ connect("deep_for", "output_collection", "inner_return", "output")
+ graph.add_edge(create_loop_linkage("deep_for", "deep_return"))
+ return graph
+
+
+def _sibling_nested_for_graph() -> Graph:
+ graph = _three_level_nested_for_graph()
+ middle_return_edge = next(
+ edge for edge in graph._get_input_edges("middle_return", "output") if edge.source.node_id == "inner_for"
+ )
+ graph.delete_edge(middle_return_edge)
+ graph.add_node(ForInvocation(id="sibling_for"))
+ graph.add_node(AnyTypeTestInvocation(id="sibling_body"))
+ graph.add_node(ForReturnInvocation(id="sibling_return"))
+ graph.add_node(CollectionConcatInvocation(id="middle_join"))
+
+ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:
+ graph.add_edge(create_edge(source, source_field, destination, destination_field))
+
+ connect("middle_for", "item", "sibling_for", "collection")
+ connect("sibling_for", "item", "sibling_body", "value")
+ connect("sibling_body", "value", "sibling_return", "output")
+ connect("inner_for", "output_collection", "middle_join", "first")
+ connect("sibling_for", "output_collection", "middle_join", "second")
+ connect("middle_join", "collection", "middle_return", "output")
+ graph.add_edge(create_loop_linkage("sibling_for", "sibling_return"))
+ return graph
+
+
+def _input_driven_three_level_nested_for_graph() -> Graph:
+ graph = _three_level_nested_for_graph()
+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[[["a", "b"], ["c"]], [["d"]]]))
+ graph.add_edge(create_edge("outer_source", "collection", "outer_for", "collection"))
+ return graph
+
+
+def _malformed_three_level_nested_for_graph() -> Graph:
+ graph = _three_level_nested_for_graph()
+ outer_item_edge = next(
+ edge for edge in graph._get_input_edges("middle_for", "collection") if edge.source.node_id == "outer_for"
+ )
+ graph.delete_edge(outer_item_edge)
+ graph.add_node(AnyTypeTestInvocation(id="outer_bridge"))
+ graph.add_edge(create_edge("outer_for", "item", "outer_bridge", "value"))
+ graph.add_edge(create_edge("outer_bridge", "value", "middle_for", "collection"))
+ return graph
+
+
def _nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | None = None) -> Graph:
graph = Graph()
graph.add_node(ForInvocation(id="outer_for", collection=outer_collection or [["a", "b"], ["c"]]))
@@ -2003,6 +2096,90 @@ def test_nested_for_generic_path_rehydrates_after_inner_completion() -> None:
assert _state_projection(compatibility_resumed) == _state_projection(expected_state)
+def test_three_level_nested_for_generic_and_compatibility_paths_match() -> None:
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_three_level_nested_for_graph()),
+ force_compatibility_scheduler=True,
+ )
+ generic_trace, generic_state = _run_graph(GraphExecutionState(graph=_three_level_nested_for_graph()))
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)
+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert _source_output(generic_state, "after").value == [[["a", "b"], ["c"]], [["d"]]]
+
+
+def test_three_level_nested_for_generic_and_compatibility_paths_match_empty_inner_collection() -> None:
+ graph = _three_level_nested_for_graph(outer_collection=[[[], ["c"]], [["d"]]])
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ )
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(graph=_three_level_nested_for_graph(outer_collection=[[[], ["c"]], [["d"]]]))
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+ assert _source_output(generic_state, "after").value == [[[], ["c"]], [["d"]]]
+ assert _source_output(compatibility_state, "after").value == [[[], ["c"]], [["d"]]]
+
+
+def test_three_level_nested_for_generic_rehydrates_after_inner_completion() -> None:
+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=_three_level_nested_for_graph()))
+ partial_trace, partial_state = _run_graph(
+ GraphExecutionState(graph=_three_level_nested_for_graph()),
+ stop_after=5,
+ )
+
+ restored = load_execution_state(dump_execution_state(partial_state))
+ resumed_trace, resumed_state = _run_graph(restored)
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert resumed_state.is_complete()
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+
+
+def test_three_level_nested_for_generic_failure_matches_compatibility() -> None:
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_three_level_nested_for_graph()),
+ fail_source_id="inner_body",
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_three_level_nested_for_graph()),
+ force_compatibility_scheduler=True,
+ fail_source_id="inner_body",
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.has_error() and compatibility_state.has_error()
+ assert generic_state.is_complete() and compatibility_state.is_complete()
+ assert "inner_return" not in generic_trace
+ assert "middle_return" not in generic_trace
+ assert "outer_return" not in generic_trace
+ assert "after" not in generic_trace
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+
+
+ "graph_factory",
+ [
+ pytest.param(_four_level_nested_for_graph, id="four-level"),
+ pytest.param(_sibling_nested_for_graph, id="sibling"),
+ pytest.param(_input_driven_three_level_nested_for_graph, id="input-driven"),
+ pytest.param(_malformed_three_level_nested_for_graph, id="malformed-link"),
+ ],
+)
+def test_three_level_nested_for_gate_falls_back_for_unsupported_shapes(graph_factory: Any) -> None:
+ state = GraphExecutionState(graph=graph_factory())
+
+ assert not state._can_use_generic_scheduler()
+
+
def test_nested_for_iterate_collect_generic_and_compatibility_paths_have_matching_completion() -> None:
compatibility_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph())
compatibility_trace, compatibility_state = _run(