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): plan direct Iterate downstream consumer

JPPhotod7aee4b59494
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index d0d115f322..51d86a6589 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -109,17 +109,18 @@ scheduling for the remaining 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 exact fresh four-node
-`literal collection source -> Iterate -> one ordinary body -> Collect` shape uses a private graph-state planner for
-prepared-copy expansion, iteration paths, and the empty-stream barrier. Downstream consumers, fan-in, nested or
-input-driven iterators, and mixed control flow remain on the compatibility materializer for those responsibilities.
+`literal collection source -> Iterate -> one ordinary body -> Collect` shape, with one ordinary downstream consumer
+from `Collect.collection`, uses a private graph-state planner for prepared-copy expansion, iteration paths, and the
+empty-stream barrier. Fan-in, additional downstream consumers, nested or input-driven iterators, and mixed control
+flow remain on the compatibility materializer for those responsibilities.
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. 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.
-For the exact fresh four-node shape, the planner owns expansion and empty closure atomically: a failed expansion leaves
-no partial prepared copies to be resumed. Versioned queue checkpoints and retries preserve the existing durable
+For the exact fresh direct shape, the planner owns expansion, downstream admission, and empty closure atomically: a
+failed expansion leaves no partial prepared copies to be resumed. Versioned queue checkpoints and retries preserve the existing durable
execution-state boundary and receive fresh execution identities. Materialization still owns those responsibilities for
fallback shapes. Mixed control-flow and queue lifecycle remain compatibility-owned. `loop_linkage`
remains association metadata and never becomes a data token.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index aa1d499bf2..145bc7c65a 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -6679,10 +6679,14 @@ class GraphExecutionState(BaseModel):
return next_node
- def _get_direct_iterate_collect_nodes(self) -> Optional[tuple[str, str, str, str]]:
- """Return the source, iterator, body, and collector for the narrow direct planner shape."""
+ def _get_direct_iterate_collect_nodes(self) -> Optional[tuple[str, str, str, str, str | None]]:
+ """Return the direct planner nodes, including one optional ordinary downstream consumer."""
- if self._legacy_snapshot_loaded or len(self.graph.nodes) != 4 or len(self.graph.edges) != 3:
+ if (
+ self._legacy_snapshot_loaded
+ or len(self.graph.nodes) not in {4, 5}
+ or len(self.graph.edges) != len(self.graph.nodes) - 1
+ ):
return None
iterator_ids = [node_id for node_id, node in self.graph.nodes.items() if isinstance(node, IterateInvocation)]
@@ -6735,7 +6739,23 @@ class GraphExecutionState(BaseModel):
if self.graph._get_input_edges(collector_id) != [item_edge]:
return None
- return source_id, iterator_id, body_id, collector_id
+ downstream_id: str | None = None
+ downstream_edges = self.graph._get_output_edges(collector_id, COLLECTION_FIELD)
+ if len(self.graph.nodes) == 5:
+ if len(downstream_edges) != 1:
+ return None
+ downstream_id = downstream_edges[0].destination.node_id
+ downstream = self.graph.get_node(downstream_id)
+ if downstream_id in {source_id, iterator_id, body_id, collector_id} or isinstance(
+ downstream, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)
+ ):
+ return None
+ if self.graph._get_input_edges(downstream_id) != downstream_edges:
+ return None
+ elif downstream_edges:
+ return None
+
+ return source_id, iterator_id, body_id, collector_id, downstream_id
def _can_use_direct_iterate_collect_planner(self) -> bool:
"""Use fresh planner ownership only for the exact direct stream shape."""
@@ -6817,7 +6837,7 @@ class GraphExecutionState(BaseModel):
node_ids = self._get_direct_iterate_collect_nodes()
if node_ids is None:
return
- source_id, iterator_id, body_id, collector_id = node_ids
+ source_id, iterator_id, body_id, collector_id, downstream_id = node_ids
if source_id not in self.source_prepared_mapping:
source_node = self._create_direct_execution_node_copy(source_id)
@@ -6878,6 +6898,20 @@ class GraphExecutionState(BaseModel):
attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+ if downstream_id is not None:
+ downstream_node = self._create_direct_execution_node_copy(downstream_id)
+ downstream_edge = self.graph._get_input_edges(downstream_id)[0]
+ attached_downstream_edges = self._attach_direct_execution_edges(
+ downstream_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=collector_node.id, field=downstream_edge.source.field),
+ destination=EdgeConnection(node_id="", field=downstream_edge.destination.field),
+ )
+ ],
+ )
+ self._initialize_direct_execution_node(downstream_node.id, attached_downstream_edges)
+
def _reset_runtime_caches(self) -> None:
self._ready_queues = {}
self._ready_node_ids = set()
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 44a7631716..3d84d35a41 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -1318,6 +1318,37 @@ def test_direct_iterate_body_collect_planner_rolls_back_partial_expansion(
assert state.is_complete()
+def test_direct_iterate_body_collect_downstream_planner_rolls_back_partial_expansion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"], with_after=True))
+ source_node = state.next()
+ assert source_node is not None
+ state.complete(source_node.id, source_node.invoke(Mock()))
+
+ original_create = GraphExecutionState._create_direct_execution_node_copy
+
+ def fail_at_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):
+ if source_node_id == "after":
+ raise RuntimeError("injected downstream planner failure")
+ return original_create(self, source_node_id, *args, **kwargs)
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_downstream)
+ with pytest.raises(RuntimeError, match="injected downstream planner failure"):
+ state.next()
+
+ assert set(state.source_prepared_mapping) == {"source"}
+ assert len(state.execution_graph.nodes) == 1
+ assert not state.execution_graph.edges
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)
+ trace, state = _run_graph(state)
+
+ assert trace == ["iterate", "iterate", "body", "body", "collect", "after"]
+ assert _source_output(state, "after").value == ["first", "last"]
+ assert state.is_complete()
+
+
@pytest.mark.parametrize(
"collection",
[
@@ -1419,16 +1450,19 @@ def test_direct_iterate_body_collect_failure_rehydrates_pending_state_without_re
assert restored.is_complete()
-def test_direct_iterate_body_collect_with_downstream_consumer_uses_fallback_materializer() -> None:
- prepare_calls = 0
- original_prepare = graph_module._ExecutionMaterializer.prepare
-
- def prepare_spy(materializer: Any, base_graph: Any = None) -> Any:
- nonlocal prepare_calls
- prepare_calls += 1
- return original_prepare(materializer, base_graph)
-
- with patch.object(graph_module._ExecutionMaterializer, "prepare", autospec=True, side_effect=prepare_spy):
+def test_direct_iterate_body_collect_with_downstream_consumer_uses_private_planner() -> None:
+ with (
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("direct Iterate -> body -> Collect -> after must not use materializer.prepare"),
+ ) as prepare,
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "_get_collect_iteration_mapping_groups",
+ side_effect=AssertionError("direct downstream Collect must not group collector inputs"),
+ ) as group_collector_inputs,
+ ):
trace, state = _run_graph(
GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], with_after=True))
)
@@ -1436,7 +1470,30 @@ def test_direct_iterate_body_collect_with_downstream_consumer_uses_fallback_mate
assert trace[-1] == "after"
assert _source_output(state, "after").value == ["value"]
assert state.is_complete()
- assert prepare_calls > 0
+ prepare.assert_not_called()
+ group_collector_inputs.assert_not_called()
+
+
+def test_direct_iterate_body_collect_with_downstream_consumer_matches_forced_compatibility_scheduler() -> None:
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(
+ graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)
+ )
+ )
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(
+ graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)
+ ),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_trace[-2:] == ["collect", "after"]
+ assert _source_output(generic_state, "after").value == ["first", None, "last"]
+ assert _source_output(compatibility_state, "after").value == ["first", None, "last"]
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None: