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 direct Iterate Collect graphs generically

JPPhotoa1e94b949c91
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 7d4faf4edf..747b9b8235 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -91,7 +91,10 @@ its ordered values; a missing stream falls back to materialized results for lega
owns 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 retried
Iterate/Collect sessions. This is evidence for the current adapters; it does not remove materialization or queue
-ownership. `loop_linkage` remains association metadata and never becomes a data token.
+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.
+Materialization still owns copy expansion, iteration paths, grouping, and explicit empty closure; mixed control-flow and
+queue lifecycle remain compatibility-owned. `loop_linkage` remains association metadata and never becomes a data token.
`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the
selected branch, and the graph state validates and persists it after invocation. For a fresh generic `If`, the dedicated
@@ -106,9 +109,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 and existing snapshots.
-Ordinary static DAGs and legacy-shaped `If` 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 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
+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
graph JSON.
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 4005778de2..672b332d42 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -15,6 +15,11 @@ discard. It does not consult `_IfBranchScheduler` topology or call its prune/ski
execution edges. The forced compatibility `_ExecutionScheduler` path retains legacy `If` topology lowering, input-edge
pruning, and skip behavior for compatibility snapshots. This is an ownership seam, not final removal of all legacy
topology.
+Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow also use
+the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and generic
+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.
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
@@ -130,10 +135,12 @@ Checks a single prospective edge before insertion:
Holds the state for a single run. Keeps the source graph intact and materializes a separate execution graph.
`GraphExecutionState` is still the public runtime entry point, but most execution behavior is now delegated to a small
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. `Iterate`, `Collect`, `For`, `ForReturn`,
-and saved-workflow call lowering 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; the materializer remains authoritative for expansion, iteration paths, collector grouping, and
+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;
+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,
and retry behavior. This evidence does not remove the materializer or queue adapters.
@@ -217,8 +224,9 @@ ownership seam, not final removal of all legacy topology. `apply()`
validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.
Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing
control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration
-index, and the final copy emits one `close_stream` effect. Graph state maps these effects to the existing
-frame-scoped iteration-stream identity, so legacy output mirroring is idempotent. The materializer still creates
+index, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-only graphs now run through the
+generic scheduler adapter; its completion maps these results/effects to the existing frame-scoped iteration-stream
+identity, so legacy output mirroring is idempotent. The materializer still creates
prepared copies, derives iteration paths, groups collector inputs, and records the explicit close for an empty source.
For a direct `Iterate.item` edge, the scheduler defers `CollectInvocation` while its canonical stream is open, and
runtime hydration consumes the closed stream in sequence order. If no stream exists, hydration retains the legacy
@@ -245,9 +253,11 @@ subclasses that declare frame-scoped data, activation, stream-closure, child,
and terminal effects. The generic scheduler selects nodes from required
effects for the current frame; it never receives a literal successor-node ID.
Current implementation is narrower: `IfInvocation` and non-empty
-`IterateInvocation` use the effect recorder for activation and stream effects,
-while `Collect`, `For`, `ForReturn`, and workflow-call invocations remain on
-compatibility paths. For
+`IterateInvocation` use the effect recorder for activation and stream effects.
+Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for
+readiness and completion, while the materializer still expands copies and
+groups paths. `For`, `ForReturn`, workflow-call invocations, and mixed
+control-flow graphs remain on compatibility paths. For
`If`, generic readiness consumes opaque frame-local plan dependencies and requires
both matching private `ActivationGate` runtime state and a persisted activation token;
generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility
@@ -382,7 +392,8 @@ legacy unmarked snapshots are treated as version 0, while unreadable snapshots a
- Cache the preserved iteration path when the materializer has one, such as for grouped collectors.
- Wire edges from chosen prepared parents.
- Set `indegree = number of unmet inputs` (i.e., parents not yet executed). The generic scheduler mirrors this into
- its opaque plan for ordinary static DAGs and legacy-shaped `If` graphs.
+ its opaque plan for ordinary static DAGs, legacy-shaped `If` graphs, and
+ direct `Iterate`/`Collect`-only graphs.
- Try to resolve any `If`-specific scheduling state.
- If the node is ready and not deferred by an unresolved `If`, enqueue it into its class queue.
@@ -391,7 +402,8 @@ legacy unmarked snapshots are treated as version 0, while unreadable snapshots a
- `_enqueue_if_ready(nid)` applies generic readiness: `indegree == 0`, not executed or claimed, and, for an `If`
branch-local node, both matching private `ActivationGate` runtime state and a persisted activation token are present
for its frame. The generic adapter derives opaque dependencies and retires rejected nodes through generic scheduler
- discard. Forced compatibility uses `_IfBranchScheduler` topology and skip handling.
+ discard. For direct `Collect` nodes, the adapter also requires available Iterate streams to be closed. Forced
+ compatibility uses `_IfBranchScheduler` topology and skip handling.
- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and legacy-shaped `If` graphs, projecting its
deterministic class/frame order into the compatibility queues. Forced compatibility `If` topology remains responsible
for branch-local lowering, input-edge pruning, and skips. Loop and saved-workflow control-flow graphs use `_active_class`
diff --git a/invokeai/app/services/shared/execution_engine/scheduler.py b/invokeai/app/services/shared/execution_engine/scheduler.py
index b708232c29..0849340e9c 100644
--- a/invokeai/app/services/shared/execution_engine/scheduler.py
+++ b/invokeai/app/services/shared/execution_engine/scheduler.py
@@ -14,10 +14,17 @@ Frame = tuple[object, ...]
ReadyPredicate = Callable[[NodeId], bool]
-def _frame_key(frame: Frame) -> tuple[tuple[str, str], ...]:
- """Return a stable ordering key for mixed integer/string frame parts."""
-
- return tuple((type(part).__name__, repr(part)) for part in frame)
+def _frame_key(frame: Frame) -> tuple[tuple[int, int | str], ...]:
+ """Return a stable ordering key that preserves numeric iteration order."""
+
+ return tuple(
+ (0, part)
+ if isinstance(part, int) and not isinstance(part, bool)
+ else (1, part)
+ if isinstance(part, str)
+ else (2, f"{type(part).__name__}:{part!r}")
+ for part in frame
+ )
@dataclass(frozen=True, slots=True)
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index bcdfb1f3f1..6ff37b246f 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -2239,10 +2239,13 @@ class _GenericGraphSchedulerAdapter:
def _is_node_activation_ready(self, exec_node_id: str) -> bool:
"""Require every frame-local activation dependency to be satisfied."""
- return all(
+ if not all(
self._state._is_activation_dependency_satisfied(dependency)
for dependency in self._scheduler.plan.nodes[exec_node_id].activation_dependencies
- )
+ ):
+ return False
+ node = self._state.execution_graph.nodes[exec_node_id]
+ return not isinstance(node, CollectInvocation) or self._state._collect_streams_ready(exec_node_id)
def _retire_unselected_node(self, exec_node_id: str) -> None:
"""Retire one unselected prepared node through generic scheduler state."""
@@ -2411,9 +2414,14 @@ class _GenericGraphSchedulerAdapter:
return self._state.execution_graph.nodes[exec_node_id]
def _record_completed_node(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
+ node = self._state.execution_graph.nodes.get(exec_node_id)
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, IterateInvocation):
+ self._state._record_iterate_stream(exec_node_id, output)
+ if isinstance(node, (IterateInvocation, CollectInvocation)):
+ self._state._tx_set_attr(node, "collection", [])
def _mark_source_node_complete(self, exec_node_id: str) -> None:
registry = self._state._prepared_registry()
@@ -4697,9 +4705,14 @@ class GraphExecutionState(BaseModel):
return self._execution_materializer
def _can_use_generic_scheduler(self) -> bool:
- """Use generic readiness only for graphs without control-flow lowering."""
+ """Use generic readiness for static graphs and direct Iterate/Collect control flow."""
- control_nodes = (IterateInvocation, CollectInvocation, ForInvocation, ForReturnInvocation)
+ control_nodes = (ForInvocation, ForReturnInvocation)
+ 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()
)
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
index a7a1ba1d47..f24f4c6ab2 100644
--- a/tests/app/services/shared/test_execution_engine_scheduler.py
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -4,6 +4,7 @@ from unittest.mock import Mock
import pytest
+from invokeai.app.invocations.collections import CollectionConcatInvocation
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.math import AddInvocation, MultiplyInvocation
from invokeai.app.invocations.primitives import BooleanInvocation
@@ -12,7 +13,16 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionPlan,
ExecutionScheduler,
)
-from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState, _ExecutionScheduler
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ Edge,
+ EdgeConnection,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+ _ExecutionScheduler,
+ _GenericGraphSchedulerAdapter,
+)
def _plan() -> ExecutionPlan:
@@ -498,6 +508,73 @@ def test_graph_state_static_dag_delegates_readiness_to_generic_scheduler() -> No
assert state.is_complete()
+ ("source_collection", "expected_collection"),
+ [([], []), ([0, 1, 2, 3], [0, 1, 2, 3]), (list(range(11)), list(range(11)))],
+)
+def test_graph_state_iterate_collect_uses_generic_scheduler_and_closed_stream(
+ source_collection: list[int], expected_collection: list[int]
+) -> None:
+ graph = Graph()
+ graph.add_node(CollectionConcatInvocation(id="source", first=source_collection))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="source", field="collection"),
+ destination=EdgeConnection(node_id="iterate", field="collection"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="iterate", field="item"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ trace: list[str] = []
+ while (node := state.next()) is not None:
+ trace.append(state.prepared_source_mapping[node.id])
+ state.complete(node.id, node.invoke(Mock()))
+
+ assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)
+ assert trace[0] == "source"
+ assert trace[-1] == "collect"
+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[collect_exec_id].collection == expected_collection
+ streams = [stream for stream in state._generic_runtime().streams.values() if stream.owner_id == "iterate"]
+ assert len(streams) == 1
+ assert streams[0].closed
+ assert streams[0].values == tuple(expected_collection)
+ assert state.is_complete()
+
+
+def test_graph_state_mixed_if_iterate_collect_keeps_compatibility_scheduler() -> None:
+ graph = Graph()
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(CollectionConcatInvocation(id="source", first=[1]))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="source", field="collection"),
+ destination=EdgeConnection(node_id="iterate", field="collection"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="iterate", field="item"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+
+ assert not state._can_use_generic_scheduler()
+ assert isinstance(state._scheduler(), _ExecutionScheduler)
+
+
def test_graph_state_if_uses_generic_activation_routing() -> None:
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=True))