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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(execution): route producer-driven nested iterate
JPPhotodcba4ccc51b9
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 7c65d0e58f..1d99b18b1a 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -81,8 +81,14 @@ The nested planner owns per-outer-frame stream expansion, parent-frame streamidentity, empty closure, `Collect` readiness/hydration, checkpoint rehydration,and failure parity for this shape without calling the materializer's nested-copyhelper. Ordinary nested `For`, deeper or multiple nested iterators,-input-driven outer collections, mixed control flow, and legacy snapshots retain+other input-driven outer collections, mixed control flow, and legacy snapshots retaincompatibility materializer ownership.+The exact eight-node producer-driven extension—one inputless ordinary+collection producer feeding `outer For.collection`, with the same nested body+and one ordinary outer-output consumer—is also generic-routed. It owns outer+input hydration, per-outer-frame stream expansion, checkpoint rehydration, and+failure parity; input-driven inner preparation, deeper or multiple nesting,+mixed control flow, and legacy snapshots remain compatibility-owned.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.@@ -93,7 +99,7 @@ execution-node copies, input hydration, iteration paths, and body expansion. Empdeeper or multiple loops, mixed control flow, and saved-workflow calls remain on the compatibility scheduler untiltheir own differential gates are complete. One narrow fresh two-level nested-`For` shape (one non-empty literal outercollection, one inner `For` sourced from `outer.item`, and no continuation nodes) now uses the generic adapter;-deeper, multiple-child, empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.+deeper, multiple-child, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, andauthorized child-dependency records are stored in`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while@@ -222,8 +228,9 @@ the `Collect.collection` output into the linked `ForReturn`, and one final outerincluding an empty inner collection, remains isolated by its frame path. `Iterate` also records non-empty item streams through the generic effect ledger;for this exact seven-node shape, the private nested planner owns per-outer-framecopy 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,+checkpoint rehydration, and failure parity. The exact producer-driven outer+extension described above is also generic-routed. Ordinary nested `For`, deeper or+multiple nested iterators, other input-driven outer collections, mixed control flow,and legacy snapshots retain compatibility materializer ownership. Thematerializer remains authoritative for fallback expansion, iteration paths, collector grouping, andempty-source compatibility handling. The exact fresh four-node body shape, exact two- or three-stream fan-in shapes,@@ -274,7 +281,7 @@ 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 genericscheduler; the `If` adapter stores frame-local activation dependencies whose private gate state plus persisted tokenchecks control generic branch readiness. Supported static flat `For` graphs and the narrow canonical two-level nested- `For` shape use the generic adapter for readiness and continuation projection; empty/input-driven, deeper/multiple,+`For` shape and the exact producer-driven nested extension use the generic adapter for readiness and continuation projection; empty/input-driven, deeper/multiple,mixed, 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 isdeserialized.@@ -352,9 +359,10 @@ readiness and calls the graph-state generic continuation boundary after each `Fostate, honors `continue_condition`, creates the next prepared iteration when needed, and finalizes `output_collection`and `final_state`. The generic scheduler receives only opaque node IDs and dependencies; it never receives a literalnext node ID. The compatibility continuation bridge remains available only for unsupported loop shapes and explicitly-legacy-loaded snapshots. Empty/input-driven outer collections and deeper, multiple, or unsupported mixed loop shapes-remain compatibility-owned; the narrow canonical two-level nested-`For` shape and the canonical bounded internal-`Iterate`/`Collect` shape are generic-routed. On rehydration, the generic adapter restores the active class-drain+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, and the exact producer-driven outer nested extension are generic-routed. On+rehydration, the generic adapter restores the active class-drainboundary so an in-flight nested stream resumes in the same frame/sequence order.For scheduling is linear in the collection size. The continuation transfers ownership of the remaining collection to thediff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 00c903e1a3..b2dd63186d 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -809,7 +809,7 @@ class GraphExecutionState(BaseModel):if len(for_nodes) != 1 or len(return_nodes) != 1:return Falseouter_for = for_nodes[0]- if not outer_for.collection or self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD):+ if not outer_for.collection and not self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD):return Falseiterate_nodes = [node for node in self.graph.nodes.values() if isinstance(node, IterateInvocation)]@@ -890,7 +890,7 @@ class GraphExecutionState(BaseModel):if self.graph._get_input_edges(final_consumer_id) != final_output_edges:return False- return set(self.graph.nodes) == {+ expected_nodes = {outer_for.id,preparation_node_id,iterate_node.id,@@ -899,6 +899,10 @@ class GraphExecutionState(BaseModel):return_node.id,final_consumer_id,}+ outer_collection_edges = self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD)+ if outer_collection_edges:+ expected_nodes.add(outer_collection_edges[0].source.node_id)+ return set(self.graph.nodes) == expected_nodesdef _can_use_generic_scheduler(self) -> bool:"""Use generic readiness for static graphs and supported direct control flow."""diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.pyindex e4c8740dcc..7a05d3678e 100644--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py@@ -2,7 +2,9 @@from typing import TYPE_CHECKING-from invokeai.app.invocations.loops import ForInvocation+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation+from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocationfrom invokeai.app.services.shared.graph_iterate_planner import (_attach_direct_execution_edges,_create_direct_execution_node_copy,@@ -19,12 +21,37 @@ if TYPE_CHECKING: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+ """Return the supported nested stream contract, excluding broader topologies."""for_node = next((node for node in state.graph.nodes.values() if isinstance(node, ForInvocation)), None)if for_node is None:return None+ outer_collection_edges = state.graph._get_input_edges(for_node.id, COLLECTION_FIELD)+ if len(outer_collection_edges) > 1:+ return None+ input_driven_outer = bool(outer_collection_edges)+ expected_node_count = 8 if input_driven_outer else 7+ expected_edge_count = 8 if input_driven_outer else 7+ if len(state.graph.nodes) != expected_node_count or len(state.graph.edges) != expected_edge_count:+ return None+ if input_driven_outer:+ outer_collection_edge = outer_collection_edges[0]+ producer = state.graph.get_node(outer_collection_edge.source.node_id)+ if (+ outer_collection_edge.destination.node_id != for_node.id+ or outer_collection_edge.source.field != COLLECTION_FIELD+ or isinstance(+ producer,+ (+ CallSavedWorkflowInvocation,+ IfInvocation,+ ForInvocation,+ ForReturnInvocation,+ ),+ )+ or state.graph._get_input_edges(producer.id)+ or state.graph._get_output_edges(producer.id) != [outer_collection_edge]+ ):+ return Nonenested_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 Nonediff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 5cc624d8cd..4573e2ec66 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -568,6 +568,13 @@ def _nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | Nonreturn graph+def _input_driven_nested_for_iterate_collect_graph() -> Graph:+ graph = _nested_for_iterate_collect_graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[["a", "b"], ["c"]]))+ graph.add_edge(create_edge("outer_source", "collection", "outer_for", "collection"))+ return graph++def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, with_after: bool = False, downstream_count: int | None = None) -> Graph:@@ -1882,6 +1889,67 @@ def test_nested_for_iterate_collect_generic_failure_does_not_release_outer_returassert _state_projection(generic_state) == _state_projection(compatibility_state)+def test_input_driven_nested_for_iterate_collect_uses_generic_stream_planner() -> None:+ generic_state = GraphExecutionState(graph=_input_driven_nested_for_iterate_collect_graph())+ compatibility_state = GraphExecutionState(graph=_input_driven_nested_for_iterate_collect_graph())++ assert generic_state._can_use_generic_scheduler()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "_create_nested_iterate_body_iteration",+ side_effect=AssertionError("input-driven nested Iterate/Collect used materializer copy creation"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(generic_state)+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ compatibility_state,+ 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)+ after_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ assert generic_state.results[after_exec_id].value == [["a", "b"], ["c"]]+++def test_input_driven_nested_for_iterate_collect_rehydrates_without_replay() -> None:+ graph = _input_driven_nested_for_iterate_collect_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=4)++ restored = load_execution_state(dump_execution_state(partial_state))+ resumed_trace, resumed_state = _run(restored)++ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+++def test_input_driven_nested_for_iterate_collect_failure_matches_compatibility() -> None:+ graph = _input_driven_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 "nested_collect" not in generic_trace+ assert "outer_return" not in generic_trace+ assert "after" not in generic_state.source_prepared_mapping+ assert _state_projection(generic_state) == _state_projection(compatibility_state)++@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))