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 For generically
JPPhoto94735c52ac5b
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex 2e0a07ec2a..f87ab65727 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -95,8 +95,10 @@ 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, nested or multiple loops, and mixed control flow remain on the-compatibility scheduler; this additive effect seam does not claim generic scheduling for those shapes. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty `Iterate` records an+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+a 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.@@ -152,7 +154,7 @@ ports and literal successor IDs remain absent, while unsupported loop shapes andtheir compatibility paths until differential coverage proves their generic replacements.The engine still owns runtime node materialization and queue readiness for loop-containing graphs that require empty or-input-driven `For`, nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs,+input-driven `For`, deeper nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs,direct `Iterate`/`Collect`-only graphs, and supported fresh static flat `For` graphs now use the generic opaqueplan/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 controldiff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 0a68187900..8f28f9feb8 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -25,8 +25,10 @@ A fresh graph with exactly one static, non-empty `For`/`ForReturn` pair and ordiadapter. It projects readiness and invokes the graph-state continuation boundary, which selects the next iteration orfinalizes the aggregate without exposing a successor node ID to the generic scheduler. The materializer still ownsexecution-node copies, input hydration, iteration paths, and body expansion. Empty or input-driven collections,-nested or multiple loops, mixed control flow, and saved-workflow calls remain on the compatibility scheduler until-their own differential gates are complete.+deeper or multiple loops, mixed control flow, and saved-workflow calls remain on the compatibility scheduler until+their own differential gates are complete. One narrow fresh two-level nested-`For` shape (one non-empty literal outer+collection, 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.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@@ -147,8 +149,9 @@ 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, nested or multiple loops, saved-workflow calls, and mixed control-flow shapes continue to use the legacy-compatibility scheduler until their differential coverage is complete. `Iterate` also records non-empty item streams through the generic effect ledger;+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;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,@@ -188,9 +191,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre- **Ready queues grouped by class** (private projection): `_ready_queues: dict[class_name, deque[str]]` and`_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 token- checks control generic branch readiness. Supported static flat `For` graphs use the generic adapter for readiness and- continuation projection; empty/input-driven, nested/multiple-loop, mixed, and saved-workflow graphs retain the legacy- scheduler. Optional+ checks 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,+ 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.@@ -255,8 +258,8 @@ 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 nested, multiple, or mixed loop shapes remain-compatibility-owned.+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.`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@@ -308,9 +311,10 @@ compatibility loader. `For` start payloads must match the prepared index, collecseam: the generic adapter calls the graph-state generic continuation boundary,which creates the next prepared iteration, aggregates outputs, and finalizes thesupported flat loop. The compatibility bridge remains for empty/input-driven,-nested, multiple-loop, mixed-loop, and legacy-snapshot execution; those paths+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 uses the generic adapter. For+fresh static flat `For`/`ForReturn` shape and the narrow canonical two-level+nested-`For` 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,@@ -325,7 +329,8 @@ 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, and the supported static flat `For`/`ForReturn` shape.+mixed/nested `If` graph, the supported static flat `For`/`ForReturn` shape, and+the narrow canonical nested-`For` shape.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,@@ -336,7 +341,7 @@ compatibility skip propagation must not leave stale downstream indegrees. Bothscheduler adapters expose the same skip transition; the legacy path releasesdownstream indegrees without trying to hydrate inputs from the skipped node. Itdoes not claim durable persistence of the generic scheduler's private claim set,-nor does it claim ownership migration for empty/input-driven, nested, multiple,+nor does it claim ownership migration for empty/input-driven, deeper/multiple,mixed, or workflow-call loop shapes. Real queue/processorcoverage in `tests/app/services/session_processor/test_if_processor_sqlite.py`also exercises true and false `If` selection, cancellation before and afterdiff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 768135f620..e82707b43e 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -2401,6 +2401,8 @@ class _GenericGraphSchedulerAdapter:for dependency in dependencies:if dependency not in self._scheduler.plan.nodes:self.register_node(dependency)+ if exec_node_id in self._state.executed:+ self._scheduler.executed.add(exec_node_id)self._scheduler.add_node(self._scheduler.plan.add_node(exec_node_id,@@ -2547,6 +2549,7 @@ class _GenericGraphSchedulerAdapter:self._state._tx_set_mapping(self._state.indegree, dependent, self._scheduler.indegree[dependent])for ready_node_id in newly_ready:self._project_ready_node(ready_node_id)+ _ExecutionScheduler._try_materialize_deferred_nested_for_body(self, exec_node_id)if finalized_for_exec_node_id is None:return []finalized_for_node = self._state.execution_graph.get_node(finalized_for_exec_node_id)@@ -4972,6 +4975,36 @@ class GraphExecutionState(BaseModel):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 len(for_nodes) == 2 and len(return_nodes) == 2:+ source_graph = self._get_source_graph_flat()+ outer_for = next(+ (+ node+ for node in for_nodes+ if (nested_body := self.graph._get_supported_for_nested_for_body(node.id, source_graph)) is not None+ and len(nested_body.inner_for_ids) == 1+ and not nested_body.continuation_nodes+ ),+ None,+ )+ if (+ outer_for is None+ or self.graph._get_input_edges(outer_for.id, COLLECTION_FIELD)+ or not outer_for.collection+ ):+ return False+ nested_body = self.graph._get_supported_for_nested_for_body(outer_for.id, source_graph)+ assert nested_body is not None+ inner_for = self.graph.get_node(nested_body.inner_for_ids[0])+ if not isinstance(inner_for, ForInvocation):+ return False+ inner_collection_edges = self.graph._get_input_edges(inner_for.id, COLLECTION_FIELD)+ if len(inner_collection_edges) != 1 or (+ inner_collection_edges[0].source.node_id != outer_for.id+ or inner_collection_edges[0].source.field != ITEM_FIELD+ ):+ return False+ return Trueif len(for_nodes) != 1 or len(return_nodes) != 1:return Falseif self.graph._get_input_edges(for_nodes[0].id, COLLECTION_FIELD) or not for_nodes[0].collection:diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 7b858bfb64..4fc57b0afe 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -29,7 +29,7 @@ from invokeai.app.services.shared.graph import (_IfActivationCompiler,)from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context-from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocation+from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocation, create_loop_linkageFIXTURE_PATH = Path(__file__).parents[3] / "fixtures" / "execution_engine" / "static_dag_v1.json"@@ -176,6 +176,33 @@ def _flat_for_graph(return 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="inner_for"))+ graph.add_node(AnyTypeTestInvocation(id="inner_body"))+ graph.add_node(ForReturnInvocation(id="inner_return"))+ 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", "inner_for", "collection")+ connect("inner_for", "item", "inner_body", "value")+ connect("inner_body", "value", "inner_return", "output")+ connect("inner_for", "output_collection", "outer_return", "output")+ connect("outer_for", "output_collection", "after", "value")+ graph.add_edge(create_loop_linkage("outer_for", "outer_return"))+ graph.add_edge(create_loop_linkage("inner_for", "inner_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})))@@ -917,6 +944,119 @@ def test_flat_for_generic_path_does_not_use_compatibility_continuation_bridge(assert _final_for_output(state).output_collection == [11, 12]+def test_nested_for_generic_and_compatibility_paths_have_matching_completion() -> None:+ def run(force_compatibility: bool) -> tuple[list[str], GraphExecutionState]:+ state = GraphExecutionState(graph=_nested_for_graph())+ if force_compatibility:+ state._execution_scheduler = _ExecutionScheduler(state)+ return _run(state)++ compatibility_trace, compatibility_state = run(force_compatibility=True)+ generic_trace, generic_state = run(force_compatibility=False)++ 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)+ 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"]]+ compatibility_after_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in compatibility_state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ assert compatibility_state.results[compatibility_after_exec_id].value == [["a", "b"], ["c"]]+++def test_nested_for_generic_and_compatibility_paths_handle_empty_inner_collection() -> None:+ def run(force_compatibility: bool) -> tuple[list[str], GraphExecutionState]:+ state = GraphExecutionState(graph=_nested_for_graph(outer_collection=[[], ["c"]]))+ if force_compatibility:+ state._execution_scheduler = _ExecutionScheduler(state)+ return _run(state)++ compatibility_trace, compatibility_state = run(force_compatibility=True)+ generic_trace, generic_state = run(force_compatibility=False)++ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ # Empty inner iterations use different synthetic execution-node projections, but must preserve trace and outputs.+ 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 == [[], ["c"]]+ compatibility_after_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in compatibility_state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ assert compatibility_state.results[compatibility_after_exec_id].value == [[], ["c"]]+++def test_nested_for_generic_path_rehydrates_after_inner_completion() -> None:+ expected_state = GraphExecutionState(graph=_nested_for_graph())+ expected_state._execution_scheduler = _ExecutionScheduler(expected_state)+ expected_trace, expected_state = _run(expected_state)+ assert expected_trace == [+ "outer_for",+ "inner_for",+ "inner_body",+ "inner_return",+ "inner_for",+ "inner_body",+ "inner_return",+ "outer_return",+ "outer_for",+ "inner_for",+ "inner_body",+ "inner_return",+ "outer_return",+ "after",+ ]++ state = GraphExecutionState(graph=_nested_for_graph())+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ partial_trace, partial_state = _run(state, stop_after=4)+ assert partial_trace == ["outer_for", "inner_for", "inner_body", "inner_return"]++ restored = load_execution_state(dump_execution_state(partial_state))+ restored._execution_scheduler = _GenericGraphSchedulerAdapter(restored)+ resumed_trace, resumed_state = _run(restored)++ assert resumed_trace == [+ "inner_for",+ "inner_body",+ "inner_return",+ "outer_return",+ "outer_for",+ "inner_for",+ "inner_body",+ "inner_return",+ "outer_return",+ "after",+ ]+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)++ compatibility_partial = GraphExecutionState(graph=_nested_for_graph())+ compatibility_partial._execution_scheduler = _ExecutionScheduler(compatibility_partial)+ _, compatibility_partial = _run(compatibility_partial, stop_after=4)+ compatibility_restored = load_execution_state(dump_execution_state(compatibility_partial))+ compatibility_restored._execution_scheduler = _ExecutionScheduler(compatibility_restored)+ compatibility_resumed_trace, compatibility_resumed = _run(compatibility_restored)+ assert compatibility_resumed_trace == resumed_trace+ assert _state_projection(compatibility_resumed) == _state_projection(expected_state)++def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None:trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))