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.

Expand direct Iterate fan-in to three branches

JPPhoto26a36f1cd586
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 32ce693a69..9620227f9d 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -111,10 +111,10 @@ explicit empty close. A direct `Iterate.item` consumer waits for the canonical s
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 and any number of ordinary downstream
consumers from `Collect.collection` use a private graph-state planner for prepared-copy expansion, iteration paths,
-and the empty-stream barrier. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` fan-in shape also uses
-the planner for independent stream expansion, closure gating, and deterministic source-ordered hydration. Fan-in
-beyond that shape, nested or input-driven iterators, and mixed control flow remain on the compatibility materializer
-for those responsibilities.
+and the empty-stream barrier. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh
+three-source/three-`Iterate`/shared-`Collect.item` fan-in shapes also use the planner for independent stream expansion,
+closure gating, and deterministic source-ordered hydration. Fan-in with four or more branches, 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
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 58a8e8fa5e..b83a3eacdc 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -23,10 +23,11 @@ completion mirrors each Iterate result into that ledger before releasing `Collec
`literal collection source -> Iterate -> one ordinary body -> Collect`, plus any number of ordinary downstream
consumers from `Collect.collection`, is planned by a private graph-state planner, which owns its prepared-copy
expansion, iteration paths, downstream admission, and explicit empty-stream barrier without calling the legacy
-materializer. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` fan-in shape also uses the planner for
-two independent stream expansions, closure gating, and deterministic source-ordered hydration. Fan-in beyond that
-shape, nested or input-driven iterators, and all mixed control flow retain materializer copy expansion, grouping, and
-empty-source handling on the legacy compatibility route.
+materializer. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh three-source/three-`Iterate`/
+shared-`Collect.item` fan-in shapes also use the planner for independent stream expansions, closure gating, and
+deterministic source-ordered hydration. Fan-in with four or more 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.
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
@@ -162,8 +163,9 @@ one ordinary preparation node from `For.item` into `Iterate.collection`, one ord
the `Collect.collection` output into the linked `ForReturn`, and one final outer-output consumer. Each outer iteration,
including an empty inner collection, remains isolated by its frame path. `Iterate` also records non-empty item streams through the generic effect ledger;
the materializer remains authoritative for fallback expansion, iteration paths, collector grouping, and
-empty-source compatibility handling. The exact fresh four-node body shape and exact two-stream fan-in shape use
-the private planner for those responsibilities. Direct `Collect.item` consumers now use the closed stream ledger when available;
+empty-source compatibility handling. The exact fresh four-node body shape and exact two- or three-stream fan-in shapes
+use the private planner for those responsibilities; four or more streams remain compatibility-owned. 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.
@@ -257,8 +259,8 @@ control-flow invocation on this seam: each non-empty prepared copy emits one ord
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 exact fresh four-node source/Iterate/body/Collect shape,
-its ordinary downstream consumers, and the exact two-stream fan-in shape use the private planner described above;
-fallback shapes still let the
+its ordinary downstream consumers, and the exact two- or three-stream fan-in shapes use the private planner described
+above; four or more streams and other fallback shapes still let the
materializer create
prepared copies, derive iteration paths, group collector inputs, and record the explicit close for an empty source.
For a direct `Iterate.item` edge, the scheduler defers `CollectInvocation` while its canonical stream is open, and
@@ -306,8 +308,8 @@ frame-scoped continuation effects and generic readiness/continuation
projection.
Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for
readiness and completion. The exact fresh four-node source/Iterate/body/Collect
-shape, its ordinary downstream-consumer extensions, and the exact two-stream
-fan-in shape use the private planner for expansion and empty-stream closure; workflow-call
+shape, its ordinary downstream-consumer extensions, and the exact two- or three-stream
+fan-in shapes use the private planner for expansion and empty-stream closure; four or more streams, workflow-call
invocations, unsupported loop shapes, and mixed control-flow graphs remain on
compatibility paths. `ForInvocation` and
`ForReturnInvocation` now declare one validated, frame-scoped `continuation`
@@ -576,8 +578,8 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac
with a contiguous sequence beginning at zero, and closes its canonical
source/parent-path stream on the final copy. Exact output mirroring is
idempotent. The private planner closes empty streams for the exact fresh
- source/Iterate/body/Collect and two-stream fan-in shapes; fallback shapes
- retain materializer compatibility ownership.
+ source/Iterate/body/Collect and exact two- or three-stream fan-in shapes; four or more
+ streams and other fallback shapes retain materializer compatibility ownership.
- Collectors wait for available direct Iterate streams to close, then aggregate
their ledger values in stream order and may also merge incoming `collection`
inputs during runtime hydration. A missing ledger remains a legacy snapshot
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index f4a2c92edb..83186adc49 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -129,7 +129,7 @@ class _SupportedNestedForBody:
@dataclass(frozen=True)
class _DirectIterateCollectFanIn:
- branches: tuple[tuple[str, str], tuple[str, str]]
+ branches: tuple[tuple[str, str], ...]
collector_id: str
@@ -6726,11 +6726,14 @@ class GraphExecutionState(BaseModel):
def _get_direct_iterate_collect_fan_in(
self, iterator_ids: list[str], collector_id: str
) -> Optional[_DirectIterateCollectFanIn]:
- if len(self.graph.nodes) != 5 or len(self.graph.edges) != 4:
+ branch_count = len(iterator_ids)
+ if branch_count not in {2, 3} or len(self.graph.nodes) != 2 * branch_count + 1:
+ return None
+ if len(self.graph.edges) != 2 * branch_count:
return None
item_edges = self.graph._get_input_edges(collector_id, ITEM_FIELD)
- if len(item_edges) != 2 or self.graph._get_input_edges(collector_id, COLLECTION_FIELD):
+ if len(item_edges) != branch_count or self.graph._get_input_edges(collector_id, COLLECTION_FIELD):
return None
if {edge.source.node_id for edge in item_edges} != set(iterator_ids) or any(
edge.destination.field != ITEM_FIELD or edge.source.field != ITEM_FIELD for edge in item_edges
@@ -6771,7 +6774,7 @@ class GraphExecutionState(BaseModel):
branches.append((source_id, iterator_id))
branches.sort(key=lambda branch: branch[0])
- return _DirectIterateCollectFanIn(branches=(branches[0], branches[1]), collector_id=collector_id)
+ return _DirectIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
def _get_direct_iterate_collect_nodes(
self,
@@ -6787,7 +6790,7 @@ class GraphExecutionState(BaseModel):
iterator_ids = [node_id for node_id, node in self.graph.nodes.items() if isinstance(node, IterateInvocation)]
collector_ids = [node_id for node_id, node in self.graph.nodes.items() if isinstance(node, CollectInvocation)]
- if len(iterator_ids) == 2 and len(collector_ids) == 1:
+ if len(iterator_ids) in {2, 3} and len(collector_ids) == 1:
return self._get_direct_iterate_collect_fan_in(iterator_ids, collector_ids[0])
if len(iterator_ids) != 1 or len(collector_ids) != 1:
return None
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index b8606d16b2..90597a092d 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -332,6 +332,44 @@ def _direct_iterate_fan_in_graph(*, left: list[Any], right: list[Any]) -> Graph:
return graph
+def _direct_iterate_fan_in_graph_with_branches(
+ branches: tuple[tuple[str, str, list[Any]], ...],
+) -> Graph:
+ graph = Graph()
+ graph.add_node(CollectInvocation(id="collect"))
+ for source_id, iterator_id, values in sorted(branches):
+ graph.add_node(CollectionConcatInvocation(id=source_id, first=values))
+ graph.add_node(IterateInvocation(id=iterator_id))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=source_id, field="collection"),
+ destination=EdgeConnection(node_id=iterator_id, field="collection"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=iterator_id, field="item"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ )
+ )
+ return graph
+
+
+def _direct_iterate_three_fan_in_graph(
+ *,
+ a: list[Any],
+ m: list[Any],
+ z: list[Any],
+) -> Graph:
+ return _direct_iterate_fan_in_graph_with_branches(
+ branches=(
+ ("z_source", "z_iterate", z),
+ ("a_source", "a_iterate", a),
+ ("m_source", "m_iterate", m),
+ )
+ )
+
+
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})))
@@ -1608,6 +1646,243 @@ def test_direct_iterate_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.
assert state.is_complete()
+def test_direct_iterate_three_fan_in_fresh_execution_owns_sorted_stream_expansion() -> None:
+ graph = _direct_iterate_three_fan_in_graph(a=["dup", None, "dup"], m=["middle"], z=[None, "dup"])
+ state = GraphExecutionState(graph=graph)
+ fan_in = state._get_direct_iterate_collect_nodes()
+ assert isinstance(fan_in, graph_module._DirectIterateCollectFanIn)
+ assert fan_in.branches == (
+ ("a_source", "a_iterate"),
+ ("m_source", "m_iterate"),
+ ("z_source", "z_iterate"),
+ )
+
+ with (
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("fresh three-branch fan-in must not use materializer.prepare"),
+ ) as prepare,
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "_get_collect_iteration_mapping_groups",
+ side_effect=AssertionError("fresh three-branch fan-in must not group collector inputs"),
+ ) as group_collector_inputs,
+ ):
+ trace, state = _run_graph(state)
+
+ assert trace == [
+ "a_source",
+ "m_source",
+ "z_source",
+ "a_iterate",
+ "m_iterate",
+ "z_iterate",
+ "a_iterate",
+ "z_iterate",
+ "a_iterate",
+ "collect",
+ ]
+ assert _source_output(state, "collect").collection == ["dup", None, "dup", "middle", None, "dup"]
+ streams = {
+ stream.owner_id: stream
+ for stream in state._generic_runtime().streams.values()
+ if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}
+ }
+ assert {owner_id: (stream.values, stream.closed) for owner_id, stream in streams.items()} == {
+ "a_iterate": (("dup", None, "dup"), True),
+ "m_iterate": (("middle",), True),
+ "z_iterate": ((None, "dup"), True),
+ }
+ assert state.is_complete()
+ prepare.assert_not_called()
+ group_collector_inputs.assert_not_called()
+
+
+ ("a", "m", "z"),
+ [
+ ([], [], []),
+ (["a"], [], []),
+ ([], ["m"], []),
+ ([], [], ["z"]),
+ (["a"], ["m"], []),
+ (["a"], [], ["z"]),
+ ([], ["m"], ["z"]),
+ ],
+ ids=["all-empty", "a-only", "m-only", "z-only", "a-m", "a-z", "m-z"],
+)
+def test_direct_iterate_three_fan_in_closes_every_empty_stream(a: list[Any], m: list[Any], z: list[Any]) -> None:
+ trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)))
+
+ assert trace.count("collect") == 1
+ assert _source_output(state, "collect").collection == a + m + z
+ streams = {
+ stream.owner_id: stream
+ for stream in state._generic_runtime().streams.values()
+ if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}
+ }
+ assert set(streams) == {"a_iterate", "m_iterate", "z_iterate"}
+ assert all(stream.closed for stream in streams.values())
+ assert state.is_complete()
+
+
+def test_direct_iterate_three_fan_in_partial_dump_load_resumes_without_duplicate_work() -> None:
+ graph = _direct_iterate_three_fan_in_graph(a=["a-0", "a-1"], m=["m-0", "m-1"], z=["z-0", "z-1"])
+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))
+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=5)
+
+ assert partial_trace == ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"]
+ assert "collect" not in partial_trace
+ collect_exec_ids = partial_state.source_prepared_mapping["collect"]
+ assert len(collect_exec_ids) == 1
+ collect_exec_id = next(iter(collect_exec_ids))
+ assert collect_exec_id not in partial_state.executed
+
+ restored = load_execution_state(dump_execution_state(partial_state))
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ restored, execution_ids=set(partial_state.execution_refs)
+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)
+ resumed_trace, resumed_state = _run_graph_with_effects(restored)
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert _source_output(resumed_state, "collect").collection == ["a-0", "a-1", "m-0", "m-1", "z-0", "z-1"]
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ resumed_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
+ assert collect_exec_id in resumed_state.executed
+ assert resumed_state.is_complete()
+
+
+ ("a", "m", "z"),
+ [
+ (["a", None, "a"], ["m"], ["z", None]),
+ ([], ["m", "m"], []),
+ ([], [], []),
+ ],
+ ids=["ordered-none-duplicates", "mixed-empty-duplicates", "all-empty"],
+)
+def test_direct_iterate_three_fan_in_matches_forced_compatibility_scheduler(
+ a: list[Any], m: list[Any], z: list[Any]
+) -> None:
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z))
+ )
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)),
+ force_compatibility_scheduler=True,
+ )
+
+ assert generic_trace == compatibility_trace
+ assert (
+ _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection
+ )
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+
+
+ ("fail_source_id", "expected_trace"),
+ [
+ ("m_source", ["a_source", "m_source"]),
+ (
+ "m_iterate",
+ ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"],
+ ),
+ ],
+ ids=["source-failure", "iterator-failure"],
+)
+def test_direct_iterate_three_fan_in_failure_matches_compatibility_and_blocks_collect(
+ fail_source_id: str, expected_trace: list[str]
+) -> None:
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),
+ fail_source_id=fail_source_id,
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),
+ force_compatibility_scheduler=True,
+ fail_source_id=fail_source_id,
+ )
+
+ assert generic_trace == compatibility_trace == expected_trace
+ for state in (generic_state, compatibility_state):
+ assert state.next() is None
+ assert state.has_error()
+ assert "collect" not in {
+ state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed
+ }
+ assert state.is_complete()
+ restored = load_execution_state(dump_execution_state(state))
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)
+ assert restored.next() is None
+ assert restored.is_complete()
+
+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+
+
+def test_direct_iterate_three_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.MonkeyPatch) -> None:
+ state = GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"]))
+ _partial_trace, state = _run_graph(state, stop_after=3)
+
+ original_create = GraphExecutionState._create_direct_execution_node_copy
+
+ def fail_at_m_iterate(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):
+ if source_node_id == "m_iterate":
+ raise RuntimeError("injected three-branch fan-in planner failure")
+ return original_create(self, source_node_id, *args, **kwargs)
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_m_iterate)
+ with pytest.raises(RuntimeError, match="injected three-branch fan-in planner failure"):
+ state.next()
+
+ assert set(state.source_prepared_mapping) == {"a_source", "m_source", "z_source"}
+ assert len(state.execution_graph.nodes) == 3
+ assert not state.execution_graph.edges
+ assert not state._generic_runtime().streams
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)
+ trace, state = _run_graph(state)
+
+ assert trace == ["a_iterate", "m_iterate", "z_iterate", "collect"]
+ assert _source_output(state, "collect").collection == ["a", "m", "z"]
+ assert state.is_complete()
+
+
+def test_direct_iterate_four_fan_in_stays_on_compatibility_fallback() -> None:
+ graph = _direct_iterate_fan_in_graph_with_branches(
+ branches=(
+ ("a_source", "a_iterate", ["a"]),
+ ("m_source", "m_iterate", ["m"]),
+ ("z_source", "z_iterate", ["z"]),
+ ("q_source", "q_iterate", ["q"]),
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+ assert state._get_direct_iterate_collect_nodes() is None
+
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True
+ )
+
+ assert compatibility_trace
+ assert sorted(_source_output(compatibility_state, "collect").collection) == ["a", "m", "q", "z"]
+ assert compatibility_state.is_complete()
+
+
def test_direct_iterate_body_collect_fresh_execution_handles_empty_input() -> None:
state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[]))
with (