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 six-level nested iterates

JPPhotof75e9c4fc3e4
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index b0cc88fcf0..4e6244aa19 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -126,8 +126,11 @@ 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. 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,
+same guarantees. Seven-level or deeper chains and all other expanded, fan-in,
sibling, other mixed, `For`, `Collect`, and legacy shapes remain compatibility-owned.
+The exact thirteen-node/twelve-edge serial chain extends the same planner to
+six `Iterate` nodes and six-component frame paths, with the same empty-stream,
+checkpoint, source-completion, and failure-parity guarantees.
Three or more body-mediated branches, fan-in with four or more direct branches,
broader or deeper nested iterators, and mixed control flow outside the bounded
per-item topology retain materializer copy expansion,
@@ -264,8 +267,8 @@ collections, deeper or multiple loops, saved-workflow calls, and unsupported mix
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,
-the exact five-node nested-`Iterate` chain, and the bounded three-, four-, and
-five-level serial nested-`Iterate` chains are generic-routed. The nested `For`
+the exact five-node nested-`Iterate` chain, and the bounded three-, four-, five-,
+and six-level serial nested-`Iterate` chains are generic-routed. The nested `For`
shape has
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,
@@ -273,11 +276,11 @@ 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`, six-level
+extension described above is also generic-routed. Ordinary nested `For`, seven-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,
-or deeper-than-five-level iterator topology. The
+or deeper-than-six-level iterator topology. 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
@@ -327,9 +330,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the generic
scheduler; the `If` adapter stores frame-local activation dependencies whose private gate state plus persisted token
checks control generic branch readiness. Supported static flat `For` graphs and the narrow canonical two-level nested
- `For` shape, the exact producer-driven nested extension, and the bounded two- through five-level serial nested-
+ `For` shape, the exact producer-driven nested extension, and the bounded two- through six-level serial nested-
`Iterate` chains and the bounded per-item `Iterate`/`If`/`Collect` topology use the generic adapter for readiness and
- continuation projection; empty/input-driven, six-level or deeper, mixed graphs outside that topology, and saved-workflow
+ continuation projection; empty/input-driven, seven-level or deeper, mixed graphs outside that topology, and saved-workflow
graphs retain the legacy scheduler. Optional
`ready_order: list[str]` prioritizes classes. Queues are rebuilt from persisted execution state when a session is
deserialized.
@@ -410,8 +413,8 @@ and `final_state`. The generic scheduler receives only opaque node IDs and depen
next node ID. The compatibility continuation bridge remains available only for unsupported loop shapes and explicitly
legacy-loaded snapshots. Unsupported empty/input-driven outer collections and deeper, multiple, or unsupported mixed
loop shapes remain compatibility-owned; the narrow canonical two-level nested-`For` shape, the canonical bounded
-internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension, and the bounded two- through
-five-level serial nested-`Iterate` chains are generic-routed. On
+ internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension, and the bounded two- through
+ six-level serial nested-`Iterate` chains are generic-routed. On
rehydration, the generic adapter restores the active class-drain
boundary so an in-flight nested stream resumes in the same frame/sequence order.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index c6c94d61de..2edaf86da5 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -117,11 +117,13 @@ from invokeai.app.services.shared.graph_nested_iterate_planner import (
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
can_use_nested_iterate_sequence_planner,
+ can_use_six_level_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,
+ prepare_six_level_nested_iterate_sequences,
prepare_three_level_nested_iterate_sequences,
)
from invokeai.app.services.shared.graph_runtime_records import (
@@ -2415,6 +2417,11 @@ class GraphExecutionState(BaseModel):
) and can_use_five_level_nested_iterate_sequence_planner(self):
prepare_five_level_nested_iterate_sequences(self)
return self._get_next_node()
+ if isinstance(
+ self._scheduler(), _GenericGraphSchedulerAdapter
+ ) and can_use_six_level_nested_iterate_sequence_planner(self):
+ prepare_six_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 e33ea15526..dc85525cc5 100644
--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py
+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py
@@ -106,6 +106,15 @@ def can_use_five_level_nested_iterate_sequence_planner(state: "GraphExecutionSta
)
+def can_use_six_level_nested_iterate_sequence_planner(state: "GraphExecutionState") -> bool:
+ """Check the exact six-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=6)
+ 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)
@@ -570,3 +579,9 @@ def prepare_five_level_nested_iterate_sequences(state: "GraphExecutionState") ->
"""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)
+
+
+def prepare_six_level_nested_iterate_sequences(state: "GraphExecutionState") -> None:
+ """Prepare the exact six-level nested Iterate chain."""
+ if can_use_six_level_nested_iterate_sequence_planner(state):
+ _prepare_nested_iterate_sequence(state, iterate_count=6)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index e5dcdae371..e361ae115d 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -17,11 +17,13 @@ from invokeai.app.services.shared.graph_nested_iterate_planner import (
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
can_use_nested_iterate_sequence_planner,
+ can_use_six_level_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,
+ prepare_six_level_nested_iterate_sequences,
prepare_three_level_nested_iterate_sequences,
)
from invokeai.app.services.shared.graph_validation import CollectInvocation, IterateInvocation, nx
@@ -632,6 +634,7 @@ class _GenericGraphSchedulerAdapter:
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)
+ or can_use_six_level_nested_iterate_sequence_planner(self._state)
)
if not nested_iterate_sequence:
self._mark_source_node_complete(exec_node_id)
@@ -661,6 +664,8 @@ class _GenericGraphSchedulerAdapter:
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)
+ elif can_use_six_level_nested_iterate_sequence_planner(self._state):
+ prepare_six_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 c3712ef049..39df73c6df 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -731,6 +731,72 @@ def _five_level_nested_iterate_chain_graph(
return graph
+def _six_level_nested_iterate_chain_graph(
+ *, outer_collection: list[list[list[list[list[list[str]]]]]] | None = None
+) -> Graph:
+ """Exact six-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(CollectionConcatInvocation(id="level5_collection"))
+ graph.add_node(IterateInvocation(id="level5_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", "level5_collection", "first")
+ connect("level5_collection", "collection", "level5_iterate", "collection")
+ connect("level5_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"]
@@ -2704,8 +2770,117 @@ def test_five_level_nested_iterate_failure_matches_compatibility() -> None:
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))
+def test_six_level_nested_iterate_matches_compatibility() -> None:
+ graph = _six_level_nested_iterate_chain_graph()
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("six-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 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, 0, 0, 1),
+ (0, 0, 0, 1, 0, 0),
+ (0, 0, 1, 0, 0, 0),
+ (1, 0, 0, 0, 0, 0),
+ ]
+
+
+def _nested_collection(value: Any, depth: int) -> list[Any]:
+ collection: Any = [value]
+ for _ in range(depth - 1):
+ collection = [collection]
+ return collection
+
+
+ ("outer_collection", "expected_body_paths"),
+ [
+ ([], []),
+ ([[], _nested_collection("c", 5)], [(1, 0, 0, 0, 0, 0)]),
+ ([_nested_collection([], 4)], []),
+ ([_nested_collection([], 3)], []),
+ ],
+ ids=["outer-empty", "mixed-empty", "deepest-empty", "intermediate-empty"],
+)
+def test_six_level_nested_iterate_closes_empty_frames(
+ outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]
+) -> None:
+ graph = _six_level_nested_iterate_chain_graph(outer_collection=outer_collection)
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("six-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 (
+ 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_six_level_nested_iterate_rehydrates_without_replay() -> None:
+ graph = _six_level_nested_iterate_chain_graph()
+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))
+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)
+
+ 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)
+
+
+def test_six_level_nested_iterate_failure_matches_compatibility() -> None:
+ graph = _six_level_nested_iterate_chain_graph()
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("six-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
+
+
+def test_seven_level_nested_iterate_remains_on_compatibility_fallback() -> None:
+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(7))
materializer = state._materializer()
with patch.object(materializer, "prepare", wraps=materializer.prepare) as prepare:
trace, state = _run(state)