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): support five-level nested iterates

JPPhoto02d917c1506b
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 090cd46e39..da571f4cfc 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -102,8 +102,8 @@ which feeds `inner Iterate`, whose item feeds one ordinary body—is also
generic-routed. Its private planner owns ordered outer/inner frame expansion,
empty outer and inner closure, source completion, checkpoint rehydration, and
failure parity without calling the compatibility materializer. `For`, `Collect`,
-fan-in, sibling iterators, deeper or multiple nested iterators, mixed control
-flow, and legacy snapshots remain compatibility-owned.
+fan-in, sibling iterators, mixed control flow, and legacy snapshots remain
+compatibility-owned; the bounded deeper serial extensions are described next.
The exact seven-node/six-edge serial nested-`Iterate` chain extends this
bounded planner by adding one ordinary preparation/`Iterate` pair between the
outer iterator and body. It owns three-component frame paths, ordered
@@ -111,9 +111,10 @@ expansion, empty outer and intermediate streams, source completion, checkpoint
rehydration, and failure parity. The exact nine-node/eight-edge serial chain
extends the same planner to four `Iterate` nodes and four-component frame
paths, with the same empty-stream, checkpoint, source-completion, and failure
-parity guarantees. Five-level or deeper chains and all other expanded,
-fan-in, sibling, mixed, `For`, `Collect`, and legacy shapes remain
-compatibility-owned.
+parity guarantees. The exact eleven-node/ten-edge serial chain extends the
+same planner to five `Iterate` nodes and five-component frame paths, with the
+same guarantees. Six-level or deeper chains and all other expanded, fan-in,
+sibling, mixed, `For`, `Collect`, and legacy shapes remain compatibility-owned.
Three or more body-mediated branches, fan-in with four or more direct branches,
broader or deeper nested iterators, and all mixed control flow retain materializer copy expansion,
grouping, and empty-source handling on the legacy compatibility route.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index aedf204e2e..329bd9bd7a 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -113,10 +113,12 @@ from invokeai.app.services.shared.graph_models import (
WorkflowCallStatus, # noqa: F401
)
from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_five_level_nested_iterate_sequence_planner,
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
can_use_nested_iterate_sequence_planner,
can_use_three_level_nested_iterate_sequence_planner,
+ prepare_five_level_nested_iterate_sequences,
prepare_four_level_nested_iterate_sequences,
prepare_nested_iterate_bodies,
prepare_nested_iterate_sequences,
@@ -2402,6 +2404,11 @@ class GraphExecutionState(BaseModel):
) and can_use_four_level_nested_iterate_sequence_planner(self):
prepare_four_level_nested_iterate_sequences(self)
return self._get_next_node()
+ if isinstance(
+ self._scheduler(), _GenericGraphSchedulerAdapter
+ ) and can_use_five_level_nested_iterate_sequence_planner(self):
+ prepare_five_level_nested_iterate_sequences(self)
+ return self._get_next_node()
prepared_id = self._materializer().prepare(base_graph)
diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.py
index d6b58bfa15..e33ea15526 100644
--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py
+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py
@@ -97,6 +97,15 @@ def can_use_four_level_nested_iterate_sequence_planner(state: "GraphExecutionSta
)
+def can_use_five_level_nested_iterate_sequence_planner(state: "GraphExecutionState") -> bool:
+ """Check the exact five-level Iterate-only chain before generic admission."""
+ return (
+ not state._legacy_snapshot_loaded
+ and state.graph._get_supported_nested_iterate_sequence(state._get_source_graph_flat(), iterate_count=5)
+ 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)
@@ -555,3 +564,9 @@ def prepare_four_level_nested_iterate_sequences(state: "GraphExecutionState") ->
"""Prepare the exact four-level nested Iterate chain."""
if can_use_four_level_nested_iterate_sequence_planner(state):
_prepare_nested_iterate_sequence(state, iterate_count=4)
+
+
+def prepare_five_level_nested_iterate_sequences(state: "GraphExecutionState") -> None:
+ """Prepare the exact five-level nested Iterate chain."""
+ if can_use_five_level_nested_iterate_sequence_planner(state):
+ _prepare_nested_iterate_sequence(state, iterate_count=5)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index b6fac9cad1..e5dcdae371 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -13,10 +13,12 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionScheduler,
)
from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_five_level_nested_iterate_sequence_planner,
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
can_use_nested_iterate_sequence_planner,
can_use_three_level_nested_iterate_sequence_planner,
+ prepare_five_level_nested_iterate_sequences,
prepare_four_level_nested_iterate_sequences,
prepare_nested_iterate_bodies,
prepare_nested_iterate_sequences,
@@ -629,6 +631,7 @@ class _GenericGraphSchedulerAdapter:
can_use_nested_iterate_sequence_planner(self._state)
or can_use_three_level_nested_iterate_sequence_planner(self._state)
or can_use_four_level_nested_iterate_sequence_planner(self._state)
+ or can_use_five_level_nested_iterate_sequence_planner(self._state)
)
if not nested_iterate_sequence:
self._mark_source_node_complete(exec_node_id)
@@ -656,6 +659,8 @@ class _GenericGraphSchedulerAdapter:
prepare_three_level_nested_iterate_sequences(self._state)
elif can_use_four_level_nested_iterate_sequence_planner(self._state):
prepare_four_level_nested_iterate_sequences(self._state)
+ elif can_use_five_level_nested_iterate_sequence_planner(self._state):
+ prepare_five_level_nested_iterate_sequences(self._state)
else:
self._try_materialize_deferred_nested_for_body(exec_node_id)
if finalized_for_exec_node_id is None:
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 84ea8c6c0f..c3712ef049 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -685,6 +685,78 @@ def _four_level_nested_iterate_chain_graph(*, outer_collection: list[list[list[l
return graph
+def _five_level_nested_iterate_chain_graph(
+ *, outer_collection: list[list[list[list[list[str]]]]] | None = None
+) -> Graph:
+ """Exact five-level serial nested-iterator shape."""
+ graph = Graph()
+ graph.add_node(
+ CollectionConcatInvocation(
+ id="outer_source",
+ first=[
+ [
+ [[["a", "b"]], [["c"]]],
+ [[["d"]]],
+ ],
+ [[[["e"]]]],
+ ]
+ if outer_collection is None
+ else outer_collection,
+ )
+ )
+ graph.add_node(IterateInvocation(id="outer_iterate"))
+ graph.add_node(CollectionConcatInvocation(id="level1_collection"))
+ graph.add_node(IterateInvocation(id="level1_iterate"))
+ graph.add_node(CollectionConcatInvocation(id="level2_collection"))
+ graph.add_node(IterateInvocation(id="level2_iterate"))
+ graph.add_node(CollectionConcatInvocation(id="level3_collection"))
+ graph.add_node(IterateInvocation(id="level3_iterate"))
+ graph.add_node(CollectionConcatInvocation(id="level4_collection"))
+ graph.add_node(IterateInvocation(id="level4_iterate"))
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+
+ 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_source", "collection", "outer_iterate", "collection")
+ connect("outer_iterate", "item", "level1_collection", "first")
+ connect("level1_collection", "collection", "level1_iterate", "collection")
+ connect("level1_iterate", "item", "level2_collection", "first")
+ connect("level2_collection", "collection", "level2_iterate", "collection")
+ connect("level2_iterate", "item", "level3_collection", "first")
+ connect("level3_collection", "collection", "level3_iterate", "collection")
+ connect("level3_iterate", "item", "level4_collection", "first")
+ connect("level4_collection", "collection", "level4_iterate", "collection")
+ connect("level4_iterate", "item", "body", "value")
+ return graph
+
+
+def _serial_nested_iterate_chain_graph_at_depth(iterate_count: int) -> Graph:
+ """Build one non-empty serial nested-iterator chain for admission-boundary tests."""
+ collection: list[Any] = ["value"]
+ for _ in range(iterate_count - 1):
+ collection = [collection]
+
+ graph = Graph()
+ graph.add_node(CollectionConcatInvocation(id="source", first=collection))
+ previous_iterate_id = "source"
+ previous_field = "collection"
+ for level in range(iterate_count):
+ iterate_id = f"iterate_{level}"
+ graph.add_node(IterateInvocation(id=iterate_id))
+ graph.add_edge(create_edge(previous_iterate_id, previous_field, iterate_id, "collection"))
+ if level == iterate_count - 1:
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+ graph.add_edge(create_edge(iterate_id, "item", "body", "value"))
+ else:
+ preparation_id = f"preparation_{level}"
+ graph.add_node(CollectionConcatInvocation(id=preparation_id))
+ graph.add_edge(create_edge(iterate_id, "item", preparation_id, "first"))
+ previous_iterate_id = preparation_id
+ previous_field = "collection"
+ return graph
+
+
def _direct_iterate_body_collect_graph(
*, collection: list[Any] | None = None, with_after: bool = False, downstream_count: int | None = None
) -> Graph:
@@ -2528,6 +2600,121 @@ def test_four_level_nested_iterate_failure_matches_compatibility() -> None:
assert _state_projection(generic_state) == _state_projection(compatibility_state)
+def test_five_level_nested_iterate_matches_compatibility() -> None:
+ graph = _five_level_nested_iterate_chain_graph()
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),
+ ):
+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))
+ compatibility_trace, compatibility_state = _run(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.is_complete()
+ assert compatibility_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
+ )
+ assert sorted(
+ generic_state._get_iteration_path(exec_id)
+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")
+ ) == [
+ (0, 0, 0, 0, 0),
+ (0, 0, 0, 0, 1),
+ (0, 0, 1, 0, 0),
+ (0, 1, 0, 0, 0),
+ (1, 0, 0, 0, 0),
+ ]
+
+
+ ("outer_collection", "expected_body_paths"),
+ [
+ ([], []),
+ ([[], [[[["c"]]]]], [(1, 0, 0, 0, 0)]),
+ ([[[[]]]], []),
+ ([[[[], []]]], []),
+ ],
+ ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],
+)
+def test_five_level_nested_iterate_closes_empty_frames(
+ outer_collection: list[list[list[list[list[str]]]]], expected_body_paths: list[tuple[int, ...]]
+) -> None:
+ graph = _five_level_nested_iterate_chain_graph(outer_collection=outer_collection)
+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))
+ compatibility_trace, compatibility_state = _run(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert (
+ sorted(
+ generic_state._get_iteration_path(exec_id)
+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")
+ )
+ == expected_body_paths
+ )
+
+
+def test_five_level_nested_iterate_rehydrates_without_replay() -> None:
+ graph = _five_level_nested_iterate_chain_graph()
+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))
+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=15)
+
+ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert resumed_state.is_complete()
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+
+
+def test_five_level_nested_iterate_failure_matches_compatibility() -> None:
+ graph = _five_level_nested_iterate_chain_graph()
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),
+ ):
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ fail_source_id="body",
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ fail_source_id="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 generic_trace.count("body") == 1
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+
+
+def test_six_level_nested_iterate_remains_on_compatibility_fallback() -> None:
+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(6))
+ materializer = state._materializer()
+ with patch.object(materializer, "prepare", wraps=materializer.prepare) as prepare:
+ trace, state = _run(state)
+
+ assert trace.count("body") == 1
+ assert state.is_complete()
+ assert prepare.call_count > 0
+
+
@pytest.mark.parametrize("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])
def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:
compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))