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): hydrate Collect from closed streams

JPPhoto31d7814a73d1
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 81173a2e80..b37262f21d 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -1857,11 +1857,14 @@ class _ExecutionScheduler:
raise KeyError(f"indegree missing for exec node {exec_node_id}")
def _should_skip_ready_enqueue(self, exec_node_id: str) -> bool:
- return (
+ if (
self._state.indegree[exec_node_id] != 0
or exec_node_id in self._state.executed
or self._state._is_deferred_by_unresolved_if(exec_node_id)
- )
+ ):
+ return True
+ node = self._state.execution_graph.nodes[exec_node_id]
+ return isinstance(node, CollectInvocation) and not self._state._collect_streams_ready(exec_node_id)
def _get_ready_queue(self, exec_node_id: str) -> Deque[str]:
node_obj = self._state.execution_graph.nodes[exec_node_id]
@@ -2589,7 +2592,7 @@ class _ExecutionRuntime:
continue
stream_id, parent_path = stream_info
stream = self._state._generic_runtime().streams.get(stream_id)
- if stream is None or not stream.closed:
+ if stream is None:
item_values.append(
(
(*self.get_iteration_path(edge.source.node_id), 0),
@@ -2598,6 +2601,8 @@ class _ExecutionRuntime:
)
)
continue
+ if not stream.closed:
+ raise RuntimeError(f"Cannot hydrate Collect from open Iterate stream {stream_id}")
if stream_id in consumed_streams:
continue
consumed_streams.add(stream_id)
@@ -4843,7 +4848,9 @@ class GraphExecutionState(BaseModel):
path = ",".join(str(index) for index in parent_path)
return f"{self.id}:iterate:{source_node_id}:{path}"
- def _record_iterate_stream(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
+ def _record_iterate_stream(
+ self, exec_node_id: str, output: BaseInvocationOutput, *, prefer_existing: bool = False
+ ) -> None:
if not isinstance(output, IterateInvocationOutput):
return
source_node_id = self.prepared_source_mapping.get(exec_node_id)
@@ -4860,9 +4867,25 @@ class GraphExecutionState(BaseModel):
elif self._apply_transaction is not None:
previous = StreamBuffer[Any].model_validate(stream.model_dump(mode="python"))
self._tx_record_once(("stream", stream_id), lambda: runtime.replace_stream(previous))
- stream.accept(StreamData(sequence=output.index, value=copydeep(output.item)))
+ skip_data = False
+ if prefer_existing:
+ existing = next((event for event in stream.events if event.sequence == output.index), None)
+ if existing is not None:
+ if isinstance(existing, StreamData) and existing.value != output.item:
+ # Durable effect values are authoritative when an older result mirror is stale.
+ skip_data = True
+ elif isinstance(existing, StreamData):
+ skip_data = True
+ else:
+ raise ValueError(f"Iterate result conflicts with closed stream {stream_id}")
+ if not skip_data:
+ stream.accept(StreamData(sequence=output.index, value=copydeep(output.item)))
if output.index + 1 >= output.total:
- stream.close(sequence=output.total)
+ if stream.closed:
+ if stream.end_sequence != output.total:
+ raise ValueError(f"Iterate result conflicts with closed stream {stream_id}")
+ else:
+ stream.close(sequence=output.total)
def _record_empty_iterate_stream(self, source_node_id: str, parent_path: tuple[int, ...] = ()) -> None:
runtime = self._generic_runtime()
@@ -4946,6 +4969,19 @@ class GraphExecutionState(BaseModel):
parent_path = iteration_path[:-1] if iteration_path else ()
return self._iteration_stream_id(source_node_id, parent_path), parent_path
+ def _collect_streams_ready(self, exec_node_id: str) -> bool:
+ """Require any available Iterate streams to close before Collect is scheduled."""
+
+ for edge in self.execution_graph._get_input_edges(exec_node_id, ITEM_FIELD):
+ stream_info = self._stream_for_iterate_edge(edge)
+ if stream_info is None:
+ continue
+ stream_id, _parent_path = stream_info
+ stream = self._generic_runtime().streams.get(stream_id)
+ if stream is not None and not stream.closed:
+ return False
+ return True
+
def _for_continuation(self, for_exec_node_id: str) -> ContinuationRecord[Any]:
runtime = self._generic_runtime()
continuation_id = f"{self.id}:for:{for_exec_node_id}"
@@ -5909,14 +5945,6 @@ class GraphExecutionState(BaseModel):
):
self._record_empty_iterate_stream(source_node_id)
- iterate_results: list[tuple[str, IterateInvocationOutput]] = []
- for exec_node_id, output in self.results.items():
- if isinstance(output, IterateInvocationOutput):
- iterate_results.append((exec_node_id, output))
- iterate_results.sort(key=lambda item: (self._get_iteration_path(item[0]), item[1].index, item[0]))
- for exec_node_id, output in iterate_results:
- self._record_iterate_stream(exec_node_id, output)
-
for reference_id, effects in self.execution_effects.items():
execution_ref = next(
(ref for ref in self.execution_refs.values() if ref.reference_id == reference_id),
@@ -5926,6 +5954,14 @@ class GraphExecutionState(BaseModel):
self._validate_effects(execution_ref, list(effects), None)
self._record_effect_streams(execution_ref, effects)
+ iterate_results: list[tuple[str, IterateInvocationOutput]] = []
+ for exec_node_id, output in self.results.items():
+ if isinstance(output, IterateInvocationOutput):
+ iterate_results.append((exec_node_id, output))
+ iterate_results.sort(key=lambda item: (self._get_iteration_path(item[0]), item[1].index, item[0]))
+ for exec_node_id, output in iterate_results:
+ self._record_iterate_stream(exec_node_id, output, prefer_existing=True)
+
for exec_node_id, node in self.execution_graph.nodes.items():
if isinstance(node, ForInvocation) and node.index >= 0 and exec_node_id in self.results:
continuation = self._for_continuation(exec_node_id)
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 069ea87740..758b89357f 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -54,6 +54,8 @@ from invokeai.app.services.shared.execution_effects import (
from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state
from invokeai.app.services.shared.graph import (
CollectInvocation,
+ Edge,
+ EdgeConnection,
Graph,
GraphExecutionState,
IterateInvocation,
@@ -464,6 +466,133 @@ def test_graph_state_maps_iterate_effects_to_the_canonical_iteration_stream():
assert not streams[0].closed
+def test_collect_does_not_hydrate_from_an_open_iterate_stream():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+
+ state = GraphExecutionState(graph=graph)
+ range_node, range_output = invoke_next(state)
+ assert range_node is not None
+ assert range_output is not None
+ iterate_node = state.next()
+ assert isinstance(iterate_node, IterateInvocation)
+ execution_ref = state.get_execution_ref(iterate_node.id)
+ recorder = ExecutionEffectsRecorder(
+ source_node_id=iterate_node.id,
+ frame_path=execution_ref.frame.iteration_path,
+ )
+ context = SimpleNamespace(
+ execution_effects=recorder,
+ effects=recorder,
+ execution=ExecutionInterface(recorder),
+ )
+ run_result = iterate_node.invoke_internal_with_effects(context, Mock())
+ state.apply(state.get_execution_ref(iterate_node.id, effect_count=len(run_result.effects)), run_result)
+
+ state.execution_graph.add_node(CollectInvocation(id="collect"))
+ edge = Edge(
+ source=EdgeConnection(node_id=iterate_node.id, field="item"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ )
+ state.execution_graph.add_edge(edge)
+ assert not state._collect_streams_ready("collect")
+ with pytest.raises(RuntimeError, match="open Iterate stream"):
+ state._runtime()._build_collect_collection([edge])
+
+
+def test_collect_prefers_closed_iterate_effect_stream_over_legacy_output():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ while True:
+ node = state.next()
+ if node is None:
+ break
+ if isinstance(node, IterateInvocation):
+ execution_ref = state.get_execution_ref(node.id)
+ recorder = ExecutionEffectsRecorder(
+ source_node_id=node.id,
+ frame_path=execution_ref.frame.iteration_path,
+ )
+ context = SimpleNamespace(
+ execution_effects=recorder,
+ effects=recorder,
+ execution=ExecutionInterface(recorder),
+ )
+ run_result = node.invoke_internal_with_effects(context, Mock())
+ state.apply(state.get_execution_ref(node.id, effect_count=len(run_result.effects)), run_result)
+ continue
+
+ if isinstance(node, CollectInvocation):
+ for iterate_exec_id in state.source_prepared_mapping["iterate"]:
+ object.__setattr__(state.results[iterate_exec_id], "item", -1)
+ assert node.collection == [0, 1]
+ restored = load_execution_state(dump_execution_state(state))
+ restored_node = restored.next()
+ assert isinstance(restored_node, CollectInvocation)
+ for iterate_exec_id in restored.source_prepared_mapping["iterate"]:
+ object.__setattr__(restored.results[iterate_exec_id], "item", -1)
+ assert restored_node.collection == [0, 1]
+ restored.complete(restored_node.id, restored_node.invoke(Mock(InvocationContext)))
+ assert restored.is_complete()
+ state.complete(node.id, node.invoke(Mock(InvocationContext)))
+
+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[collect_exec_id].collection == [0, 1]
+
+
+def test_rehydrated_terminal_iterate_result_closes_existing_effect_stream():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=1, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ range_node, range_output = invoke_next(state)
+ assert range_node is not None
+ assert range_output is not None
+ iterate_node = state.next()
+ assert isinstance(iterate_node, IterateInvocation)
+ execution_ref = state.get_execution_ref(iterate_node.id)
+ recorder = ExecutionEffectsRecorder(
+ source_node_id=iterate_node.id,
+ frame_path=execution_ref.frame.iteration_path,
+ )
+ context = SimpleNamespace(
+ execution_effects=recorder,
+ effects=recorder,
+ execution=ExecutionInterface(recorder),
+ )
+ run_result = iterate_node.invoke_internal_with_effects(context, Mock())
+ assert len(run_result.effects) == 2
+
+ # Simulate an older snapshot that persisted the data effect but omitted its close effect.
+ state.apply(
+ state.get_execution_ref(iterate_node.id, effect_count=1),
+ run_result.output,
+ effects=[run_result.effects[0]],
+ )
+ restored = load_execution_state(dump_execution_state(state))
+ restored_streams = list(restored._generic_runtime().streams.values())
+ assert len(restored_streams) == 1
+ assert restored_streams[0].values == (0,)
+ assert restored_streams[0].closed
+ restored_collect = restored.next()
+ assert isinstance(restored_collect, CollectInvocation)
+ assert restored_collect.collection == [0]
+
+
@pytest.mark.parametrize("port", ["type", "output_meta", "loop_linkage"])
@pytest.mark.parametrize("effect_kind, token_kind", [("emit", "data"), ("close_stream", "stream_end")])
def test_graph_state_apply_rejects_reserved_effect_ports(port: str, effect_kind: str, token_kind: str):