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 canonical nested iterate generically
JPPhoto252bc02e8ddf
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex f87ab65727..6fa8b30f14 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -63,15 +63,22 @@ Nested `For` boundaries are supported recursively when each inner boundary has icontinuation. Independent inner loops must all feed one explicit fan-in continuation; collection concatenation, zipping,or Cartesian semantics come from the connected collection operation, not from loop scheduling.-A bounded internal `Iterate` is supported only when one `Collect` collapses its item dimension before the parent-`ForReturn`:+A bounded internal `Iterate` is supported only for the canonical outer-`For` shape: one ordinary preparation node+converts `For.item` to the inner collection, one ordinary body node consumes `Iterate.item`, and one `Collect` collapses+that item dimension before the parent `ForReturn`:```text-For.item -> Iterate.collection+For.item -> preparation -> Iterate.collectionIterate.item -> body -> Collect.itemCollect.collection -> ForReturn.output```+The fresh generic scheduler admits this exact shape when the outer collection is a non-empty literal and there is one+final consumer of `For.output_collection`. Each outer frame is isolated, including when the preparation node produces+an empty inner collection. A checkpoint after any nested iterator boundary restores the generic class-drain state and+continues the same frame/stream order. Input-driven outer collections, additional loop or control-flow nodes, escaped+body paths, and other mixed shapes remain on the compatibility scheduler.+Unsupported shapes, including independent iterator-derived body inputs, mixed nested `For`/`Iterate` bodies, escapingbody paths, ambiguous returns, and arbitrary cyclic graphs, are rejected before execution.@@ -95,17 +102,20 @@ pair now uses the generic scheduler adapter for readiness and continuation transgeneric continuation boundary: it carries returned state, honors `continue_condition`, materializes the next bodyiteration, and finalizes the aggregate. The generic scheduler remains opaque and never receives a literal successornode ID. The compatibility continuation bridge is retained only for unsupported loop shapes and explicitly-legacy-loaded snapshots. Empty or input-driven collections, deeper or multiple nested loops, and mixed control flow-remain on the compatibility scheduler; the narrow canonical two-level nested-`For` shape is now generic-routed. This-additive effect seam does not claim generic scheduling for the remaining shapes. `Iterate` records ordered item tokens in+legacy-loaded snapshots. Empty or input-driven outer collections, deeper or multiple nested loops, and unsupported mixed+control flow remain on the compatibility scheduler; the narrow canonical two-level nested-`For` shape and the exact+bounded outer-`For`/`Iterate`/`Collect` shape are now generic-routed. This additive effect seam does not claim generic+scheduling for the remaining shapes. `Iterate` records ordered item tokens ina closed `StreamBuffer`; an empty `Iterate` records anexplicit empty close. A direct `Iterate.item` consumer waits for the canonical stream to close, then `Collect` consumesits ordered values; a missing stream falls back to materialized results for legacy snapshots. The materializer stillowns iterator expansion, iteration paths, collector grouping, collection-input hydration, and empty-source closure.Focused compatibility coverage now proves empty, nested, fan-in, partial/rehydrated, failed, canceled, and retriedIterate/Collect sessions. This is evidence for the current adapters; it does not remove materialization or queue-ownership. Direct `Iterate`/`Collect`-only graphs now use the generic scheduler adapter: its readiness predicate waits-for the canonical stream to close, and completion mirrors Iterate outputs into that ledger before releasing Collect.+ownership. Direct `Iterate`/`Collect`-only graphs and the exact bounded nested shape now use the generic scheduler+adapter: its readiness predicate waits for the canonical stream to close, and completion mirrors Iterate outputs into+that ledger before releasing Collect. Rehydration restores the active class-drain boundary so nested stream order is+preserved across dump/load.Materialization still owns copy expansion, iteration paths, grouping, and explicit empty closure; mixed control-flow andqueue lifecycle remain compatibility-owned. `loop_linkage` remains association metadata and never becomes a data token.diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 8f28f9feb8..5e07e026fb 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -149,9 +149,12 @@ other control-flow nodes also use that adapter: its readiness predicate waits focompletion mirrors Iterate outputs into the stream ledger. A fresh graph with one static, non-empty flat`For`/`ForReturn` pair also uses the adapter for readiness and continuation transitions; graph state owns theinvocation-specific continuation boundary while the generic scheduler remains opaque. Empty or input-driven `For`-collections, deeper or multiple loops, saved-workflow calls, and mixed control-flow shapes continue to use the legacy-compatibility scheduler until their differential coverage is complete. The narrow canonical two-level nested-`For`-shape is generic-routed. `Iterate` also records non-empty item streams through the generic effect ledger;+collections, deeper or multiple loops, saved-workflow calls, and unsupported mixed control-flow shapes continue to use+the legacy compatibility scheduler until their differential coverage is complete. The narrow canonical two-level+nested-`For` shape and the canonical outer-`For`/bounded-`Iterate`/`Collect` shape are generic-routed. The latter 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,+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 expansion, iteration paths, collector grouping, andempty-source compatibility handling. Direct `Collect.item` consumers now use the closed stream ledger when available;the full Iterate/Collect compatibility matrix covers empty, nested, fan-in, partial rehydration, failure, cancellation,@@ -258,8 +261,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 collections and deeper, multiple, or mixed loop shapes remain-compatibility-owned; the narrow canonical two-level nested-`For` shape is generic-routed.+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+boundary so an in-flight nested stream resumes in the same frame/sequence order.`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token@@ -313,8 +318,9 @@ which creates the next prepared iteration, aggregates outputs, and finalizes thesupported flat loop. The compatibility bridge remains for empty/input-driven,deeper/multiple nested, mixed-loop, and legacy-snapshot execution; those pathsretain their existing materialization and linkage ownership. The supported-fresh static flat `For`/`ForReturn` shape and the narrow canonical two-level-nested-`For` shape use the generic adapter. For+fresh static flat `For`/`ForReturn` shape, the narrow canonical two-level+nested-`For` shape, and the canonical bounded internal `Iterate`/`Collect`+shape use the generic adapter. For`If`, generic readiness consumes opaque frame-local plan dependencies and requiresboth matching private `ActivationGate` runtime state and a persisted activation token. Fresh resolution attaches onlythe selected branch edge; the forced compatibility `_ExecutionScheduler` path preserves this behavior for fresh states,@@ -329,8 +335,10 @@ existing web/webv2 interactions.The test-only differential harness at`tests/app/services/shared/test_execution_engine_differential.py` comparesgeneric and forced-compatibility scheduling for static DAGs, a constructed-mixed/nested `If` graph, the supported static flat `For`/`ForReturn` shape, and-the narrow canonical nested-`For` shape.+mixed/nested `If` graph, the supported static flat `For`/`ForReturn` shape, the+narrow canonical nested-`For` shape, and the canonical nested+`For`/`Iterate`/`Collect` shape. The latter covers empty inner collections and+dump/load resume ordering.Its fixture corpus covers fresh completion, true/false branch selection, nestedbranch isolation, partial checkpoints, versioned rehydration, in-flight claimreplay, activation-token persistence, injected failure, loop continuation,diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex e82707b43e..ec99cbb6a1 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -2310,6 +2310,22 @@ class _GenericGraphSchedulerAdapter:self._initializing = Falseself._sync_indegree()self._project_ready_nodes()+ self._restore_active_class()++ def _restore_active_class(self) -> None:+ """Continue draining the class that produced the latest durable result."""++ if not self._state.results:+ return+ last_exec_node_id = next(reversed(self._state.results))+ last_plan_node = self._scheduler.plan.nodes.get(last_exec_node_id)+ if last_plan_node is None:+ return+ if any(+ self._scheduler.plan.nodes[ready_node_id].class_name == last_plan_node.class_name+ for ready_node_id in self._scheduler.ready_ids+ ):+ self._scheduler._active_class = last_plan_node.class_namedef _is_node_activation_ready(self, exec_node_id: str) -> bool:"""Require every frame-local activation dependency to be satisfied."""@@ -4907,7 +4923,7 @@ class GraphExecutionState(BaseModel):self._tx_set_attr(existing, "value", copydeep(token.value))def _apply_generic_for_continuation(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:- """Apply the graph-state continuation boundary for a generic flat For run."""+ """Apply the graph-state continuation boundary for a supported fresh For run."""if not isinstance(output, ForReturnInvocationOutput):return None@@ -4964,17 +4980,16 @@ class GraphExecutionState(BaseModel):return self._apply_generic_for_continuation(exec_node_id, output)def _can_use_generic_for_scheduler(self) -> bool:- """Allow generic routing only for one flat For body with no other control-flow node."""+ """Allow generic routing only for the explicitly supported fresh For shapes."""if self._legacy_snapshot_loaded:return False- if any(- isinstance(node, (IterateInvocation, CollectInvocation, IfInvocation, CallSavedWorkflowInvocation))- for node in self.graph.nodes.values()- ):+ if any(isinstance(node, (IfInvocation, CallSavedWorkflowInvocation)) for node in self.graph.nodes.values()):return Falsefor_nodes = [node for node in self.graph.nodes.values() if isinstance(node, ForInvocation)]return_nodes = [node for node in self.graph.nodes.values() if isinstance(node, ForReturnInvocation)]+ if any(isinstance(node, (IterateInvocation, CollectInvocation)) for node in self.graph.nodes.values()):+ return self._can_use_generic_nested_iterate_scheduler(for_nodes, return_nodes)if len(for_nodes) == 2 and len(return_nodes) == 2:source_graph = self._get_source_graph_flat()outer_for = next(@@ -5019,6 +5034,102 @@ class GraphExecutionState(BaseModel):if node_id != return_node_id)+ def _can_use_generic_nested_iterate_scheduler(+ self, for_nodes: list[ForInvocation], return_nodes: list[ForReturnInvocation]+ ) -> bool:+ """Admit only the bounded single-outer-For Iterate/Collect contract."""++ if len(for_nodes) != 1 or len(return_nodes) != 1:+ return False+ outer_for = for_nodes[0]+ if not outer_for.collection or self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD):+ return False++ iterate_nodes = [node for node in self.graph.nodes.values() if isinstance(node, IterateInvocation)]+ collect_nodes = [node for node in self.graph.nodes.values() if isinstance(node, CollectInvocation)]+ if len(iterate_nodes) != 1 or len(collect_nodes) != 1:+ return False+ iterate_node = iterate_nodes[0]+ collect_node = collect_nodes[0]+ 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:+ return False++ iterate_collection_edges = self.graph._get_input_edges(iterate_node.id, COLLECTION_FIELD)+ if len(iterate_collection_edges) != 1:+ return False+ preparation_node_id = iterate_collection_edges[0].source.node_id+ preparation_node = self.graph.get_node(preparation_node_id)+ if isinstance(preparation_node, (ForInvocation, ForReturnInvocation, IterateInvocation, CollectInvocation)):+ return False+ preparation_inputs = self.graph._get_input_edges(preparation_node_id)+ if len(preparation_inputs) != 1 or (+ preparation_inputs[0].source.node_id != outer_for.id or preparation_inputs[0].source.field != ITEM_FIELD+ ):+ return False+ if self.graph._get_output_edges(outer_for.id, ITEM_FIELD) != preparation_inputs:+ return False++ collect_item_edges = self.graph._get_input_edges(collect_node.id, ITEM_FIELD)+ if len(collect_item_edges) != 1:+ return False+ body_node_id = collect_item_edges[0].source.node_id+ body_node = self.graph.get_node(body_node_id)+ if body_node_id == preparation_node_id or isinstance(+ body_node, (ForInvocation, ForReturnInvocation, IterateInvocation, CollectInvocation)+ ):+ return False+ body_inputs = self.graph._get_input_edges(body_node_id)+ if len(body_inputs) != 1 or (+ body_inputs[0].source.node_id != iterate_node.id or body_inputs[0].source.field != ITEM_FIELD+ ):+ return False+ if self.graph._get_output_edges(iterate_node.id, ITEM_FIELD) != body_inputs:+ return False+ if self.graph._get_output_edges(body_node_id) != collect_item_edges:+ return False++ if self.graph._get_input_edges(collect_node.id, COLLECTION_FIELD):+ return False+ collect_output_edges = self.graph._get_output_edges(collect_node.id, COLLECTION_FIELD)+ if len(collect_output_edges) != 1 or (+ collect_output_edges[0].destination.node_id != return_node.id+ or collect_output_edges[0].destination.field != "output"+ ):+ return False+ if self.graph._get_input_edges(return_node.id) != collect_output_edges:+ return False+ if self.graph._get_linked_for_return_id(outer_for.id) != return_node.id:+ return False++ final_output_edges = self.graph._get_for_final_output_edges(outer_for.id)+ if len(final_output_edges) != 1:+ return False+ final_consumer_id = final_output_edges[0].destination.node_id+ final_consumer = self.graph.get_node(final_consumer_id)+ if final_consumer_id in {+ outer_for.id,+ iterate_node.id,+ body_node_id,+ collect_node.id,+ return_node.id,+ } or isinstance(final_consumer, (ForInvocation, ForReturnInvocation, IterateInvocation, CollectInvocation)):+ return False+ if self.graph._get_input_edges(final_consumer_id) != final_output_edges:+ return False++ return set(self.graph.nodes) == {+ outer_for.id,+ preparation_node_id,+ iterate_node.id,+ body_node_id,+ collect_node.id,+ return_node.id,+ final_consumer_id,+ }+def _can_use_generic_scheduler(self) -> bool:"""Use generic readiness for static graphs and supported direct control flow."""diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 4fc57b0afe..a2ff4f54ee 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -9,7 +9,12 @@ import pytestfrom pydantic import ValidationErrorfrom invokeai.app.invocations.logic import IfInvocation-from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation, LoopState, StateSetInvocation+from invokeai.app.invocations.loops import (+ ForInvocation,+ ForReturnInvocation,+ LoopState,+ StateSetInvocation,+)from invokeai.app.invocations.math import AddInvocationfrom invokeai.app.invocations.primitives import BooleanInvocation, BooleanOutputfrom invokeai.app.services.shared import graph as graph_module@@ -20,16 +25,24 @@ from invokeai.app.services.shared.execution_state_migration import (load_execution_state,)from invokeai.app.services.shared.graph import (+ CollectInvocation,Edge,EdgeConnection,Graph,GraphExecutionState,+ IterateInvocation,_ExecutionScheduler,_GenericGraphSchedulerAdapter,_IfActivationCompiler,)from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context-from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocation, create_loop_linkage+from tests.test_nodes import (+ AnyTypeTestInvocation,+ ErrorInvocation,+ PolymorphicStringTestInvocation,+ UnionCollectionTestInvocation,+ create_loop_linkage,+)FIXTURE_PATH = Path(__file__).parents[3] / "fixtures" / "execution_engine" / "static_dag_v1.json"@@ -178,7 +191,9 @@ def _flat_for_graph(def _nested_for_graph(*, outer_collection: list[list[str]] | None = None) -> Graph:graph = Graph()- graph.add_node(ForInvocation(id="outer_for", collection=outer_collection or [["a", "b"], ["c"]]))+ graph.add_node(+ ForInvocation(id="outer_for", collection=[["a", "b"], ["c"]] if outer_collection is None else outer_collection)+ )graph.add_node(ForInvocation(id="inner_for"))graph.add_node(AnyTypeTestInvocation(id="inner_body"))graph.add_node(ForReturnInvocation(id="inner_return"))@@ -203,6 +218,34 @@ def _nested_for_graph(*, outer_collection: list[list[str]] | None = None) -> Grareturn graph+def _nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | None = None) -> Graph:+ graph = Graph()+ graph.add_node(ForInvocation(id="outer_for", collection=outer_collection or [["a", "b"], ["c"]]))+ graph.add_node(PolymorphicStringTestInvocation(id="nested_collection"))+ graph.add_node(IterateInvocation(id="nested_iterate"))+ graph.add_node(AnyTypeTestInvocation(id="nested_body"))+ graph.add_node(CollectInvocation(id="nested_collect"))+ graph.add_node(ForReturnInvocation(id="outer_return"))+ graph.add_node(AnyTypeTestInvocation(id="after"))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source, field=source_field),+ destination=EdgeConnection(node_id=destination, field=destination_field),+ )+ )++ connect("outer_for", "item", "nested_collection", "value")+ connect("nested_collection", "collection", "nested_iterate", "collection")+ connect("nested_iterate", "item", "nested_body", "value")+ connect("nested_body", "value", "nested_collect", "item")+ connect("nested_collect", "collection", "outer_return", "output")+ connect("outer_for", "output_collection", "after", "value")+ graph.add_edge(create_loop_linkage("outer_for", "outer_return"))+ return graph++def _flat_for_state_graph(continue_condition: bool) -> Graph:graph = Graph()graph.add_node(ForInvocation(id="for", collection=[1, 2, 3], state=LoopState(values={"count": 0})))@@ -1057,6 +1100,90 @@ def test_nested_for_generic_path_rehydrates_after_inner_completion() -> None:assert _state_projection(compatibility_resumed) == _state_projection(expected_state)+def test_nested_for_iterate_collect_generic_and_compatibility_paths_have_matching_completion() -> 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())+ generic_trace, generic_state = _run(generic_state)++ assert (+ generic_trace+ == compatibility_trace+ == [+ "outer_for",+ "nested_collection",+ "nested_iterate",+ "nested_iterate",+ "nested_body",+ "nested_body",+ "nested_collect",+ "outer_return",+ "outer_for",+ "nested_collection",+ "nested_iterate",+ "nested_body",+ "nested_collect",+ "outer_return",+ "after",+ ]+ )+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ for state in (generic_state, compatibility_state):+ after_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ assert state.results[after_exec_id].value == [["a", "b"], ["c"]]+++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(+ compatibility_state,+ force_compatibility_scheduler=True,+ )+ generic_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph(outer_collection=[[], ["c"]]))+ generic_trace, generic_state = _run(generic_state)++ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ for state in (generic_state, compatibility_state):+ after_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ assert state.results[after_exec_id].value == [[], ["c"]]+++def test_nested_for_iterate_collect_generic_rehydrates_after_inner_completion() -> None:+ expected_state = GraphExecutionState(graph=_nested_for_iterate_collect_graph())+ expected_state._execution_scheduler = _ExecutionScheduler(expected_state)+ expected_trace, expected_state = _run(expected_state)++ state = GraphExecutionState(graph=_nested_for_iterate_collect_graph())+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ partial_trace, partial_state = _run(state, stop_after=3)+ 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 isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert _state_projection(resumed_state) == _state_projection(expected_state)++def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None:trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))