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
refactor(execution): record Iterate stream effects
JPPhoto8444d33d53a1
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 8e5ac41135..5db0567d68 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -128,8 +128,10 @@ Holds the state for a single run. Keeps the source graph intact and materializes`GraphExecutionState` is still the public runtime entry point, but most execution behavior is now delegated to a smallset of internal helper classes. For ordinary static DAGs and legacy-shaped `If` graphs, readiness and completion areprojected through the generic `ExecutionPlan`/`ExecutionScheduler` adapter. `Iterate`, `Collect`, `For`, `ForReturn`,-and saved-workflow call lowering continue to use the legacy compatibility scheduler until their differential coverage-is complete.+and saved-workflow call lowering continue to use the legacy compatibility scheduler for materialization and queue+lifecycle until their differential coverage is complete. `Iterate` also records non-empty item streams through the+generic effect ledger; the materializer remains authoritative for expansion, iteration paths, collector grouping, and+empty-source compatibility handling.The source graph is treated as stable during normal execution, but the runtime object still exposes guarded graphmutation helpers. Those helpers reject changes once the affected nodes have already been prepared or executed.@@ -207,9 +209,14 @@ discard. It does not call `_IfBranchScheduler._prune_unselected_if_inputs`,`_IfBranchScheduler.mark_exec_node_skipped`, or delete execution edges. The forced compatibility `_ExecutionScheduler`path still uses `_IfBranchScheduler` for legacy branch topology, input-edge pruning, and skip behavior. `apply()`validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.-Activation effects are excluded from data-stream handling. This is not yet the token-authoritative downstream topology-migration: no author-time activation ports or literal successor IDs are introduced, and other control-flow invocations-remain on their legacy paths until differential coverage proves each replacement.+Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing+control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration+index, and the final copy emits one `close_stream` effect. Graph state maps these effects to the existing+frame-scoped iteration-stream identity, so legacy output mirroring is idempotent. The materializer still creates+prepared copies, derives iteration paths, groups collector inputs, and records the explicit close for an empty source.+This is not yet token-authoritative downstream topology or full `Collect` migration: no author-time activation ports or+literal successor IDs are introduced, and the remaining control-flow invocations stay on compatibility paths until+differential coverage proves each replacement.`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token@@ -229,9 +236,10 @@ Target migration contract: control-flow nodes remain concrete invocationsubclasses that declare frame-scoped data, activation, stream-closure, child,and terminal effects. The generic scheduler selects nodes from requiredeffects for the current frame; it never receives a literal successor-node ID.-Current implementation is narrower: `IfInvocation` is the only control-flow-invocation using the effect recorder, while `Iterate`, `Collect`, `For`,-`ForReturn`, and workflow-call invocations remain on compatibility paths. For+Current implementation is narrower: `IfInvocation` and non-empty+`IterateInvocation` use the effect recorder for activation and stream effects,+while `Collect`, `For`, `ForReturn`, and workflow-call invocations remain on+compatibility paths. For`If`, generic readiness consumes opaque frame-local plan dependencies and requiresboth matching private `ActivationGate` runtime state and a persisted activation token;generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility@@ -319,15 +327,18 @@ Workflow-call note:only by forced compatibility `_ExecutionScheduler`; generic legacy-shaped `If` scheduling compiles opaque dependenciesand retires unselected prepared nodes through generic scheduler discard. The opaque scheduler has no `If`-specificbranch.-- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters.+- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters. The+ canonical stream for a prepared `IterateInvocation` is keyed by the source iterator and its parent iteration path;+ its item/close effects and legacy output mirroring update the same idempotent buffer.`GraphExecutionState.model_post_init()` rehydrates private runtime helpers and caches after normal construction or aJSON/model round trip. Rehydration reconstructs prepared exec metadata, cached iteration paths, private resolved `If`-gate state from condition results or persisted activation tokens, closed iteration streams from durable Iterate results-or completed empty-source state, For continuation identity, and ready queues from `execution_graph`, `indegree`,-`executed`, and `results`. Activation tokens persist; private `ActivationGate` runtime state does not and is-reconstructed from condition results or persisted activation tokens. Before token validation, missing legacy iteration-path-metadata is rebuilt from the prepared execution graph. Persisted activation identity is then validated fail-closed+gate state from condition results or persisted activation tokens, non-empty iteration streams from durable effects and+legacy Iterate results, explicit empty-source closes, For continuation identity, and ready queues from+`execution_graph`, `indegree`, `executed`, and `results`. Activation tokens persist; private `ActivationGate` runtime+state does not and is reconstructed from condition results or persisted activation tokens. Before token validation,+missing legacy iteration-path metadata is rebuilt from the prepared execution graph. Persisted activation identity is+then validated fail-closedagainst prepared owners, derived references, declared activation fields, canonical ids, and known frame fields; extraframe metadata is retained. Persisted execution references, tokens, and effects remain part of serialized state; privatehelper objects do not. Queue snapshots carry an additive execution-state version marker and use version-aware loader;@@ -451,6 +462,11 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac- Applied execution references are unique to one prepared node and frame; their output/effect records are JSON-safe.- Output and `emit` effects produce frame-aware tokens. `close_stream` produces a `stream_end` token. Association fieldssuch as `loop_linkage` are never stored as data tokens.+- A non-empty `IterateInvocation` emits one `item` effect per prepared copy,+ with a contiguous sequence beginning at zero, and closes its canonical+ source/parent-path stream on the final copy. Exact output mirroring is+ idempotent; empty-source closure remains a materializer compatibility+ operation.- Collectors aggregate `item` inputs and may also merge incoming `collection` inputs during runtime hydration.Collectors nested under iterators preserve enclosing iteration paths, so downstream consumers materialize per enclosingiteration instead of receiving a mixed collection from unrelated outer iterations.diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex e5e529e073..81173a2e80 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -2905,6 +2905,8 @@ class IterateInvocationOutput(BaseInvocationOutput):class IterateInvocation(BaseInvocation):"""Iterates over a list of items"""+ execution_effects_enabled = True+collection: list[Any] = InputField(description="The list of items to iterate over", default=[], ui_type=UIType._Collection)@@ -2912,7 +2914,13 @@ class IterateInvocation(BaseInvocation):def invoke(self, context: InvocationContext) -> IterateInvocationOutput:"""Produces the outputs as values"""- return IterateInvocationOutput(item=self.collection[self.index], index=self.index, total=len(self.collection))+ item = self.collection[self.index]+ execution = getattr(context, "execution", None)+ if execution is not None:+ execution.emit("item", item, sequence=self.index)+ if self.index + 1 >= len(self.collection):+ execution.close_stream("item")+ return IterateInvocationOutput(item=item, index=self.index, total=len(self.collection))def get_event_invocation(self) -> "IterateInvocation":event_invocation = self.model_copy()@@ -4884,20 +4892,26 @@ class GraphExecutionState(BaseModel):if self._value_from_object(token, "token_kind") == "activation":continuestream_id = f"{self.id}:effect:{execution_ref.reference_id}:{port}"+ stream_owner_id = execution_ref.exec_node_id+ stream_frame = EngineExecutionFrame(+ state_id=execution_ref.frame.state_id or self.id,+ frame_id=execution_ref.frame.frame_id or f"{self.id}:{execution_ref.exec_node_id}",+ iteration_path=execution_ref.frame.iteration_path,+ workflow_call_depth=execution_ref.frame.workflow_call_depth,+ )+ source_node = self.execution_graph.nodes.get(execution_ref.exec_node_id)+ source_node_id = self.prepared_source_mapping.get(execution_ref.exec_node_id)+ if isinstance(source_node, IterateInvocation) and port == ITEM_FIELD and source_node_id is not None:+ iteration_path = self._get_iteration_path(execution_ref.exec_node_id)+ parent_path = iteration_path[:-1] if iteration_path else ()+ stream_id = self._iteration_stream_id(source_node_id, parent_path)+ stream_owner_id = source_node_id+ stream_frame = self._engine_frame(parent_path)runtime = self._generic_runtime()stream = runtime.streams.get(stream_id)if stream is None:self._tx_record(lambda runtime=runtime, stream_id=stream_id: runtime.remove_stream(stream_id))- stream = runtime.get_or_create_stream(- stream_id,- execution_ref.exec_node_id,- EngineExecutionFrame(- state_id=execution_ref.frame.state_id or self.id,- frame_id=execution_ref.frame.frame_id or f"{self.id}:{execution_ref.exec_node_id}",- iteration_path=execution_ref.frame.iteration_path,- workflow_call_depth=execution_ref.frame.workflow_call_depth,- ),- )+ stream = runtime.get_or_create_stream(stream_id, stream_owner_id, stream_frame)elif self._apply_transaction is not None:previous = StreamBuffer[Any].model_validate(stream.model_dump(mode="python"))self._tx_record_once(@@ -4909,6 +4923,10 @@ class GraphExecutionState(BaseModel):if sequence is None:sequence = stream.next_sequenceif effect_kind == "close_stream":+ if stream.closed:+ if stream.end_sequence == sequence:+ continue+ raise ValueError("conflicting close sequence for stream")stream.close(sequence=sequence)continueif self._value_from_object(token, "token_kind") == "stream_end":diff --git a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py b/tests/app/services/session_processor/test_for_loop_processor_sqlite.pyindex 77ff58ffd9..bfad1686c4 100644--- a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py+++ b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py@@ -2,6 +2,7 @@ import asyncioimport uuidfrom contextlib import contextmanagerfrom threading import Condition, Event+from types import SimpleNamespacefrom typing import Any, Iteratorimport pytest@@ -18,6 +19,7 @@ from invokeai.app.services.session_processor.session_processor_default import (DefaultSessionRunner,)from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue+from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder, ExecutionInterfacefrom invokeai.app.services.shared.graph import CollectInvocation, Graph, GraphExecutionState, IterateInvocationfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom tests.test_nodes import create_edge, create_loop_linkage@@ -168,6 +170,18 @@ def _insert_session(queue: SqliteSessionQueue, graph: Graph) -> int:return cursor.lastrowid # type: ignore[return-value]+def _build_test_invocation_context(data, services, is_canceled):+ recorder = ExecutionEffectsRecorder(+ source_node_id=data.invocation.id,+ frame_path=data.execution_frame,+ )+ return SimpleNamespace(+ execution_effects=recorder,+ effects=recorder,+ execution=ExecutionInterface(recorder),+ )++class _Stats:@contextmanagerdef collect_stats(self, invocation, graph_execution_state_id):@@ -189,7 +203,7 @@ def test_processor_sqlite_queue_nested_iterate_for_cleanup() -> None:monkeypatch.setattr("invokeai.app.services.session_processor.session_processor_default.build_invocation_context",- lambda data, services, is_canceled: None,+ _build_test_invocation_context,)queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)@@ -273,7 +287,7 @@ def test_processor_sqlite_queue_nested_for_cleanup() -> None:monkeypatch.setattr("invokeai.app.services.session_processor.session_processor_default.build_invocation_context",- lambda data, services, is_canceled: None,+ _build_test_invocation_context,)queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pyindex a31f0340c0..6a4a3de947 100644--- a/tests/app/services/shared/test_execution_effects.py+++ b/tests/app/services/shared/test_execution_effects.py@@ -30,7 +30,7 @@ from invokeai.app.services.shared.execution_effects import ()from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapabilityfrom invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state-from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState, IterateInvocationfrom invokeai.app.services.shared.invocation_context import (InvocationContext,InvocationContextData,@@ -134,25 +134,42 @@ def test_if_invocation_declares_selected_branch_activation_effect(condition: booassert effect.token.token_kind == "activation"+ ("index", "expected_effect_kinds"),+ [(0, ["emit"]), (1, ["emit", "close_stream"])],+)+def test_iterate_invocation_declares_ordered_item_stream_effects(index: int, expected_effect_kinds: list[str]) -> None:+ context = _context()+ context.execution_effects = ExecutionEffectsRecorder(source_node_id="iterate")+ context.execution = ExecutionInterface(context.execution_effects)+ invocation = IterateInvocation(id="iterate", collection=["first", "last"], index=index)++ result = invocation.invoke_internal_with_effects(context, _services())++ assert result.output.item == invocation.collection[index]+ assert result.output.index == index+ assert result.output.total == len(invocation.collection)+ assert [effect.kind for effect in result.effects] == expected_effect_kinds+ emit = result.effects[0]+ assert isinstance(emit, EmitEffect)+ assert emit.token.node_id == "iterate"+ assert emit.token.field == "item"+ assert emit.token.value == invocation.collection[index]+ assert emit.token.sequence == index+ assert emit.value == invocation.collection[index]+ if index == 1:+ close = result.effects[1]+ assert isinstance(close, CloseStreamEffect)+ assert close.token.node_id == "iterate"+ assert close.token.field == "item"+ assert close.token.token_kind == "stream_end"++@pytest.mark.parametrize("condition", [True, False])def test_graph_state_applies_if_activation_and_releases_selected_branch(condition: bool) -> None:graph = Graph()- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(ExecutionEffectsTestInvocation(id="true_branch", value=1))- graph.add_node(ExecutionEffectsTestInvocation(id="false_branch", value=2))+ graph.add_node(IfInvocation(id="if", condition=condition, true_input=1, false_input=2))graph.add_node(ExecutionEffectsTestInvocation(id="successor"))- graph.add_edge(- Edge(- source=EdgeConnection(node_id="true_branch", field="value"),- destination=EdgeConnection(node_id="if", field="true_input"),- )- )- graph.add_edge(- Edge(- source=EdgeConnection(node_id="false_branch", field="value"),- destination=EdgeConnection(node_id="if", field="false_input"),- )- )graph.add_edge(Edge(source=EdgeConnection(node_id="if", field="value"),@@ -180,10 +197,7 @@ def test_graph_state_applies_if_activation_and_releases_selected_branch(conditioelse:state.complete(invocation.id, invocation.invoke(context=MagicMock()))- selected_branch = "true_branch" if condition else "false_branch"- unselected_branch = "false_branch" if condition else "true_branch"- assert selected_branch in executed_source_ids- assert unselected_branch not in executed_source_ids+ assert executed_source_ids == ["if", "successor"]assert "successor" in executed_source_idsactivation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]assert len(activation_tokens) == 1diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 7767114319..069ea87740 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -414,6 +414,7 @@ def test_graph_state_apply_records_generic_effect_stream_and_rehydrates_it():},],)+ state._record_effect_streams(ref, state.execution_effects[ref.reference_id])streams = list(state._generic_runtime().streams.values())assert len(streams) == 1@@ -427,6 +428,42 @@ def test_graph_state_apply_records_generic_effect_stream_and_rehydrates_it():assert restored_streams[0].values == (3,)+def test_graph_state_maps_iterate_effects_to_the_canonical_iteration_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)++ streams = list(state._generic_runtime().streams.values())+ assert len(streams) == 1+ assert streams[0].owner_id == "iterate"+ assert ":effect:" not in streams[0].stream_id+ assert streams[0].values == (0,)+ assert not streams[0].closed++@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):