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): route flat For through generic adapter

JPPhoto59def8fecf44
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 088938ec1e..f021048fdf 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -84,15 +84,18 @@ collections or state.
The execution-engine seam is additive to this loop contract. The session runner applies each result through
`GraphExecutionState.apply()` using a stable execution reference and records frame-aware output tokens and accepted
-effects. Legacy `For`/`ForReturn` continuation scheduling is mirrored by a typed, frame-scoped
+`For`/`ForReturn` continuation state is mirrored by a typed, frame-scoped
`ContinuationRecord`. `ForInvocation` and `ForReturnInvocation` also declare one validated, frame-scoped
`continuation` effect per prepared invocation. The `For` effect starts the `for` continuation with the current
iteration and state; the `ForReturn` effect completes it with output, state, and the continue decision. These effects
are persisted under the invocation reference. Session-built effect references carry graph-state, durable-frame,
iteration-path, and workflow-call-depth identity, and stale or cross-scope effects are rejected before mutation. They
-never encode `loop_linkage` as a data token. The legacy scheduler still
-resolves the linkage, materializes the next iteration, aggregates output, finalizes the loop, and owns empty/nested/
-mixed loop behavior; this additive effect seam does not claim generic `For` scheduling. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty `Iterate` records an
+never encode `loop_linkage` as a data token. A fresh graph with exactly one static, non-empty flat `For`/`ForReturn`
+pair now uses the generic scheduler adapter for readiness and continuation transitions. Graph state owns the
+invocation-specific continuation boundary: it carries returned state, honors `continue_condition`, materializes the
+next body iteration, and finalizes the aggregate. The generic scheduler remains opaque and never receives a literal
+successor node ID. 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
explicit empty close. A direct `Iterate.item` consumer waits for the canonical stream to close, then `Collect` consumes
its ordered values; a missing stream falls back to materialized results for legacy snapshots. The materializer still
owns iterator expansion, iteration paths, collector grouping, collection-input hydration, and empty-source closure.
@@ -116,9 +119,10 @@ ownership seam, not final removal of all legacy topology. Author-time activation
absent, while loop and saved-workflow control flow remain on their 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 `For`,
-nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs, and direct
-`Iterate`/`Collect`-only graphs now use the generic opaque plan/scheduler through a compatibility projection; a fresh
+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,
+direct `Iterate`/`Collect`-only graphs, and supported fresh static flat `For` graphs now use the generic opaque
+plan/scheduler through a compatibility projection; a fresh
generic `If` uses the compiler/adapter seam described above. 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
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 27d982dbc3..748221d92f 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -20,6 +20,12 @@ the generic adapter. Its adapter-level readiness predicate waits for canonical I
completion mirrors each Iterate result into that ledger before releasing `Collect`; materialization still owns copy
expansion, iteration paths, grouping, and explicit empty-stream closure. Mixed control-flow shapes remain on the legacy
compatibility scheduler until their differential gates are complete.
+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
+execution-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.
The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and
authorized child-dependency records are stored in
`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while
@@ -137,9 +143,11 @@ Holds the state for a single run. Keeps the source graph intact and materializes
set of internal helper classes. For ordinary static DAGs and legacy-shaped `If` graphs, readiness and completion are
projected through the generic `ExecutionPlan`/`ExecutionScheduler` adapter. Direct `Iterate`/`Collect` graphs without
other control-flow nodes also use that adapter: its readiness predicate waits for canonical streams to close and its
-completion mirrors Iterate outputs into the stream ledger. `For`, `ForReturn`, saved-workflow calls, and mixed
-control-flow shapes continue to use the legacy compatibility scheduler for materialization and queue lifecycle until
-their differential coverage is complete. `Iterate` also records non-empty item streams through the generic effect ledger;
+completion 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 the
+invocation-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;
the materializer remains authoritative for expansion, iteration paths, collector grouping, and
empty-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,
@@ -180,7 +188,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 generic
scheduler; the `If` adapter stores frame-local activation dependencies whose private gate state plus persisted token
- checks control generic branch readiness. Loop and saved-workflow graphs retain the legacy scheduler. Optional
+ 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
`ready_order: list[str]` prioritizes classes. Queues are rebuilt from persisted execution state when a session is
deserialized.
@@ -234,12 +244,19 @@ materialized-result fallback needed by older snapshots. This is not yet token-au
`Collect` migration: the materializer still owns copy expansion, iteration paths, collector grouping, collection-input
hydration, and empty-source closure; no author-time activation ports or literal successor IDs are introduced.
+For a fresh graph with one static, non-empty flat `For`/`ForReturn` pair, the same adapter now projects ordinary
+readiness and calls the graph-state continuation boundary after each `ForReturn`. That boundary carries returned state,
+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 literal next
+node ID. Empty/input-driven collections and nested, multiple, or mixed loop shapes remain compatibility-owned.
+
`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
kind, and optional sequence. `loop_linkage` remains association metadata and never becomes a data token. This ledger is
currently additive. Ordinary static-DAG and legacy-shaped `If` readiness comes from the generic scheduler through a
-compatibility projection; the activation token is authoritative for generic `If` branch readiness, while materialization
-and type-specific control paths remain authoritative for branch topology, loops, and workflow-call graphs. A future
+compatibility projection; the activation token is authoritative for generic `If` branch readiness. Supported static flat
+`For` readiness and continuation transitions also use the generic adapter, while materialization and type-specific
+control paths remain authoritative for unsupported loop shapes and workflow-call graphs. A future
migration may make token-built topology and the remaining control-flow paths authoritative only after compatibility is proven.
The generic scheduler is an in-memory graph-state component only. It does not
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index e670db930b..df92c704ac 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -1894,130 +1894,8 @@ class _ExecutionScheduler:
):
self._state._mark_source_executed(source_node_id)
- def _get_for_parent(self, exec_node_id: str) -> Optional[str]:
- source_return_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
- iteration_path = self._state._get_iteration_path(exec_node_id)
- source_for_id = self._state._get_for_source_by_return_id().get(source_return_id)
- if source_for_id is not None:
- prepared_for_id = self._state._get_prepared_for_index().get((source_for_id, iteration_path))
- if prepared_for_id is not None:
- return prepared_for_id
-
- # The indexed source/path lookup is the normal path. The ancestor fallback only covers legacy execution
- # graphs whose durable linkage was not materialized; keep it explicit so an unexpected miss is diagnosable.
- execution_graph = self._state._get_execution_graph_flat()
- for ancestor_id in nx.ancestors(execution_graph, exec_node_id):
- source_node = self._state.execution_graph.get_node(ancestor_id)
- if isinstance(source_node, ForInvocation):
- return ancestor_id
-
- # An empty nested Iterate has no item execution node, so its synthetic Collect and ForReturn have no
- # execution-graph edge back to their owning For. The same indexed lookup handles this case when the
- # synthetic node has been assigned its durable parent path.
- if source_for_id is not None:
- for prepared_for_id in self._state._prepared_registry().get_prepared_ids(source_for_id):
- prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)
- if not isinstance(prepared_for_node, ForInvocation) or prepared_for_node.index < 0:
- continue
- if self._state._get_iteration_path(prepared_for_id) == iteration_path:
- return prepared_for_id
- return None
-
- def _get_loop_state_for_next_iteration(
- self, for_exec_node_id: str, return_output: "ForReturnInvocationOutput"
- ) -> "LoopState":
- if return_output.state is not None:
- return return_output.state
-
- for_output = self._state.results.get(for_exec_node_id)
- if isinstance(for_output, ForInvocationOutput):
- return for_output.state
-
- return LoopState()
-
- def _get_ordered_for_return_outputs(
- self, for_exec_node_id: str, source_return_id: str
- ) -> list["ForReturnInvocationOutput"]:
- parent_iteration_path = self._state._get_for_parent_iteration_path(for_exec_node_id)
- prepared_return_ids = self._state._prepared_registry().get_prepared_ids(source_return_id)
- prepared_return_ids = [
- prepared_return_id
- for prepared_return_id in prepared_return_ids
- if self._state._get_iteration_path(prepared_return_id)[:-1] == parent_iteration_path
- ]
- prepared_return_ids = sorted(prepared_return_ids, key=self._state._get_iteration_path)
- return [
- output
- for prepared_return_id in prepared_return_ids
- if isinstance((output := self._state.results.get(prepared_return_id)), ForReturnInvocationOutput)
- ]
-
- def _finalize_for_outputs(
- self,
- for_exec_node_id: str,
- source_for_id: str,
- source_return_id: str,
- return_output: "ForReturnInvocationOutput",
- ) -> None:
- for_output = self._state.results.get(for_exec_node_id)
- if not isinstance(for_output, ForInvocationOutput):
- return
-
- return_outputs = self._get_ordered_for_return_outputs(for_exec_node_id, source_return_id)
- self._state._tx_set_attr(for_output, "output_collection", [output.output for output in return_outputs])
- self._state._tx_set_attr(
- for_output,
- "final_state",
- self._get_loop_state_for_next_iteration(for_exec_node_id, return_output),
- )
- self._state._mark_loop_context_finalized(source_for_id, for_exec_node_id)
-
def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
- if not isinstance(output, ForReturnInvocationOutput):
- return None
- if not isinstance(self._state.execution_graph.get_node(exec_node_id), ForReturnInvocation):
- return None
-
- for_exec_node_id = self._get_for_parent(exec_node_id)
- if for_exec_node_id is None:
- return None
-
- for_node = self._state.execution_graph.get_node(for_exec_node_id)
- if not isinstance(for_node, ForInvocation):
- return None
-
- self._state._complete_for_continuation(for_exec_node_id, output.model_dump(mode="json"))
-
- registry = self._state._prepared_registry()
- source_for_id = registry.get_source_node_id(for_exec_node_id)
- source_return_id = registry.get_source_node_id(exec_node_id)
-
- next_index = for_node.index + 1
- for_return_node = self._state.execution_graph.get_node(exec_node_id)
- assert isinstance(for_return_node, ForReturnInvocation)
- if next_index >= len(for_node.collection) or for_return_node.continue_condition is False:
- self._finalize_for_outputs(for_exec_node_id, source_for_id, source_return_id, output)
- self._state._materializer().create_nested_for_return(
- inner_for_id=source_for_id,
- prepared_inner_for_id=for_exec_node_id,
- )
- self._state._tx_set_attr(for_node, "collection", [])
- return for_exec_node_id
-
- next_state = self._get_loop_state_for_next_iteration(for_exec_node_id, output)
- parent_iteration_path = self._state._get_for_parent_iteration_path(for_exec_node_id)
-
- next_for_id = self._state._materializer().create_for_iteration(
- source_for_id=source_for_id,
- iteration_index=next_index,
- collection=for_node.collection,
- state=next_state,
- iteration_path=(*parent_iteration_path, next_index),
- )
- self._state._discard_source_executed(source_for_id)
- self._state._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
- self._state._tx_set_attr(for_node, "collection", [])
- return None
+ return self._state._try_schedule_next_for_iteration(exec_node_id, output)
def _try_materialize_deferred_nested_for_body(self, exec_node_id: str) -> None:
completed_source_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
@@ -2418,6 +2296,8 @@ class _GenericGraphSchedulerAdapter:
self._state._set_prepared_exec_state(exec_node_id, "executed")
self._state._tx_add_set(self._state.executed, exec_node_id)
self._state._tx_set_mapping(self._state.results, exec_node_id, output)
+ if isinstance(node, ForInvocation) and node.index >= 0:
+ self._state._for_continuation(exec_node_id)
if isinstance(node, IterateInvocation):
self._state._record_iterate_stream(exec_node_id, output)
if isinstance(node, (IterateInvocation, CollectInvocation)):
@@ -2445,12 +2325,17 @@ class _GenericGraphSchedulerAdapter:
self.register_node(exec_node_id)
if exec_node_id not in self._state.indegree:
raise KeyError(f"indegree missing for exec node {exec_node_id}")
+ if exec_node_id in self._scheduler.executed:
+ # Compatibility callers may advance with the invocation result and then replace that result explicitly.
+ self._state._tx_set_mapping(self._state.results, exec_node_id, output)
+ return []
dependents = self._scheduler.plan.dependents(exec_node_id)
for dependent in dependents:
if dependent not in self._state.indegree:
raise KeyError(f"indegree missing for exec node {dependent}")
self._remove_projected(exec_node_id)
self._record_completed_node(exec_node_id, output)
+ finalized_for_exec_node_id = self._state._try_schedule_next_for_iteration(exec_node_id, output)
self._mark_source_node_complete(exec_node_id)
# A condition may become resolvable when this node completes. Resolve it
# while the state has the completed result, before recalculating generic
@@ -2463,7 +2348,15 @@ 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)
- return []
+ if finalized_for_exec_node_id is None:
+ return []
+ finalized_for_node = self._state.execution_graph.get_node(finalized_for_exec_node_id)
+ finalized_for_output = self._state.results.get(finalized_for_exec_node_id)
+ if not isinstance(finalized_for_node, ForInvocation) or not isinstance(
+ finalized_for_output, ForInvocationOutput
+ ):
+ return []
+ return [(finalized_for_node, finalized_for_output)]
def set_ready_order(self, ready_order: Iterable[str]) -> None:
self._scheduler.set_ready_order(ready_order)
@@ -4704,18 +4597,169 @@ class GraphExecutionState(BaseModel):
self._execution_materializer = _ExecutionMaterializer(self)
return self._execution_materializer
+ def _get_for_parent(self, exec_node_id: str) -> Optional[str]:
+ source_return_id = self._prepared_registry().get_source_node_id(exec_node_id)
+ iteration_path = self._get_iteration_path(exec_node_id)
+ source_for_id = self._get_for_source_by_return_id().get(source_return_id)
+ if source_for_id is not None:
+ prepared_for_id = self._get_prepared_for_index().get((source_for_id, iteration_path))
+ if prepared_for_id is not None:
+ return prepared_for_id
+
+ # The indexed source/path lookup is the normal path. The ancestor fallback only covers legacy execution
+ # graphs whose durable linkage was not materialized; keep it explicit so an unexpected miss is diagnosable.
+ execution_graph = self._get_execution_graph_flat()
+ for ancestor_id in nx.ancestors(execution_graph, exec_node_id):
+ source_node = self.execution_graph.get_node(ancestor_id)
+ if isinstance(source_node, ForInvocation):
+ return ancestor_id
+
+ # An empty nested Iterate has no item execution node, so its synthetic Collect and ForReturn have no
+ # execution-graph edge back to their owning For. The same indexed lookup handles this case when the
+ # synthetic node has been assigned its durable parent path.
+ if source_for_id is not None:
+ for prepared_for_id in self._prepared_registry().get_prepared_ids(source_for_id):
+ prepared_for_node = self.execution_graph.get_node(prepared_for_id)
+ if not isinstance(prepared_for_node, ForInvocation) or prepared_for_node.index < 0:
+ continue
+ if self._get_iteration_path(prepared_for_id) == iteration_path:
+ return prepared_for_id
+ return None
+
+ def _get_loop_state_for_next_iteration(
+ self, for_exec_node_id: str, return_output: ForReturnInvocationOutput
+ ) -> LoopState:
+ if return_output.state is not None:
+ return return_output.state
+
+ for_output = self.results.get(for_exec_node_id)
+ if isinstance(for_output, ForInvocationOutput):
+ return for_output.state
+
+ return LoopState()
+
+ def _get_ordered_for_return_outputs(
+ self, for_exec_node_id: str, source_return_id: str
+ ) -> list[ForReturnInvocationOutput]:
+ parent_iteration_path = self._get_for_parent_iteration_path(for_exec_node_id)
+ prepared_return_ids = self._prepared_registry().get_prepared_ids(source_return_id)
+ prepared_return_ids = [
+ prepared_return_id
+ for prepared_return_id in prepared_return_ids
+ if self._get_iteration_path(prepared_return_id)[:-1] == parent_iteration_path
+ ]
+ prepared_return_ids = sorted(prepared_return_ids, key=self._get_iteration_path)
+ return [
+ output
+ for prepared_return_id in prepared_return_ids
+ if isinstance((output := self.results.get(prepared_return_id)), ForReturnInvocationOutput)
+ ]
+
+ def _finalize_for_outputs(
+ self,
+ for_exec_node_id: str,
+ source_for_id: str,
+ source_return_id: str,
+ return_output: ForReturnInvocationOutput,
+ ) -> None:
+ for_output = self.results.get(for_exec_node_id)
+ if not isinstance(for_output, ForInvocationOutput):
+ return
+
+ return_outputs = self._get_ordered_for_return_outputs(for_exec_node_id, source_return_id)
+ self._tx_set_attr(for_output, "output_collection", [output.output for output in return_outputs])
+ self._tx_set_attr(
+ for_output,
+ "final_state",
+ self._get_loop_state_for_next_iteration(for_exec_node_id, return_output),
+ )
+ self._mark_loop_context_finalized(source_for_id, for_exec_node_id)
+
+ def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
+ """Advance one For continuation without making the generic scheduler know loop semantics."""
+
+ if not isinstance(output, ForReturnInvocationOutput):
+ return None
+ if not isinstance(self.execution_graph.get_node(exec_node_id), ForReturnInvocation):
+ return None
+
+ for_exec_node_id = self._get_for_parent(exec_node_id)
+ if for_exec_node_id is None:
+ return None
+
+ for_node = self.execution_graph.get_node(for_exec_node_id)
+ if not isinstance(for_node, ForInvocation):
+ return None
+
+ self._complete_for_continuation(for_exec_node_id, output.model_dump(mode="json"))
+
+ registry = self._prepared_registry()
+ source_for_id = registry.get_source_node_id(for_exec_node_id)
+ source_return_id = registry.get_source_node_id(exec_node_id)
+
+ next_index = for_node.index + 1
+ for_return_node = self.execution_graph.get_node(exec_node_id)
+ assert isinstance(for_return_node, ForReturnInvocation)
+ if next_index >= len(for_node.collection) or for_return_node.continue_condition is False:
+ self._finalize_for_outputs(for_exec_node_id, source_for_id, source_return_id, output)
+ self._materializer().create_nested_for_return(
+ inner_for_id=source_for_id,
+ prepared_inner_for_id=for_exec_node_id,
+ )
+ self._tx_set_attr(for_node, "collection", [])
+ return for_exec_node_id
+
+ next_state = self._get_loop_state_for_next_iteration(for_exec_node_id, output)
+ parent_iteration_path = self._get_for_parent_iteration_path(for_exec_node_id)
+
+ next_for_id = self._materializer().create_for_iteration(
+ source_for_id=source_for_id,
+ iteration_index=next_index,
+ collection=for_node.collection,
+ state=next_state,
+ iteration_path=(*parent_iteration_path, next_index),
+ )
+ self._discard_source_executed(source_for_id)
+ self._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
+ self._tx_set_attr(for_node, "collection", [])
+ return None
+
+ def _can_use_generic_for_scheduler(self) -> bool:
+ """Allow generic routing only for one flat For body with no other control-flow node."""
+
+ if any(
+ isinstance(node, (IterateInvocation, CollectInvocation, IfInvocation, CallSavedWorkflowInvocation))
+ for node in self.graph.nodes.values()
+ ):
+ return False
+ for_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) != 1 or len(return_nodes) != 1:
+ return False
+ if self.graph._get_input_edges(for_nodes[0].id, COLLECTION_FIELD) or not for_nodes[0].collection:
+ return False
+ body_path = self.graph._get_for_body_path_to_return(for_nodes[0].id, self._get_source_graph_flat())
+ if body_path is None:
+ return False
+ body_node_ids, return_node_id = body_path
+ return return_node_id == return_nodes[0].id and not any(
+ isinstance(self.graph.get_node(node_id), (ForInvocation, ForReturnInvocation))
+ for node_id in body_node_ids
+ if node_id != return_node_id
+ )
+
def _can_use_generic_scheduler(self) -> bool:
- """Use generic readiness for static graphs and direct Iterate/Collect control flow."""
+ """Use generic readiness for static graphs and supported direct control flow."""
control_nodes = (ForInvocation, ForReturnInvocation)
+ if any(isinstance(node, control_nodes) for node in self.graph.nodes.values()):
+ return self._can_use_generic_for_scheduler()
if any(isinstance(node, (IterateInvocation, CollectInvocation)) for node in self.graph.nodes.values()):
return not any(
isinstance(node, (*control_nodes, IfInvocation, CallSavedWorkflowInvocation))
for node in self.graph.nodes.values()
)
- return not any(isinstance(node, control_nodes) for node in self.graph.nodes.values()) and not any(
- isinstance(node, CallSavedWorkflowInvocation) for node in self.graph.nodes.values()
- )
+ return not any(isinstance(node, CallSavedWorkflowInvocation) for node in self.graph.nodes.values())
def _scheduler(self) -> _ExecutionScheduler | _GenericGraphSchedulerAdapter:
if self._execution_scheduler 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 5bf3e6624e..a585ff793a 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -9,6 +9,7 @@ import pytest
from pydantic import ValidationError
from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation, LoopState, StateSetInvocation
from invokeai.app.invocations.math import AddInvocation
from invokeai.app.invocations.primitives import BooleanInvocation
from invokeai.app.services.shared import graph as graph_module
@@ -27,6 +28,7 @@ from invokeai.app.services.shared.graph import (
_GenericGraphSchedulerAdapter,
_IfBranchScheduler,
)
+from tests.test_nodes import AnyTypeTestInvocation
FIXTURE_PATH = Path(__file__).parents[3] / "fixtures" / "execution_engine" / "static_dag_v1.json"
@@ -98,6 +100,81 @@ def _nested_if_graph() -> Graph:
return graph
+def _flat_for_graph(*, with_after: bool = False) -> Graph:
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=[1, 2]))
+ graph.add_node(AddInvocation(id="body", b=10))
+ graph.add_node(ForReturnInvocation(id="return"))
+ if with_after:
+ graph.add_node(AnyTypeTestInvocation(id="after"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="item"),
+ destination=EdgeConnection(node_id="body", field="a"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="body", field="value"),
+ destination=EdgeConnection(node_id="return", field="output"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ type="loop_linkage",
+ source=EdgeConnection(node_id="for", field="loop_linkage"),
+ destination=EdgeConnection(node_id="return", field="loop_linkage"),
+ )
+ )
+ if with_after:
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="output_collection"),
+ destination=EdgeConnection(node_id="after", field="value"),
+ )
+ )
+ 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})))
+ graph.add_node(StateSetInvocation(id="body", key="count"))
+ graph.add_node(ForReturnInvocation(id="return", continue_condition=continue_condition))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="state"),
+ destination=EdgeConnection(node_id="body", field="state"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="item"),
+ destination=EdgeConnection(node_id="body", field="value"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="item"),
+ destination=EdgeConnection(node_id="return", field="output"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="body", field="state"),
+ destination=EdgeConnection(node_id="return", field="state"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ type="loop_linkage",
+ source=EdgeConnection(node_id="for", field="loop_linkage"),
+ destination=EdgeConnection(node_id="return", field="loop_linkage"),
+ )
+ )
+ return graph
+
+
def _run_graph(
state: GraphExecutionState,
*,
@@ -519,6 +596,102 @@ def test_nested_if_fresh_execution_matches_compatibility_scheduler(
assert compatibility_state.is_complete()
+def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:
+ generic_trace, generic_state = _run_graph(GraphExecutionState(graph=_flat_for_graph()))
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_flat_for_graph()),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return"]
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)
+ final_for_id = max(
+ (
+ exec_node_id
+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()
+ if source_node_id == "for"
+ ),
+ key=lambda exec_node_id: generic_state.execution_graph.get_node(exec_node_id).index,
+ )
+ assert generic_state.results[final_for_id].output_collection == [11, 12]
+ assert generic_state._generic_runtime().continuations
+ assert all(
+ continuation.status == "completed" for continuation in generic_state._generic_runtime().continuations.values()
+ )
+ assert len(generic_state._generic_runtime().continuations) == 2
+ assert {continuation.owner_id for continuation in generic_state._generic_runtime().continuations.values()} == {
+ exec_node_id
+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()
+ if source_node_id == "for"
+ }
+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)
+
+
+def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),
+ )
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]
+ after_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_id].value == [11, 12]
+ assert compatibility_state.results[
+ next(
+ exec_node_id
+ for exec_node_id, source_node_id in compatibility_state.prepared_source_mapping.items()
+ if source_node_id == "after"
+ )
+ ].value == [11, 12]
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+
+
+ ("continue_condition", "expected_trace", "expected_collection", "expected_state"),
+ [
+ (True, ["for", "body", "return"] * 3, [1, 2, 3], {"count": 3}),
+ (False, ["for", "body", "return"], [1], {"count": 1}),
+ ],
+)
+def test_flat_for_fresh_execution_matches_state_and_break_semantics(
+ continue_condition: bool,
+ expected_trace: list[str],
+ expected_collection: list[int],
+ expected_state: dict[str, int],
+) -> None:
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),
+ )
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace == expected_trace
+ final_for_id = max(
+ (
+ exec_node_id
+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()
+ if source_node_id == "for"
+ ),
+ key=lambda exec_node_id: generic_state.execution_graph.get_node(exec_node_id).index,
+ )
+ final_for_output = generic_state.results[final_for_id]
+ assert final_for_output.output_collection == expected_collection
+ assert final_for_output.final_state == LoopState(values=expected_state)
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+
+
def test_nested_if_checkpoint_restore_matches_compatibility_scheduler() -> None:
graph = _nested_if_graph()
expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))