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): extract graph runtime helper

JPPhoto8d1bacaf7e68
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 121b42e99f..fc1010bd80 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -447,6 +447,8 @@ Workflow-call note:
- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,
control-flow continuation scheduling, and the shared opaque activation-dependency projection for compatibility graphs.
- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.
+ Its implementation lives in the private `graph_execution_runtime.py` module; `graph.py` re-exports the runtime
+ class and its fan-in record types so existing imports and test seams remain stable.
- `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. Direct `CollectInvocation.item`
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 8fcb6f374d..82dbd938d0 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -5,7 +5,6 @@ import itertools
import json
import weakref # noqa: F401
from collections import deque
-from dataclasses import dataclass
from functools import wraps # noqa: F401
from typing import (
TYPE_CHECKING, # noqa: F401
@@ -48,10 +47,7 @@ from invokeai.app.invocations.baseinvocation import (
invocation, # noqa: F401
invocation_output, # noqa: F401
)
-from invokeai.app.invocations.call_saved_workflow import (
- CallSavedWorkflowInvocation,
- is_call_saved_workflow_dynamic_input,
-)
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.invocations.fields import Input, InputField, OutputField, OutputScope, UIType # noqa: F401
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.loops import (
@@ -85,6 +81,11 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionPlan,
ExecutionScheduler,
)
+from invokeai.app.services.shared.graph_execution_runtime import (
+ _BodyIterateCollectFanIn,
+ _DirectIterateCollectFanIn,
+ _ExecutionRuntime,
+)
from invokeai.app.services.shared.graph_if_activation import _IfActivationController
from invokeai.app.services.shared.graph_models import (
Edge, # noqa: F401
@@ -154,18 +155,6 @@ from invokeai.app.util.misc import uuid_string
_JSON_SERIALIZER = TypeAdapter(Any)
-@dataclass(frozen=True)
-class _DirectIterateCollectFanIn:
- branches: tuple[tuple[str, str], ...]
- collector_id: str
-
-
-@dataclass(frozen=True)
-class _BodyIterateCollectFanIn:
- branches: tuple[tuple[str, str, str], ...]
- collector_id: str
-
-
class _ExecutionMaterializer:
"""Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
@@ -2200,239 +2189,6 @@ class _GenericGraphSchedulerAdapter:
self._project_ready_nodes()
-class _ExecutionRuntime:
- """Provides runtime-only helpers such as iteration-path lookup and input hydration."""
-
- def __init__(self, state: "GraphExecutionState") -> None:
- self._state = state
-
- def _get_cached_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
- return self._state._prepared_registry().get_iteration_path(exec_node_id)
-
- def _get_iteration_source_node_id(self, exec_node_id: str) -> Optional[str]:
- if exec_node_id not in self._state.prepared_source_mapping:
- return None
- return self._state._prepared_registry().get_source_node_id(exec_node_id)
-
- def _get_ordered_iterator_sources(self, source_node_id: str) -> list[str]:
- iterator_graph = self._state._iterator_graph(self._state.graph.nx_graph())
- iterator_sources = [
- node_id
- for node_id in nx.ancestors(iterator_graph, source_node_id)
- if isinstance(self._state.graph.get_node(node_id), (ForInvocation, IterateInvocation))
- ]
-
- topo = list(nx.topological_sort(iterator_graph))
- topo_index = {node_id: i for i, node_id in enumerate(topo)}
- iterator_sources.sort(key=lambda node_id: topo_index.get(node_id, 0))
- return iterator_sources
-
- def _get_iterator_exec_id(
- self, iterator_source_id: str, exec_node_id: str, execution_graph: "nx.DiGraph"
- ) -> Optional[str]:
- prepared = self._state.source_prepared_mapping.get(iterator_source_id)
- if not prepared:
- return None
- return next((pid for pid in prepared if nx.has_path(execution_graph, pid, exec_node_id)), None)
-
- def _build_iteration_path(self, exec_node_id: str, source_node_id: str) -> tuple[int, ...]:
- iterator_sources = self._get_ordered_iterator_sources(source_node_id)
- execution_graph = self._state.execution_graph.nx_graph()
- path: list[int] = []
- for iterator_source_id in iterator_sources:
- iterator_exec_id = self._get_iterator_exec_id(iterator_source_id, exec_node_id, execution_graph)
- if iterator_exec_id is None:
- continue
- iterator_node = self._state.execution_graph.nodes.get(iterator_exec_id)
- if isinstance(iterator_node, (ForInvocation, IterateInvocation)):
- path.append(iterator_node.index)
-
- node_obj = self._state.execution_graph.nodes.get(exec_node_id)
- if isinstance(node_obj, (ForInvocation, IterateInvocation)):
- path.append(node_obj.index)
-
- return tuple(path)
-
- def _cache_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> tuple[int, ...]:
- self._state._prepared_registry().set_iteration_path(exec_node_id, iteration_path)
- return iteration_path
-
- def get_iteration_path(self, exec_node_id: str) -> tuple[int, ...]:
- """Best-effort outer->inner iteration indices for an execution node, stopping at collectors."""
- cached = self._get_cached_iteration_path(exec_node_id)
- if cached is not None:
- return cached
-
- source_node_id = self._get_iteration_source_node_id(exec_node_id)
- if source_node_id is None:
- return self._cache_iteration_path(exec_node_id, ())
-
- return self._cache_iteration_path(exec_node_id, self._build_iteration_path(exec_node_id, source_node_id))
-
- def _sort_collect_input_edges(self, input_edges: list[Edge], field_name: str) -> list[Edge]:
- matching_edges = [edge for edge in input_edges if edge.destination.field == field_name]
- fan_in = self._state._get_direct_iterate_collect_nodes()
- if isinstance(fan_in, _DirectIterateCollectFanIn):
- matching_edges.sort(
- key=lambda edge: (
- self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
- self.get_iteration_path(edge.source.node_id),
- )
- )
- elif isinstance(fan_in, _BodyIterateCollectFanIn):
- body_source_ids = {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches}
- matching_edges.sort(
- key=lambda edge: (
- body_source_ids.get(
- self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
- self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
- ),
- self.get_iteration_path(edge.source.node_id),
- )
- )
- else:
- matching_edges.sort(key=lambda edge: (self.get_iteration_path(edge.source.node_id), edge.source.node_id))
- return matching_edges
-
- def _get_copied_result_value(self, edge: Edge) -> Any:
- return copydeep(getattr(self._state.results[edge.source.node_id], edge.source.field))
-
- def _try_get_copied_result_value(self, edge: Edge) -> tuple[bool, Any]:
- source_output = self._state.results.get(edge.source.node_id)
- if source_output is None:
- return False, None
- return True, copydeep(getattr(source_output, edge.source.field))
-
- def _build_collect_collection(self, input_edges: list[Edge]) -> list[Any]:
- item_edges = self._sort_collect_input_edges(input_edges, ITEM_FIELD)
- collection_edges = self._sort_collect_input_edges(input_edges, COLLECTION_FIELD)
-
- output_collection = []
- for edge in collection_edges:
- source_value = self._get_copied_result_value(edge)
- if isinstance(source_value, list):
- output_collection.extend(source_value)
- else:
- output_collection.append(source_value)
- fan_in = self._state._get_direct_iterate_collect_nodes()
- stable_direct_fan_in = isinstance(fan_in, _DirectIterateCollectFanIn)
- stable_body_fan_in = isinstance(fan_in, _BodyIterateCollectFanIn)
- body_source_ids = (
- {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches} if stable_body_fan_in else {}
- )
- item_values: list[tuple[Any, ...]] = []
- consumed_streams: set[str] = set()
- for edge in item_edges:
- source_node_id = self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id)
- item_source_id = (
- source_node_id
- if stable_direct_fan_in
- else body_source_ids.get(source_node_id, "")
- if stable_body_fan_in
- else ""
- )
- item_exec_id = "" if stable_direct_fan_in or stable_body_fan_in else edge.source.node_id
- stream_info = self._state._stream_for_iterate_edge(edge)
- if stream_info is None:
- item_values.append(
- (
- item_source_id,
- (*self.get_iteration_path(edge.source.node_id), 0),
- item_exec_id,
- self._get_copied_result_value(edge),
- )
- )
- continue
- stream_id, parent_path = stream_info
- stream = self._state._generic_runtime().streams.get(stream_id)
- if stream is None:
- item_values.append(
- (
- item_source_id,
- (*self.get_iteration_path(edge.source.node_id), 0),
- item_exec_id,
- self._get_copied_result_value(edge),
- )
- )
- 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)
- item_values.extend(
- (item_source_id, (*parent_path, sequence), item_exec_id, copydeep(value))
- for sequence, value in enumerate(stream.values)
- )
- if stable_direct_fan_in or stable_body_fan_in:
- item_values.sort(key=lambda item: (item[0], item[1]))
- else:
- item_values.sort(key=lambda item: (item[1], item[2]))
- output_collection.extend(value for _source_id, _path, _exec_id, value in item_values)
- return output_collection
-
- def _set_node_inputs(
- self, node: BaseInvocation, input_edges: list[Edge], allowed_fields: Optional[set[str]] = None
- ) -> None:
- for edge in input_edges:
- if allowed_fields is not None and edge.destination.field not in allowed_fields:
- continue
- if isinstance(node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(
- edge.destination.field
- ):
- continue
- setattr(node, edge.destination.field, self._get_copied_result_value(edge))
-
- def _prepare_collect_inputs(self, node: "CollectInvocation", input_edges: list[Edge]) -> None:
- node.collection = self._build_collect_collection(input_edges)
-
- def _prepare_iterate_inputs(self, node: "IterateInvocation", input_edges: list[Edge]) -> None:
- for edge in input_edges:
- if edge.destination.field != COLLECTION_FIELD:
- continue
- source_output = self._state.results[edge.source.node_id]
- object.__setattr__(node, COLLECTION_FIELD, getattr(source_output, edge.source.field))
- return
-
- def _prepare_if_inputs(self, node: IfInvocation, input_edges: list[Edge]) -> None:
- selected_field = self._state._resolved_if_exec_branches.get(node.id)
- allowed_fields = {"condition", selected_field} if selected_field is not None else {"condition"}
-
- for edge in input_edges:
- if edge.destination.field not in allowed_fields:
- continue
-
- found_value, copied_value = self._try_get_copied_result_value(edge)
- if not found_value:
- iteration_path = self._state._get_iteration_path(node.id)
- raise RuntimeError(
- "IfInvocation selected input edge points at an exec node with no stored result output: "
- f"if_exec_id={node.id}, source_exec_id={edge.source.node_id}, iteration_path={iteration_path}"
- )
-
- setattr(node, edge.destination.field, copied_value)
-
- def _prepare_default_inputs(self, node: BaseInvocation, input_edges: list[Edge]) -> None:
- self._set_node_inputs(node, input_edges)
-
- def prepare_inputs(self, node: BaseInvocation) -> None:
- input_edges = self._state.execution_graph._get_input_edges(node.id)
-
- if isinstance(node, IterateInvocation):
- self._prepare_iterate_inputs(node, input_edges)
- return
-
- if isinstance(node, CollectInvocation):
- self._prepare_collect_inputs(node, input_edges)
- return
-
- if isinstance(node, IfInvocation):
- self._prepare_if_inputs(node, input_edges)
- return
-
- self._prepare_default_inputs(node, input_edges)
-
-
class GraphExecutionState(BaseModel):
"""Tracks source-graph expansion, execution progress, and runtime results."""
diff --git a/invokeai/app/services/shared/graph_execution_runtime.py b/invokeai/app/services/shared/graph_execution_runtime.py
new file mode 100644
index 0000000000..ec7a6fdbca
--- /dev/null
+++ b/invokeai/app/services/shared/graph_execution_runtime.py
@@ -0,0 +1,269 @@
+"""Runtime-only helpers for graph execution state."""
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Optional
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.call_saved_workflow import (
+ CallSavedWorkflowInvocation,
+ is_call_saved_workflow_dynamic_input,
+)
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.services.shared.graph_models import Edge
+from invokeai.app.services.shared.graph_validation import (
+ COLLECTION_FIELD,
+ ITEM_FIELD,
+ CollectInvocation,
+ ForInvocation,
+ IterateInvocation,
+ copydeep,
+ nx,
+)
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+@dataclass(frozen=True)
+class _DirectIterateCollectFanIn:
+ branches: tuple[tuple[str, str], ...]
+ collector_id: str
+
+
+@dataclass(frozen=True)
+class _BodyIterateCollectFanIn:
+ branches: tuple[tuple[str, str, str], ...]
+ collector_id: str
+
+
+class _ExecutionRuntime:
+ """Provides runtime-only helpers such as iteration-path lookup and input hydration."""
+
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+
+ def _get_cached_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
+ return self._state._prepared_registry().get_iteration_path(exec_node_id)
+
+ def _get_iteration_source_node_id(self, exec_node_id: str) -> Optional[str]:
+ if exec_node_id not in self._state.prepared_source_mapping:
+ return None
+ return self._state._prepared_registry().get_source_node_id(exec_node_id)
+
+ def _get_ordered_iterator_sources(self, source_node_id: str) -> list[str]:
+ iterator_graph = self._state._iterator_graph(self._state.graph.nx_graph())
+ iterator_sources = [
+ node_id
+ for node_id in nx.ancestors(iterator_graph, source_node_id)
+ if isinstance(self._state.graph.get_node(node_id), (ForInvocation, IterateInvocation))
+ ]
+
+ topo = list(nx.topological_sort(iterator_graph))
+ topo_index = {node_id: i for i, node_id in enumerate(topo)}
+ iterator_sources.sort(key=lambda node_id: topo_index.get(node_id, 0))
+ return iterator_sources
+
+ def _get_iterator_exec_id(
+ self, iterator_source_id: str, exec_node_id: str, execution_graph: "nx.DiGraph"
+ ) -> Optional[str]:
+ prepared = self._state.source_prepared_mapping.get(iterator_source_id)
+ if not prepared:
+ return None
+ return next((pid for pid in prepared if nx.has_path(execution_graph, pid, exec_node_id)), None)
+
+ def _build_iteration_path(self, exec_node_id: str, source_node_id: str) -> tuple[int, ...]:
+ iterator_sources = self._get_ordered_iterator_sources(source_node_id)
+ execution_graph = self._state.execution_graph.nx_graph()
+ path: list[int] = []
+ for iterator_source_id in iterator_sources:
+ iterator_exec_id = self._get_iterator_exec_id(iterator_source_id, exec_node_id, execution_graph)
+ if iterator_exec_id is None:
+ continue
+ iterator_node = self._state.execution_graph.nodes.get(iterator_exec_id)
+ if isinstance(iterator_node, (ForInvocation, IterateInvocation)):
+ path.append(iterator_node.index)
+
+ node_obj = self._state.execution_graph.nodes.get(exec_node_id)
+ if isinstance(node_obj, (ForInvocation, IterateInvocation)):
+ path.append(node_obj.index)
+
+ return tuple(path)
+
+ def _cache_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> tuple[int, ...]:
+ self._state._prepared_registry().set_iteration_path(exec_node_id, iteration_path)
+ return iteration_path
+
+ def get_iteration_path(self, exec_node_id: str) -> tuple[int, ...]:
+ """Best-effort outer->inner iteration indices for an execution node, stopping at collectors."""
+ cached = self._get_cached_iteration_path(exec_node_id)
+ if cached is not None:
+ return cached
+
+ source_node_id = self._get_iteration_source_node_id(exec_node_id)
+ if source_node_id is None:
+ return self._cache_iteration_path(exec_node_id, ())
+
+ return self._cache_iteration_path(exec_node_id, self._build_iteration_path(exec_node_id, source_node_id))
+
+ def _sort_collect_input_edges(self, input_edges: list[Edge], field_name: str) -> list[Edge]:
+ matching_edges = [edge for edge in input_edges if edge.destination.field == field_name]
+ fan_in = self._state._get_direct_iterate_collect_nodes()
+ if isinstance(fan_in, _DirectIterateCollectFanIn):
+ matching_edges.sort(
+ key=lambda edge: (
+ self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
+ self.get_iteration_path(edge.source.node_id),
+ )
+ )
+ elif isinstance(fan_in, _BodyIterateCollectFanIn):
+ body_source_ids = {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches}
+ matching_edges.sort(
+ key=lambda edge: (
+ body_source_ids.get(
+ self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
+ self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
+ ),
+ self.get_iteration_path(edge.source.node_id),
+ )
+ )
+ else:
+ matching_edges.sort(key=lambda edge: (self.get_iteration_path(edge.source.node_id), edge.source.node_id))
+ return matching_edges
+
+ def _get_copied_result_value(self, edge: Edge) -> Any:
+ return copydeep(getattr(self._state.results[edge.source.node_id], edge.source.field))
+
+ def _try_get_copied_result_value(self, edge: Edge) -> tuple[bool, Any]:
+ source_output = self._state.results.get(edge.source.node_id)
+ if source_output is None:
+ return False, None
+ return True, copydeep(getattr(source_output, edge.source.field))
+
+ def _build_collect_collection(self, input_edges: list[Edge]) -> list[Any]:
+ item_edges = self._sort_collect_input_edges(input_edges, ITEM_FIELD)
+ collection_edges = self._sort_collect_input_edges(input_edges, COLLECTION_FIELD)
+
+ output_collection = []
+ for edge in collection_edges:
+ source_value = self._get_copied_result_value(edge)
+ if isinstance(source_value, list):
+ output_collection.extend(source_value)
+ else:
+ output_collection.append(source_value)
+ fan_in = self._state._get_direct_iterate_collect_nodes()
+ stable_direct_fan_in = isinstance(fan_in, _DirectIterateCollectFanIn)
+ stable_body_fan_in = isinstance(fan_in, _BodyIterateCollectFanIn)
+ body_source_ids = (
+ {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches} if stable_body_fan_in else {}
+ )
+ item_values: list[tuple[Any, ...]] = []
+ consumed_streams: set[str] = set()
+ for edge in item_edges:
+ source_node_id = self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id)
+ item_source_id = (
+ source_node_id
+ if stable_direct_fan_in
+ else body_source_ids.get(source_node_id, "")
+ if stable_body_fan_in
+ else ""
+ )
+ item_exec_id = "" if stable_direct_fan_in or stable_body_fan_in else edge.source.node_id
+ stream_info = self._state._stream_for_iterate_edge(edge)
+ if stream_info is None:
+ item_values.append(
+ (
+ item_source_id,
+ (*self.get_iteration_path(edge.source.node_id), 0),
+ item_exec_id,
+ self._get_copied_result_value(edge),
+ )
+ )
+ continue
+ stream_id, parent_path = stream_info
+ stream = self._state._generic_runtime().streams.get(stream_id)
+ if stream is None:
+ item_values.append(
+ (
+ item_source_id,
+ (*self.get_iteration_path(edge.source.node_id), 0),
+ item_exec_id,
+ self._get_copied_result_value(edge),
+ )
+ )
+ 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)
+ item_values.extend(
+ (item_source_id, (*parent_path, sequence), item_exec_id, copydeep(value))
+ for sequence, value in enumerate(stream.values)
+ )
+ if stable_direct_fan_in or stable_body_fan_in:
+ item_values.sort(key=lambda item: (item[0], item[1]))
+ else:
+ item_values.sort(key=lambda item: (item[1], item[2]))
+ output_collection.extend(value for _source_id, _path, _exec_id, value in item_values)
+ return output_collection
+
+ def _set_node_inputs(
+ self, node: BaseInvocation, input_edges: list[Edge], allowed_fields: Optional[set[str]] = None
+ ) -> None:
+ for edge in input_edges:
+ if allowed_fields is not None and edge.destination.field not in allowed_fields:
+ continue
+ if isinstance(node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(
+ edge.destination.field
+ ):
+ continue
+ setattr(node, edge.destination.field, self._get_copied_result_value(edge))
+
+ def _prepare_collect_inputs(self, node: "CollectInvocation", input_edges: list[Edge]) -> None:
+ node.collection = self._build_collect_collection(input_edges)
+
+ def _prepare_iterate_inputs(self, node: "IterateInvocation", input_edges: list[Edge]) -> None:
+ for edge in input_edges:
+ if edge.destination.field != COLLECTION_FIELD:
+ continue
+ source_output = self._state.results[edge.source.node_id]
+ object.__setattr__(node, COLLECTION_FIELD, getattr(source_output, edge.source.field))
+ return
+
+ def _prepare_if_inputs(self, node: IfInvocation, input_edges: list[Edge]) -> None:
+ selected_field = self._state._resolved_if_exec_branches.get(node.id)
+ allowed_fields = {"condition", selected_field} if selected_field is not None else {"condition"}
+
+ for edge in input_edges:
+ if edge.destination.field not in allowed_fields:
+ continue
+
+ found_value, copied_value = self._try_get_copied_result_value(edge)
+ if not found_value:
+ iteration_path = self._state._get_iteration_path(node.id)
+ raise RuntimeError(
+ "IfInvocation selected input edge points at an exec node with no stored result output: "
+ f"if_exec_id={node.id}, source_exec_id={edge.source.node_id}, iteration_path={iteration_path}"
+ )
+
+ setattr(node, edge.destination.field, copied_value)
+
+ def _prepare_default_inputs(self, node: BaseInvocation, input_edges: list[Edge]) -> None:
+ self._set_node_inputs(node, input_edges)
+
+ def prepare_inputs(self, node: BaseInvocation) -> None:
+ input_edges = self._state.execution_graph._get_input_edges(node.id)
+
+ if isinstance(node, IterateInvocation):
+ self._prepare_iterate_inputs(node, input_edges)
+ return
+
+ if isinstance(node, CollectInvocation):
+ self._prepare_collect_inputs(node, input_edges)
+ return
+
+ if isinstance(node, IfInvocation):
+ self._prepare_if_inputs(node, input_edges)
+ return
+
+ self._prepare_default_inputs(node, input_edges)
diff --git a/tests/app/services/shared/test_graph_execution_runtime.py b/tests/app/services/shared/test_graph_execution_runtime.py
new file mode 100644
index 0000000000..d5b0ee11fd
--- /dev/null
+++ b/tests/app/services/shared/test_graph_execution_runtime.py
@@ -0,0 +1,58 @@
+import subprocess
+import sys
+import textwrap
+
+from invokeai.app.services.shared import graph as graph_facade
+from invokeai.app.services.shared import graph_execution_runtime
+
+
+def test_runtime_module_imports_without_graph_cycle() -> None:
+ script = textwrap.dedent(
+ """
+ import sys
+
+ from invokeai.app.services.shared import graph_execution_runtime
+
+ assert graph_execution_runtime._ExecutionRuntime
+ assert "invokeai.app.services.shared.graph" not in sys.modules
+ """
+ )
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False)
+ assert result.returncode == 0, result.stderr
+
+
+def test_graph_facade_reexports_runtime_aliases() -> None:
+ assert graph_facade._ExecutionRuntime is graph_execution_runtime._ExecutionRuntime
+ assert graph_facade._DirectIterateCollectFanIn is graph_execution_runtime._DirectIterateCollectFanIn
+ assert graph_facade._BodyIterateCollectFanIn is graph_execution_runtime._BodyIterateCollectFanIn
+
+
+def test_graph_execution_state_runtime_seam_uses_extracted_runtime() -> None:
+ state = graph_facade.GraphExecutionState(graph=graph_facade.Graph())
+
+ runtime = state._runtime()
+
+ assert type(runtime) is graph_execution_runtime._ExecutionRuntime
+ assert state._runtime() is runtime
+
+
+def test_graph_execution_state_delegates_runtime_helpers(monkeypatch) -> None:
+ state = graph_facade.GraphExecutionState(graph=graph_facade.Graph())
+ calls: list[tuple[str, object]] = []
+
+ class StubRuntime:
+ def get_iteration_path(self, exec_node_id: str) -> tuple[int, ...]:
+ calls.append(("get_iteration_path", exec_node_id))
+ return (3,)
+
+ def prepare_inputs(self, node: object) -> None:
+ calls.append(("prepare_inputs", node))
+
+ runtime = StubRuntime()
+ monkeypatch.setattr(state, "_runtime", lambda: runtime)
+ node = object()
+
+ assert state._get_iteration_path("exec-node") == (3,)
+ state._prepare_inputs(node)
+
+ assert calls == [("get_iteration_path", "exec-node"), ("prepare_inputs", node)]