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
feat(execution): plan bounded input-driven iterate streams
JPPhoto1f8cd6025fc4
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex e392905a68..b6270c6ac7 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -66,9 +66,17 @@ inputless ordinary sources, two `Iterate` nodes, two ordinary bodies, and one`Collect`; it has no`Collect.collection` input or downstream/extra topology. It is not a change tothe public workflow contract.+The planner also admits one bounded input-driven extension: one inputless+ordinary collection producer feeds one ordinary collection-preparation node,+which feeds the same `Iterate` -> ordinary body -> `Collect` path, with+ordinary downstream consumers allowed. It owns the preparation input edge,+ordered stream effects, empty closure, checkpoint rehydration, failure,+rollback, and fresh retry behavior for that exact shape. It does not admit+`If`, `For`, `ForReturn`, saved-workflow, nested-iterator, fan-in, or mixed+control-flow nodes; those remain compatibility-owned.Three or more body-mediated branches, fan-in with four or more direct branches,-nested or input-driven iterators, and all mixed control flow retain materializer-copy expansion, grouping, and empty-source handling on the legacy compatibility route.+nested iterators, and all mixed control flow retain materializer copy expansion,+grouping, and empty-source handling on the legacy compatibility route.A fresh graph with exactly one static, non-empty `For`/`ForReturn` pair and ordinary body nodes also uses the genericadapter. 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 ownsdiff --git a/invokeai/app/services/shared/graph_iterate_planner.py b/invokeai/app/services/shared/graph_iterate_planner.pyindex e9efad52fe..857273ce7d 100644--- a/invokeai/app/services/shared/graph_iterate_planner.py+++ b/invokeai/app/services/shared/graph_iterate_planner.py@@ -164,7 +164,7 @@ def _get_body_iterate_collect_fan_in(def _get_direct_iterate_collect_nodes(state: "GraphExecutionState",) -> Optional[tuple[str, str, str, str, tuple[str, ...]] | _DirectIterateCollectFanIn | _BodyIterateCollectFanIn]:- """Return fresh direct/body planner nodes, including ordinary downstream consumers."""+ """Return bounded fresh stream-planner nodes, including one input-driven source chain."""if (state._legacy_snapshot_loaded@@ -218,8 +218,22 @@ def _get_direct_iterate_collect_nodes(source = state.graph.get_node(source_id)if isinstance(source, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)):return None- if state.graph._get_input_edges(source_id):+ source_input_edges = state.graph._get_input_edges(source_id)+ if len(source_input_edges) > 1:return None+ for source_input_edge in source_input_edges:+ upstream_id = source_input_edge.source.node_id+ if upstream_id in {source_id, iterator_id, body_id, collector_id}:+ return None+ upstream = state.graph.get_node(upstream_id)+ if isinstance(+ upstream, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)+ ):+ return None+ if state.graph._get_input_edges(upstream_id) or state.graph._get_output_edges(upstream_id) != [+ source_input_edge+ ]:+ return Noneif state.graph._get_output_edges(source_id) != [collection_edge]:return Noneif state.graph._get_output_edges(iterator_id) != [body_input_edges[0]]:@@ -230,7 +244,8 @@ def _get_direct_iterate_collect_nodes(return Nonedownstream_edges = state.graph._get_output_edges(collector_id, COLLECTION_FIELD)- if len(downstream_edges) != len(state.graph.nodes) - 4:+ upstream_count = len(source_input_edges)+ if len(downstream_edges) != len(state.graph.nodes) - 4 - upstream_count:return Nonedownstream_ids: list[str] = []for downstream_edge in downstream_edges:@@ -248,7 +263,7 @@ def _get_direct_iterate_collect_nodes(def _can_use_direct_iterate_collect_planner(state: "GraphExecutionState") -> bool:- """Use fresh planner ownership only for the exact direct stream shape."""+ """Use fresh planner ownership only for the bounded direct stream shapes."""return state._get_direct_iterate_collect_nodes() is not None@@ -482,8 +497,30 @@ def _prepare_direct_iterate_collect_unchecked(state: "GraphExecutionState") -> Nsource_id, iterator_id, body_id, collector_id, downstream_ids = node_idsif source_id not in state.source_prepared_mapping:+ source_input_edges = state.graph._get_input_edges(source_id)+ source_input_exec_ids: dict[str, str] = {}+ for source_input_edge in source_input_edges:+ upstream_id = source_input_edge.source.node_id+ if upstream_id not in state.source_prepared_mapping:+ upstream_node = state._create_direct_execution_node_copy(upstream_id)+ state._initialize_direct_execution_node(upstream_node.id, ())+ source_input_exec_ids[upstream_id] = next(iter(state.source_prepared_mapping[upstream_id]))+source_node = state._create_direct_execution_node_copy(source_id)- state._initialize_direct_execution_node(source_node.id, ())+ attached_source_edges = state._attach_direct_execution_edges(+ source_node.id,+ [+ Edge(+ source=EdgeConnection(+ node_id=source_input_exec_ids[edge.source.node_id],+ field=edge.source.field,+ ),+ destination=EdgeConnection(node_id="", field=edge.destination.field),+ )+ for edge in source_input_edges+ ],+ )+ state._initialize_direct_execution_node(source_node.id, attached_source_edges)returnif collector_id in state.source_prepared_mapping:diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 8fe051d47e..0950817325 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -608,6 +608,23 @@ def _direct_iterate_body_collect_graph(return graph+def _input_driven_iterate_body_collect_graph(values: list[Any] | None = None) -> Graph:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="producer", first=[1, 2, 3] if values is None else values))+ graph.add_node(CollectionConcatInvocation(id="source"))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(AnyTypeTestInvocation(id="after"))++ graph.add_edge(create_edge("producer", "collection", "source", "first"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "body", "value"))+ graph.add_edge(create_edge("body", "value", "collect", "item"))+ graph.add_edge(create_edge("collect", "collection", "after", "value"))+ return graph++def _direct_iterate_fan_in_graph(*, left: list[Any], right: list[Any]) -> Graph:graph = Graph()graph.add_node(CollectionConcatInvocation(id="left_source", first=left))@@ -1815,6 +1832,121 @@ def test_nested_for_iterate_collect_generic_rehydrates_after_inner_completion()assert _state_projection(resumed_state) == _state_projection(expected_state)[email protected]("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])+def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:+ compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))+ compatibility_trace, compatibility_state = _run(+ compatibility_state,+ force_compatibility_scheduler=True,+ )++ generic_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))+ with patch.object(+ generic_state._materializer(),+ "prepare",+ side_effect=AssertionError("input-driven Iterate/Collect must not use materializer.prepare"),+ ):+ generic_trace, generic_state = _run(generic_state)++ 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)+ assert _source_output(generic_state, "after").value == values+++def test_input_driven_iterate_collect_partial_dump_load_preserves_generic_streams() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run_graph(GraphExecutionState(graph=graph), stop_after=3)++ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("input-driven checkpoint must not use materializer.prepare"),+ ):+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "after").value == ["first", None, "last"]+ assert _state_projection(resumed_state) == _state_projection(expected_state)+++def test_input_driven_iterate_collect_failure_matches_compatibility() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", "last"])+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph), fail_source_id="body")+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True, fail_source_id="body"+ )++ assert generic_trace == compatibility_trace+ assert generic_state.has_error() == compatibility_state.has_error()+ assert generic_state.is_complete() == compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert generic_state.next() is None+++def test_input_driven_iterate_collect_planner_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(["first", "last"]))+ for _ in range(2):+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))++ original_create = GraphExecutionState._create_direct_execution_node_copy++ def fail_at_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ node = original_create(self, source_node_id, *args, **kwargs)+ if source_node_id == "body":+ raise RuntimeError("injected input-driven planner failure")+ return node++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_body)+ with pytest.raises(RuntimeError, match="injected input-driven planner failure"):+ state.next()++ assert set(state.source_prepared_mapping) == {"producer", "source"}+ assert len(state.execution_graph.nodes) == 2+ assert len(state.execution_graph.edges) == 1++ 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()+++def test_input_driven_iterate_collect_retry_after_input_boundary_isolated() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])+ canceled_trace, canceled_state = _run_until_source(+ GraphExecutionState(graph=graph),+ "source",+ )+ retry_trace, retry_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))++ assert canceled_trace == ["producer", "source"]+ assert not canceled_state.is_complete()+ assert retry_trace == [+ "producer",+ "source",+ "iterate",+ "iterate",+ "iterate",+ "body",+ "body",+ "body",+ "collect",+ "after",+ ]+ assert retry_state.id != canceled_state.id+ assert _source_output(retry_state, "after").value == ["first", None, "last"]+ assert retry_state.is_complete()++def test_direct_iterate_body_collect_fresh_execution_preserves_order_and_none() -> None:collection = ["first", None, "last"]state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))