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 empty input-driven For generically

JPPhotoa4549772a1d6
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 4b88bcf705..8b374db00e 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -98,14 +98,15 @@ iteration and state; the `ForReturn` effect completes it with output, state, and
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. A fresh graph with exactly one static flat `For`/`ForReturn` pair,
-including an empty literal collection or a supported non-empty input-driven collection producer, now uses the generic
-scheduler adapter for readiness and continuation transitions.
+including an empty literal collection, a supported non-empty input-driven collection producer, or the exact bounded
+empty input-driven producer shape, now uses the generic scheduler adapter for readiness and continuation transitions.
Graph state owns the generic continuation boundary: it carries returned state, honors `continue_condition`, materializes the next body
iteration, and finalizes the aggregate. An empty literal collection completes through the existing synthetic terminal
`For` result without running the body or `ForReturn`. The generic scheduler remains opaque and never receives a literal
successor node ID. The compatibility continuation bridge is retained only for unsupported loop shapes and explicitly
-legacy-loaded snapshots. Empty input-driven collections, unsupported input-driven outer collections, deeper or multiple
-nested loops, and unsupported mixed control flow remain on the compatibility scheduler; the narrow canonical two-level
+legacy-loaded snapshots. Empty input-driven shapes outside the exact four-node/four-edge bounded topology, unsupported
+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 in
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 37d5fc15e0..86bdfc9de2 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -143,12 +143,13 @@ eight `Iterate` nodes and eight-component frame paths, with the same
empty-stream, checkpoint, source-completion, and failure-parity guarantees.
Nine-level or deeper chains and all other expanded, fan-in, sibling, mixed,
`For`, `Collect`, and legacy shapes remain compatibility-owned.
-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,
-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
+A fresh graph with exactly one flat `For`/`ForReturn` pair and ordinary body nodes also uses the generic adapter for a
+literal collection, a supported non-empty input-driven collection, or the exact four-node/four-edge empty input-driven
+shape with one inputless producer and no downstream node. 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. Other empty/input-driven shapes, 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, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.
The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and
@@ -269,10 +270,11 @@ set of internal helper classes. For ordinary static DAGs and legacy-shaped `If`
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. A fresh graph with one static flat `For`/`ForReturn` pair,
-including a supported non-empty input-driven collection producer, also uses the adapter for readiness and continuation
-transitions; graph state owns the invocation-specific continuation boundary while the generic scheduler remains opaque.
-Empty input-driven collections, unsupported input-driven shapes, deeper or multiple loops, saved-workflow calls, and unsupported mixed control-flow shapes outside the
-bounded per-item topology continue to use
+including a supported non-empty input-driven collection producer or the exact bounded empty input-driven producer
+shape, also uses the adapter for readiness and continuation transitions; graph state owns the invocation-specific
+continuation boundary while the generic scheduler remains opaque. Other empty or unsupported input-driven shapes,
+deeper or multiple loops, saved-workflow calls, and unsupported mixed control-flow shapes outside the bounded per-item
+topology continue to use
the legacy compatibility scheduler until their differential coverage is complete. The narrow canonical two-level
nested-`For` shape, the canonical outer-`For`/bounded-`Iterate`/`Collect` shape,
the exact five-node nested-`Iterate` chain, and the bounded three-, four-, five-,
@@ -338,10 +340,10 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the generic
scheduler; 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 and the narrow canonical two-level nested
- `For` shape, the exact producer-driven nested extension, and the bounded two- through eight-level serial nested-
- `Iterate` chains and the bounded per-item `Iterate`/`If`/`Collect` topology use the generic adapter for readiness and
- continuation projection; empty input-driven, unsupported input-driven, nine-level or deeper, mixed graphs outside that topology, and saved-workflow
- graphs retain the legacy scheduler. Optional
+ `For` shape, the exact producer-driven nested extension, the exact bounded empty input-driven flat `For`, the bounded
+ two- through eight-level serial nested-`Iterate` chains, and the bounded per-item `Iterate`/`If`/`Collect` topology use
+ the generic adapter for readiness and continuation projection; other unsupported input-driven, nine-level or deeper,
+ mixed graphs outside that topology, 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.
@@ -488,11 +490,11 @@ after finalization, their authoritative returned collection and final state. Unv
compatibility loader. `For` start payloads must match the prepared index, collection total, and state before mutation. This is the invocation/effect ownership
seam: the generic adapter calls the graph-state generic continuation boundary,
which creates the next prepared iteration, aggregates outputs, and finalizes the
-supported flat loop. The compatibility bridge remains for empty input-driven,
-unsupported input-driven,
+supported flat loop. The compatibility bridge remains for other unsupported input-driven,
deeper/multiple nested, mixed-loop, and legacy-snapshot execution; those paths
retain their existing materialization and linkage ownership. The supported
-fresh static flat `For`/`ForReturn` shape, the narrow canonical two-level
+fresh static flat `For`/`ForReturn` shape, the exact bounded empty input-driven
+flat 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 requires
@@ -523,7 +525,7 @@ compatibility skip propagation must not leave stale downstream indegrees. Both
scheduler adapters expose the same skip transition; the legacy path releases
downstream indegrees without trying to hydrate inputs from the skipped node. It
does not claim durable persistence of the generic scheduler's private claim set,
-nor does it claim ownership migration for empty input-driven, unsupported input-driven, deeper/multiple,
+nor does it claim ownership migration for other unsupported input-driven, deeper/multiple,
mixed, or workflow-call loop shapes. Real queue/processor
coverage in `tests/app/services/session_processor/test_if_processor_sqlite.py`
also exercises true and false `If` selection, cancellation before and after
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index f1871009f1..0ca39ea60c 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -807,6 +807,7 @@ class GraphExecutionState(BaseModel):
if len(for_nodes) != 1 or len(return_nodes) != 1:
return False
collection_edges = self.graph._get_input_edges(for_nodes[0].id, COLLECTION_FIELD)
+ empty_collection_source: BaseInvocation | None = None
if collection_edges:
collection_source = self.graph.get_node(collection_edges[0].source.node_id)
collection_value = getattr(collection_source, "value", None)
@@ -815,11 +816,58 @@ class GraphExecutionState(BaseModel):
and isinstance(collection_value, list)
and not collection_value
):
- return False
+ empty_collection_source = collection_source
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
+ if empty_collection_source is not None:
+ body_node_ids_without_return = body_node_ids - {return_node_id}
+ if len(body_node_ids_without_return) != 1:
+ return False
+ body_node_id = next(iter(body_node_ids_without_return))
+ body_node = self.graph.get_node(body_node_id)
+ control_node_types = (
+ ForInvocation,
+ ForReturnInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ IfInvocation,
+ CallSavedWorkflowInvocation,
+ )
+ if (
+ len(self.graph.nodes) != 4
+ or len(self.graph.edges) != 4
+ or set(self.graph.nodes)
+ != {empty_collection_source.id, for_nodes[0].id, body_node_id, return_nodes[0].id}
+ or isinstance(empty_collection_source, control_node_types)
+ or isinstance(body_node, control_node_types)
+ or len(collection_edges) != 1
+ or self.graph._get_input_edges(empty_collection_source.id)
+ or self.graph._get_output_edges(empty_collection_source.id) != collection_edges
+ or self.graph._get_input_edges(for_nodes[0].id) != collection_edges
+ or collection_edges[0].source.field != "value"
+ or collection_edges[0].destination.field != COLLECTION_FIELD
+ or self.graph._get_output_edges(for_nodes[0].id, ITEM_FIELD)
+ != [edge for edge in self.graph._get_input_edges(body_node_id) if edge.source.field == ITEM_FIELD]
+ or len(self.graph._get_input_edges(body_node_id)) != 1
+ or self.graph._get_input_edges(body_node_id)[0].source.node_id != for_nodes[0].id
+ or self.graph._get_input_edges(body_node_id)[0].source.field != ITEM_FIELD
+ or self.graph._get_output_edges(body_node_id, "value")
+ != self.graph._get_input_edges(return_nodes[0].id, "output")
+ or len(self.graph._get_input_edges(return_nodes[0].id, "output")) != 1
+ or len(self.graph._get_input_edges(return_nodes[0].id, "loop_linkage", include_loop_linkage=True)) != 1
+ or self.graph._get_input_edges(return_nodes[0].id, "loop_linkage", include_loop_linkage=True)[
+ 0
+ ].source.node_id
+ != for_nodes[0].id
+ or self.graph._get_input_edges(return_nodes[0].id, "loop_linkage", include_loop_linkage=True)[
+ 0
+ ].source.field
+ != "loop_linkage"
+ or self.graph._get_for_final_output_edges(for_nodes[0].id)
+ ):
+ return False
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
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index e680559c90..b3b9a94898 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -5181,20 +5181,99 @@ def test_empty_literal_flat_for_matches_compatibility_scheduler() -> None:
assert _state_projection(generic_state) == _state_projection(compatibility_state)
-def test_input_driven_empty_flat_for_uses_compatibility_scheduler() -> None:
+def test_input_driven_empty_flat_for_uses_generic_scheduler_and_exact_terminal_semantics() -> None:
state = GraphExecutionState(graph=_flat_for_graph(input_collection=[]))
- assert state._can_use_generic_scheduler() is False
+ assert state._can_use_generic_scheduler()
trace, state = _run_graph_with_effects(state)
assert trace == ["collection"]
- assert isinstance(state._execution_scheduler, _ExecutionScheduler)
- assert _final_for_output(state).output_collection == []
+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)
+ final_output = _final_for_output(state)
+ assert final_output.item is None
+ assert final_output.index == -1
+ assert final_output.total == 0
+ assert final_output.state == LoopState()
+ assert final_output.output_collection == []
+ assert final_output.final_state == LoopState()
+ assert "body" not in state.source_prepared_mapping
+ assert "return" not in state.source_prepared_mapping
assert state.is_complete()
assert list(state._generic_runtime().continuations.values()) == []
_assert_execution_identity_consistent(state)
+def test_input_driven_empty_flat_for_matches_compatibility_scheduler() -> None:
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph(input_collection=[]))
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace == ["collection"]
+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)
+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ _assert_execution_identity_consistent(generic_state)
+ _assert_execution_identity_consistent(compatibility_state)
+
+
+def test_input_driven_empty_flat_for_checkpoint_after_producer_does_not_replay() -> None:
+ expected_trace, expected_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph(input_collection=[]))
+ )
+ partial_trace, partial_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])),
+ stop_after_source="collection",
+ )
+
+ restored = load_execution_state(dump_execution_state(partial_state))
+ resumed_trace, restored = _run_graph_with_effects(restored)
+ terminal_reload = load_execution_state(dump_execution_state(restored))
+
+ assert expected_trace == partial_trace == ["collection"]
+ assert resumed_trace == []
+ assert isinstance(restored._execution_scheduler, _GenericGraphSchedulerAdapter)
+ assert _state_projection(restored) == _state_projection(expected_state)
+ assert terminal_reload.is_complete()
+ assert _state_projection(terminal_reload) == _state_projection(restored)
+ assert _final_for_output(terminal_reload).output_collection == []
+ _assert_execution_identity_consistent(restored)
+ _assert_execution_identity_consistent(terminal_reload)
+
+
+def test_input_driven_empty_flat_for_with_downstream_remains_compatibility_owned() -> None:
+ state = GraphExecutionState(graph=_flat_for_graph(input_collection=[], with_after=True))
+
+ assert state._can_use_generic_scheduler() is False
+ assert isinstance(state._scheduler(), _ExecutionScheduler)
+
+
+def test_input_driven_empty_flat_for_with_index_body_edge_remains_compatibility_owned() -> None:
+ graph = _flat_for_graph(input_collection=[])
+ body_edge = next(edge for edge in graph.edges if edge.destination.node_id == "body")
+ graph.delete_edge(body_edge)
+ graph.add_edge(create_edge("for", "index", "body", body_edge.destination.field))
+
+ state = GraphExecutionState(graph=graph)
+
+ assert state._can_use_generic_scheduler() is False
+
+
+def test_input_driven_empty_flat_for_with_wrong_return_edge_remains_compatibility_owned() -> None:
+ graph = _flat_for_graph(input_collection=[])
+ graph.delete_node("body")
+ graph.add_node(StateSetInvocation(id="body"))
+ graph.add_edge(create_edge("for", "item", "body", "value"))
+ graph.add_edge(create_edge("body", "state", "return", "state"))
+
+ state = GraphExecutionState(graph=graph)
+
+ assert state._can_use_generic_scheduler() is False
+
+
def test_input_driven_flat_for_uses_generic_scheduler() -> None:
state = GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7]))