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): plan bounded nested iterate streams

JPPhoto5e328d3257be
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index b6270c6ac7..8563afb76f 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -74,6 +74,15 @@ ordered stream effects, empty closure, checkpoint rehydration, failure,
rollback, and fresh retry behavior for that exact shape. It does not admit
`If`, `For`, `ForReturn`, saved-workflow, nested-iterator, fan-in, or mixed
control-flow nodes; those remain compatibility-owned.
+The exact fresh seven-node nested shape `outer For -> ordinary collection
+preparation -> Iterate -> ordinary body -> Collect -> linked outer ForReturn`,
+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,
+input-driven outer collections, mixed control flow, and legacy snapshots retain
+compatibility materializer ownership.
Three or more body-mediated branches, fan-in with four or more direct branches,
nested iterators, and all mixed control flow retain materializer copy expansion,
grouping, and empty-source handling on the legacy compatibility route.
@@ -211,7 +220,12 @@ nested-`For` shape and the canonical outer-`For`/bounded-`Iterate`/`Collect` sha
one ordinary preparation node from `For.item` into `Iterate.collection`, one ordinary body node into `Collect.item`,
the `Collect.collection` output into the linked `ForReturn`, and one final outer-output consumer. Each outer iteration,
including an empty inner collection, remains isolated by its frame path. `Iterate` also records non-empty item streams through the generic effect ledger;
-the materializer remains authoritative for fallback expansion, iteration paths, collector grouping, and
+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. Ordinary nested `For`, deeper or
+multiple nested iterators, input-driven outer collections, mixed control flow,
+and legacy snapshots retain compatibility materializer ownership. The
+materializer remains authoritative for fallback expansion, iteration paths, collector grouping, and
empty-source compatibility handling. The exact fresh four-node body shape, exact two- or three-stream fan-in shapes,
and exact two-branch body-mediated fan-in use the private planner for those responsibilities; three or more
body-mediated branches and four or more direct streams remain compatibility-owned. Direct `Collect.item`
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 578d9cb640..00c903e1a3 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -112,6 +112,10 @@ from invokeai.app.services.shared.graph_models import (
WorkflowCallParentRef, # noqa: F401
WorkflowCallStatus, # noqa: F401
)
+from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_nested_iterate_planner,
+ prepare_nested_iterate_bodies,
+)
from invokeai.app.services.shared.graph_runtime_records import (
_ApplyTransaction,
_PreparedExecNodeMetadata,
@@ -731,7 +735,10 @@ class GraphExecutionState(BaseModel):
iteration_path=(*parent_iteration_path, next_index),
)
self._discard_source_executed(source_for_id)
- self._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
+ if self._is_generic_graph_scheduler(self._scheduler()) and can_use_nested_iterate_planner(self):
+ prepare_nested_iterate_bodies(self)
+ else:
+ self._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
return None
def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
@@ -814,7 +821,10 @@ class GraphExecutionState(BaseModel):
return_node = return_nodes[0]
source_graph = self._get_source_graph_flat()
- if self.graph._get_supported_for_nested_iterate_body(outer_for.id, source_graph) is None:
+ if (
+ not can_use_nested_iterate_planner(self)
+ or self.graph._get_supported_for_nested_iterate_body(outer_for.id, source_graph) is None
+ ):
return False
iterate_collection_edges = self.graph._get_input_edges(iterate_node.id, COLLECTION_FIELD)
diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.py
new file mode 100644
index 0000000000..e4c8740dcc
--- /dev/null
+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py
@@ -0,0 +1,178 @@
+"""Bounded generic planning for the supported nested For/Iterate/Collect shape."""
+
+from typing import TYPE_CHECKING
+
+from invokeai.app.invocations.loops import ForInvocation
+from invokeai.app.services.shared.graph_iterate_planner import (
+ _attach_direct_execution_edges,
+ _create_direct_execution_node_copy,
+ _initialize_direct_execution_node,
+)
+from invokeai.app.services.shared.graph_models import Edge, EdgeConnection
+from invokeai.app.services.shared.graph_validation import (
+ COLLECTION_FIELD,
+ ITEM_FIELD,
+)
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+def _get_exact_nested_iterate_body(state: "GraphExecutionState"):
+ """Return the seven-node nested stream contract, excluding broader topologies."""
+ if len(state.graph.nodes) != 7 or len(state.graph.edges) != 7:
+ return None
+ for_node = next((node for node in state.graph.nodes.values() if isinstance(node, ForInvocation)), None)
+ if for_node is None:
+ return None
+ nested_body = state.graph._get_supported_for_nested_iterate_body(for_node.id, state._get_source_graph_flat())
+ if nested_body is None or len(nested_body.body_path_nodes) != 5:
+ return None
+ return for_node.id, nested_body
+
+
+def can_use_nested_iterate_planner(state: "GraphExecutionState") -> bool:
+ """Check the exact fresh nested stream topology before generic admission."""
+ return not state._legacy_snapshot_loaded and _get_exact_nested_iterate_body(state) is not None
+
+
+def _outer_iteration_path(state: "GraphExecutionState", prepared_for_id: str) -> tuple[int, ...]:
+ path = state._get_iteration_path(prepared_for_id)
+ prepared_for = state.execution_graph.get_node(prepared_for_id)
+ if isinstance(prepared_for, ForInvocation) and prepared_for.index >= 0:
+ return (*state._get_for_parent_iteration_path(prepared_for_id), prepared_for.index)
+ return path
+
+
+def _prepared_at_path(state: "GraphExecutionState", source_node_id: str, path: tuple[int, ...]) -> str | None:
+ matches = [
+ prepared_id
+ for prepared_id in state._prepared_registry().get_prepared_ids(source_node_id)
+ if state._get_iteration_path(prepared_id) == path
+ ]
+ if len(matches) > 1:
+ raise RuntimeError(f"Multiple prepared nested nodes exist for {source_node_id} at {path}")
+ return matches[0] if matches else None
+
+
+def _prepare_nested_iterate_body_for_outer(
+ state: "GraphExecutionState", source_for_id: str, prepared_for_id: str
+) -> None:
+ exact = _get_exact_nested_iterate_body(state)
+ if exact is None or exact[0] != source_for_id:
+ return
+ _, nested_body = exact
+ outer_path = _outer_iteration_path(state, prepared_for_id)
+ source_iterate_id = nested_body.iterate_node_id
+ source_collect_id = nested_body.collect_node_id
+ source_return_id = nested_body.return_node_id
+ iterate_input_edge = state.graph._get_input_edges(source_iterate_id, COLLECTION_FIELD)[0]
+ preparation_node_id = iterate_input_edge.source.node_id
+ preparation_input_edge = state.graph._get_input_edges(preparation_node_id)[0]
+ body_node_id = state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0].source.node_id
+ body_input_edge = state.graph._get_input_edges(body_node_id)[0]
+
+ preparation_exec_id = _prepared_at_path(state, preparation_node_id, outer_path)
+ if preparation_exec_id is None:
+ preparation_node = _create_direct_execution_node_copy(state, preparation_node_id, iteration_path=outer_path)
+ attached_preparation_edges = _attach_direct_execution_edges(
+ state,
+ preparation_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=prepared_for_id, field=preparation_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=preparation_input_edge.destination.field),
+ )
+ ],
+ )
+ _initialize_direct_execution_node(state, preparation_node.id, attached_preparation_edges)
+ return
+
+ if preparation_exec_id not in state.results:
+ return
+ if _prepared_at_path(state, source_collect_id, outer_path) is not None:
+ return
+
+ collection = getattr(state.results[preparation_exec_id], iterate_input_edge.source.field)
+ if not isinstance(collection, list):
+ raise ValueError("Nested Iterate collection source must produce a list")
+
+ body_exec_ids: list[str] = []
+ for index in range(len(collection)):
+ iteration_path = (*outer_path, index)
+ iterate_node = _create_direct_execution_node_copy(
+ state, source_iterate_id, iteration_index=index, iteration_path=iteration_path
+ )
+ attached_iterate_edges = _attach_direct_execution_edges(
+ state,
+ iterate_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=preparation_exec_id, field=iterate_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=iterate_input_edge.destination.field),
+ )
+ ],
+ )
+ _initialize_direct_execution_node(state, iterate_node.id, attached_iterate_edges)
+
+ body_node = _create_direct_execution_node_copy(state, body_node_id, iteration_path=iteration_path)
+ attached_body_edges = _attach_direct_execution_edges(
+ state,
+ body_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=iterate_node.id, field=body_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
+ )
+ ],
+ )
+ _initialize_direct_execution_node(state, body_node.id, attached_body_edges)
+ body_exec_ids.append(body_node.id)
+
+ if not body_exec_ids:
+ state._record_empty_iterate_stream(source_iterate_id, outer_path)
+
+ state._discard_source_executed(source_iterate_id)
+ collect_node = _create_direct_execution_node_copy(state, source_collect_id, iteration_path=outer_path)
+ collect_item_edge = state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]
+ attached_collect_edges = _attach_direct_execution_edges(
+ state,
+ collect_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
+ )
+ for body_exec_id in body_exec_ids
+ ],
+ )
+ _initialize_direct_execution_node(state, collect_node.id, attached_collect_edges)
+
+ state._discard_source_executed(source_return_id)
+ return_node = _create_direct_execution_node_copy(state, source_return_id, iteration_path=outer_path)
+ return_input_edges = state.graph._get_input_edges(source_return_id, "output")
+ attached_return_edges = _attach_direct_execution_edges(
+ state,
+ return_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=collect_node.id, field=COLLECTION_FIELD),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ for edge in return_input_edges
+ ],
+ )
+ _initialize_direct_execution_node(state, return_node.id, attached_return_edges)
+
+
+def prepare_nested_iterate_bodies(state: "GraphExecutionState") -> None:
+ """Prepare the exact nested stream body for every outer For execution path."""
+ if not can_use_nested_iterate_planner(state):
+ return
+ exact = _get_exact_nested_iterate_body(state)
+ assert exact is not None
+ source_for_id, _ = exact
+ for prepared_for_id in tuple(state._prepared_registry().get_prepared_ids(source_for_id)):
+ prepared_for = state.execution_graph.get_node(prepared_for_id)
+ if isinstance(prepared_for, ForInvocation) and prepared_for.index >= 0:
+ _prepare_nested_iterate_body_for_outer(state, source_for_id, prepared_for_id)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index 8870ae4321..cf716853ba 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -12,6 +12,10 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionPlan,
ExecutionScheduler,
)
+from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_nested_iterate_planner,
+ prepare_nested_iterate_bodies,
+)
from invokeai.app.services.shared.graph_validation import CollectInvocation, IterateInvocation, nx
if TYPE_CHECKING:
@@ -569,6 +573,11 @@ class _GenericGraphSchedulerAdapter:
if self._state._count_unexecuted_prepared(source_node_id) == 0 and source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
+ def _try_materialize_deferred_nested_for_body(self, exec_node_id: str) -> None:
+ """Keep the compatibility materializer for generic shapes outside the new planner."""
+
+ _ExecutionScheduler._try_materialize_deferred_nested_for_body(self, exec_node_id)
+
def complete(
self, exec_node_id: str, output: BaseInvocationOutput
) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:
@@ -609,7 +618,10 @@ class _GenericGraphSchedulerAdapter:
# its selected branch completes. Recheck activation readiness here.
if any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
self._enqueue_activation_ready_nodes()
- _ExecutionScheduler._try_materialize_deferred_nested_for_body(self, exec_node_id)
+ if can_use_nested_iterate_planner(self._state):
+ prepare_nested_iterate_bodies(self._state)
+ else:
+ self._try_materialize_deferred_nested_for_body(exec_node_id)
if finalized_for_exec_node_id is None:
return []
finalized_for_node = self._state.execution_graph.get_node(finalized_for_exec_node_id)
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 0950817325..5cc624d8cd 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -1792,6 +1792,29 @@ def test_nested_for_iterate_collect_generic_and_compatibility_paths_have_matchin
assert state.results[after_exec_id].value == [["a", "b"], ["c"]]
+def test_nested_for_iterate_collect_generic_owns_nested_stream_expansion() -> None:
+ compatibility_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph())
+ compatibility_trace, compatibility_state = _run(
+ compatibility_state,
+ force_compatibility_scheduler=True,
+ )
+
+ generic_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph())
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "_create_nested_iterate_body_iteration",
+ side_effect=AssertionError("generic nested Iterate/Collect used materializer copy creation"),
+ ):
+ generic_trace, generic_state = _run(generic_state)
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.is_complete()
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+
+
def test_nested_for_iterate_collect_generic_handles_empty_inner_collection() -> None:
compatibility_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph(outer_collection=[[], ["c"]]))
compatibility_trace, compatibility_state = _run(
@@ -1813,6 +1836,10 @@ def test_nested_for_iterate_collect_generic_handles_empty_inner_collection() ->
if source_node_id == "after"
)
assert state.results[after_exec_id].value == [[], ["c"]]
+ generic_streams = generic_state._generic_runtime().streams
+ assert generic_streams[generic_state._iteration_stream_id("nested_iterate", (0,))].closed
+ assert generic_streams[generic_state._iteration_stream_id("nested_iterate", (0,))].values == ()
+ assert generic_streams[generic_state._iteration_stream_id("nested_iterate", (1,))].values == ("c",)
def test_nested_for_iterate_collect_generic_rehydrates_after_inner_completion() -> None:
@@ -1830,6 +1857,29 @@ def test_nested_for_iterate_collect_generic_rehydrates_after_inner_completion()
assert resumed_state.is_complete()
assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)
assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+
+
+def test_nested_for_iterate_collect_generic_failure_does_not_release_outer_return() -> None:
+ graph = _nested_for_iterate_collect_graph()
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ fail_source_id="nested_body",
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ fail_source_id="nested_body",
+ )
+
+ assert 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 "nested_collect" not in generic_trace
+ assert "outer_return" not in generic_trace
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
@pytest.mark.parametrize("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])