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

JPPhoto4ed63e191e4e
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index d6220ed3d9..9c9cc56642 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -200,8 +200,8 @@ plan/scheduler through a compatibility projection. This is intentional:
the generic records preserve tested loop semantics first, while the old execution graph remains the fallback for control
lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-time
graph JSON.
-Exact fresh serial nested-`Iterate` chains through seven levels use the generic planner for ordered frame expansion,
-empty-stream closure, checkpoint rehydration, source completion, and failure parity. Eight-level or deeper chains,
+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
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 9d54ed249f..69e9ca1422 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -126,18 +126,23 @@ 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. Eight-level or deeper chains and all other expanded, fan-in,
-sibling, other mixed, `For`, `Collect`, and legacy shapes remain compatibility-owned.
+same guarantees.
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.
The exact fifteen-node/fourteen-edge serial chain extends the same planner to
seven `Iterate` nodes and seven-component frame paths, with the same empty-stream,
-checkpoint, source-completion, and failure-parity guarantees. Eight-level or
-deeper chains, three or more body-mediated branches, fan-in with four or more direct branches,
+checkpoint, source-completion, and failure-parity guarantees.
+Three or more body-mediated branches, fan-in with four or more direct branches,
broader nested iterators, and mixed control flow outside the bounded
per-item topology retain materializer copy expansion,
grouping, and empty-source handling on the legacy compatibility route.
+
+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.
A fresh graph with exactly one static, non-empty `For`/`ForReturn` pair and ordinary body nodes also uses the generic
adapter. 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
@@ -271,7 +276,7 @@ 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-, five-,
-and six- and seven-level serial nested-`Iterate` chains are generic-routed. The nested `For`
+and six-, seven-, and eight-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,
@@ -279,11 +284,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`, eight-level
+extension described above is also generic-routed. Ordinary 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,
-or deeper-than-seven-level iterator topology. The
+or deeper-than-eight-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
@@ -333,9 +338,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 seven-level serial nested-
+ `For` shape, the exact producer-driven nested extension, and the bounded two- through eight-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, unsupported input-driven, eight-level or deeper, mixed graphs outside that topology, and saved-workflow
+ continuation projection; empty input-driven, unsupported input-driven, nine-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.
@@ -418,7 +423,7 @@ The generic scheduler receives only opaque node IDs and dependencies; it never r
compatibility continuation bridge remains available only for unsupported loop shapes and explicitly legacy-loaded snapshots.
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
internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension, and the bounded two- through
- six- and seven-level serial nested-`Iterate` chains are generic-routed. On
+ six-, seven-, and eight-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 75452e6c62..931a8b8238 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -113,6 +113,7 @@ from invokeai.app.services.shared.graph_models import (
WorkflowCallStatus, # noqa: F401
)
from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_eight_level_nested_iterate_sequence_planner,
can_use_five_level_nested_iterate_sequence_planner,
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
@@ -120,6 +121,7 @@ from invokeai.app.services.shared.graph_nested_iterate_planner import (
can_use_seven_level_nested_iterate_sequence_planner,
can_use_six_level_nested_iterate_sequence_planner,
can_use_three_level_nested_iterate_sequence_planner,
+ prepare_eight_level_nested_iterate_sequences,
prepare_five_level_nested_iterate_sequences,
prepare_four_level_nested_iterate_sequences,
prepare_nested_iterate_bodies,
@@ -2436,6 +2438,11 @@ class GraphExecutionState(BaseModel):
) and can_use_seven_level_nested_iterate_sequence_planner(self):
prepare_seven_level_nested_iterate_sequences(self)
return self._get_next_node()
+ if isinstance(
+ self._scheduler(), _GenericGraphSchedulerAdapter
+ ) and can_use_eight_level_nested_iterate_sequence_planner(self):
+ prepare_eight_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 147f464b79..53bcf9542a 100644
--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py
+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py
@@ -124,6 +124,15 @@ def can_use_seven_level_nested_iterate_sequence_planner(state: "GraphExecutionSt
)
+def can_use_eight_level_nested_iterate_sequence_planner(state: "GraphExecutionState") -> bool:
+ """Check the exact eight-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=8)
+ 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)
@@ -600,3 +609,9 @@ def prepare_seven_level_nested_iterate_sequences(state: "GraphExecutionState") -
"""Prepare the exact seven-level nested Iterate chain."""
if can_use_seven_level_nested_iterate_sequence_planner(state):
_prepare_nested_iterate_sequence(state, iterate_count=7)
+
+
+def prepare_eight_level_nested_iterate_sequences(state: "GraphExecutionState") -> None:
+ """Prepare the exact eight-level nested Iterate chain."""
+ if can_use_eight_level_nested_iterate_sequence_planner(state):
+ _prepare_nested_iterate_sequence(state, iterate_count=8)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index c6a0670a4d..e08d0efeb3 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -13,6 +13,7 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionScheduler,
)
from invokeai.app.services.shared.graph_nested_iterate_planner import (
+ can_use_eight_level_nested_iterate_sequence_planner,
can_use_five_level_nested_iterate_sequence_planner,
can_use_four_level_nested_iterate_sequence_planner,
can_use_nested_iterate_planner,
@@ -20,6 +21,7 @@ from invokeai.app.services.shared.graph_nested_iterate_planner import (
can_use_seven_level_nested_iterate_sequence_planner,
can_use_six_level_nested_iterate_sequence_planner,
can_use_three_level_nested_iterate_sequence_planner,
+ prepare_eight_level_nested_iterate_sequences,
prepare_five_level_nested_iterate_sequences,
prepare_four_level_nested_iterate_sequences,
prepare_nested_iterate_bodies,
@@ -638,6 +640,7 @@ class _GenericGraphSchedulerAdapter:
or can_use_five_level_nested_iterate_sequence_planner(self._state)
or can_use_six_level_nested_iterate_sequence_planner(self._state)
or can_use_seven_level_nested_iterate_sequence_planner(self._state)
+ or can_use_eight_level_nested_iterate_sequence_planner(self._state)
)
if not nested_iterate_sequence:
self._mark_source_node_complete(exec_node_id)
@@ -671,6 +674,8 @@ class _GenericGraphSchedulerAdapter:
prepare_six_level_nested_iterate_sequences(self._state)
elif can_use_seven_level_nested_iterate_sequence_planner(self._state):
prepare_seven_level_nested_iterate_sequences(self._state)
+ elif can_use_eight_level_nested_iterate_sequence_planner(self._state):
+ prepare_eight_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 4c83461e3d..9191af8fe2 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -2975,8 +2975,104 @@ def test_seven_level_nested_iterate_failure_matches_compatibility() -> None:
assert generic_trace.count("body") == 1
-def test_eight_level_nested_iterate_remains_on_compatibility_fallback() -> None:
- state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(8))
+def test_eight_level_nested_iterate_matches_compatibility() -> None:
+ graph = _serial_nested_iterate_chain_graph_at_depth(8)
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("eight-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)]
+
+
+ ("outer_collection", "expected_body_paths"),
+ [
+ ([], []),
+ ([[], _nested_collection("c", 7)], [(1, 0, 0, 0, 0, 0, 0, 0)]),
+ ([_nested_collection([], 6)], []),
+ ],
+ ids=["outer-empty", "mixed-empty", "deepest-empty"],
+)
+def test_eight_level_nested_iterate_closes_empty_frames(
+ outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]
+) -> None:
+ graph = _serial_nested_iterate_chain_graph_at_depth(8)
+ graph.get_node("source").first = outer_collection
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("eight-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_eight_level_nested_iterate_rehydrates_without_replay() -> None:
+ graph = _serial_nested_iterate_chain_graph_at_depth(8)
+ 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_eight_level_nested_iterate_failure_matches_compatibility() -> None:
+ graph = _serial_nested_iterate_chain_graph_at_depth(8)
+ with patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("eight-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_nine_level_nested_iterate_remains_on_compatibility_fallback() -> None:
+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(9))
materializer = state._materializer()
with patch.object(materializer, "prepare", wraps=materializer.prepare) as prepare:
trace, state = _run(state)