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 materialization and iterate planners

JPPhoto4641fcf68086
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 8e0fde63eb..f61f136c5b 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -433,6 +433,10 @@ Workflow-call note:
ready work. It owns iterator expansion, collector grouping, prepared-parent selection, and creation of execution-graph
edges. When matching prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannot
be selected as live inputs.
+ The class lives in `graph_materializer.py` and is re-exported by `graph.py`.
+- Private `graph_iterate_planner.py` expands the supported direct and body-mediated Iterate/Collect shapes.
+ Graph-state method wrappers preserve the admission, copy creation, edge attachment, and atomic preparation entry
+ points. The planner continues to use the graph state's journal, mappings, caches, and scheduler.
- `_IfActivationController` Owns fallback runtime `If` admission and compiles opaque, frame-local activation dependency
records for unsupported fresh shapes and legacy prepared nodes. Fresh ordinary-node single-`If` graphs compile those
dependencies in graph state. Fresh admission leaves rejected branch sources unprepared; legacy skipped-state
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index d1c9bfc378..0514ef6b89 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -1,7 +1,6 @@
# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
import copy # noqa: F401
-import itertools
import json
import weakref # noqa: F401
from collections import deque
@@ -87,6 +86,21 @@ from invokeai.app.services.shared.graph_execution_runtime import (
_ExecutionRuntime,
)
from invokeai.app.services.shared.graph_if_activation import _IfActivationController
+from invokeai.app.services.shared.graph_iterate_planner import (
+ _attach_direct_execution_edges,
+ _can_use_direct_iterate_collect_planner,
+ _create_direct_execution_node_copy,
+ _get_body_iterate_collect_fan_in,
+ _get_direct_iterate_collect_fan_in,
+ _get_direct_iterate_collect_nodes,
+ _initialize_direct_execution_node,
+ _mark_direct_source_empty,
+ _prepare_body_iterate_collect_fan_in_unchecked,
+ _prepare_direct_iterate_collect,
+ _prepare_direct_iterate_collect_fan_in_unchecked,
+ _prepare_direct_iterate_collect_unchecked,
+)
+from invokeai.app.services.shared.graph_materializer import _ExecutionMaterializer
from invokeai.app.services.shared.graph_models import (
Edge, # noqa: F401
EdgeConnection, # noqa: F401
@@ -141,7 +155,7 @@ from invokeai.app.services.shared.graph_validation import (
copydeep,
extract_collection_item_types, # noqa: F401
get_input_field_type, # noqa: F401
- get_output_field_scope,
+ get_output_field_scope, # noqa: F401
get_output_field_type, # noqa: F401
is_any, # noqa: F401
is_list_or_contains_list, # noqa: F401
@@ -155,1451 +169,6 @@ from invokeai.app.util.misc import uuid_string
_JSON_SERIALIZER = TypeAdapter(Any)
-class _ExecutionMaterializer:
- """Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
-
- `GraphExecutionState.next()` calls into this helper when no prepared exec node is ready. The materializer chooses
- the next source node that can be expanded, creates the corresponding exec nodes in the execution graph, wires their
- inputs, and initializes their scheduler state.
- """
-
- def __init__(self, state: "GraphExecutionState") -> None:
- self._state = state
- self._iteration_axes_by_source: dict[str, tuple[str, ...]] = {}
-
- def _get_iteration_axes(self, source_node_id: str) -> tuple[str, ...]:
- cached = self._iteration_axes_by_source.get(source_node_id)
- if cached is not None:
- return cached
-
- axes = self._state._runtime()._get_ordered_iterator_sources(source_node_id)
- if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
- axes.append(source_node_id)
- result = tuple(axes)
- self._iteration_axes_by_source[source_node_id] = result
- return result
-
- def _get_known_iteration_path(
- self,
- iteration_index: int,
- iteration_node_map: list[tuple[str, str]],
- ) -> Optional[tuple[int, ...]]:
- parent_paths: list[tuple[int, ...]] = []
- parent_iteration_axes: list[tuple[str, ...]] = []
- registry = self._state._prepared_registry()
- for source_node_id, prepared_id in iteration_node_map:
- parent_path = registry.get_iteration_path(prepared_id)
- if parent_path is None:
- return None
- if parent_path:
- parent_paths.append(parent_path)
- parent_iteration_axes.append(self._get_iteration_axes(source_node_id))
-
- unique_parent_paths = set(parent_paths)
- paths_share_iteration_axes = len(set(parent_iteration_axes)) <= 1
-
- # Materialized iteration boundaries use non-negative indexes; ordinary execution nodes use -1. Keeping this
- # generic allows other scheduler-managed loop nodes to reuse the same path cache.
- if iteration_index >= 0:
- if len(unique_parent_paths) > 1 or not paths_share_iteration_axes:
- return None
- parent_path = next(iter(unique_parent_paths), ())
- return (*parent_path, iteration_index)
-
- if not unique_parent_paths:
- return ()
- if len(unique_parent_paths) == 1 and paths_share_iteration_axes:
- return next(iter(unique_parent_paths))
- return None
-
- def _get_iterator_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
- input_collection_edge = next(iter(self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)))
- input_collection_prepared_node_id = next(
- prepared_id
- for source_id, prepared_id in iteration_node_map
- if source_id == input_collection_edge.source.node_id
- )
- input_collection_output = self._state.results[input_collection_prepared_node_id]
- input_collection = getattr(input_collection_output, input_collection_edge.source.field)
- return len(input_collection)
-
- def _get_for_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
- input_collection_edges = self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)
- if len(input_collection_edges) == 0:
- node = self._state.graph.get_node(node_id)
- assert isinstance(node, ForInvocation)
- return len(node.collection)
-
- input_collection_edge = input_collection_edges[0]
- input_collection_prepared_node_id = next(
- prepared_id
- for source_id, prepared_id in iteration_node_map
- if source_id == input_collection_edge.source.node_id
- )
- input_collection_output = self._state.results[input_collection_prepared_node_id]
- input_collection = getattr(input_collection_output, input_collection_edge.source.field)
- if not isinstance(input_collection, list):
- raise ValueError("For collection input must be a list")
- return len(input_collection)
-
- def _get_new_node_iterations(
- self, node: BaseInvocation, node_id: str, iteration_node_map: list[tuple[str, str]]
- ) -> list[int]:
- if isinstance(node, IterateInvocation):
- iteration_count = self._get_iterator_iteration_count(node_id, iteration_node_map)
- if iteration_count == 0:
- return []
- return list(range(iteration_count))
-
- if isinstance(node, ForInvocation):
- iteration_count = self._get_for_iteration_count(node_id, iteration_node_map)
- if iteration_count == 0:
- return []
- return [0]
-
- return [-1]
-
- def _build_execution_edges(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[Edge]:
- return self._build_execution_edges_for_fields(node_id, iteration_node_map)
-
- def _build_execution_edges_for_fields(
- self,
- node_id: str,
- iteration_node_map: list[tuple[str, str]],
- input_fields: Optional[set[str]] = None,
- ) -> list[Edge]:
- input_edges = self._state.graph._get_input_edges(node_id)
- new_edges: list[Edge] = []
- for edge in input_edges:
- if input_fields is not None and edge.destination.field not in input_fields:
- continue
- matching_inputs = [
- prepared_id for source_id, prepared_id in iteration_node_map if source_id == edge.source.node_id
- ]
- for input_node_id in matching_inputs:
- new_edges.append(
- Edge(
- source=EdgeConnection(node_id=input_node_id, field=edge.source.field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
- return new_edges
-
- def _has_unmaterializable_for_final_input(self, node_id: str) -> bool:
- final_for_source_ids = set()
- for edge in self._state.graph._get_input_edges(node_id):
- source_node = self._state.graph.get_node(edge.source.node_id)
- if not isinstance(source_node, ForInvocation):
- continue
- if get_output_field_scope(source_node, edge.source.field) == OutputScope.Final:
- final_for_source_ids.add(edge.source.node_id)
-
- return any(not self._state._all_for_contexts_finalized(source_for_id) for source_for_id in final_for_source_ids)
-
- def _create_execution_node_copy(
- self, node: BaseInvocation, node_id: str, iteration_index: int, *, deep_copy: bool = True
- ) -> BaseInvocation:
- new_node = node.model_copy(deep=deep_copy)
- new_node.id = uuid_string()
-
- if isinstance(new_node, IterateInvocation):
- new_node.index = iteration_index
- if isinstance(new_node, ForInvocation):
- new_node.index = iteration_index
-
- # Scheduler-managed iteration boundaries and collectors are cheaper to execute than to hash, especially when
- # their inputs contain large collections. Loop body nodes retain their normal cache behavior.
- if iteration_index >= 0 or isinstance(new_node, CollectInvocation):
- new_node.use_cache = False
-
- self._state._tx_add_execution_node(new_node)
- self._state._add_execution_graph_node(new_node.id)
- self._state._register_prepared_exec_node(new_node.id, node_id)
- return new_node
-
- def _create_empty_for_final_output(
- self,
- source_for_id: str,
- node: "ForInvocation",
- iteration_node_map: list[tuple[str, str]],
- ) -> str:
- new_node = self._create_execution_node_copy(node, source_for_id, -1, deep_copy=False)
- assert isinstance(new_node, ForInvocation)
- new_edges = self._build_execution_edges(source_for_id, iteration_node_map)
- iteration_path = self._get_known_iteration_path(-1, iteration_node_map)
- if iteration_path is not None:
- self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
- self._attach_execution_edges(new_node.id, new_edges)
- self._state._runtime().prepare_inputs(new_node)
-
- initial_state = copydeep(new_node.state or LoopState())
- self._state._tx_set_attr(new_node, "collection", [])
- self._state._tx_set_attr(new_node, "state", initial_state)
-
- self._state._tx_set_mapping(
- self._state.results,
- new_node.id,
- ForInvocationOutput(
- loop_linkage=LOOP_LINKAGE_FIELD,
- item=None,
- index=-1,
- total=0,
- state=initial_state,
- output_collection=[],
- final_state=initial_state,
- ),
- )
- self._state._tx_add_set(self._state.executed, new_node.id)
- self._state._set_prepared_exec_state(new_node.id, "executed")
-
- return new_node.id
-
- def _mark_empty_for_complete(self, source_for_id: str) -> None:
- prepared_for_ids = [
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_for_id)
- if isinstance(self._state.execution_graph.get_node(prepared_id), ForInvocation)
- and self._state.execution_graph.get_node(prepared_id).index == -1
- ]
- assert prepared_for_ids, f"Empty For '{source_for_id}' did not create a final execution node"
- for prepared_for_id in prepared_for_ids:
- self._state._mark_loop_context_finalized(source_for_id, prepared_for_id)
-
- self._state._mark_for_source_complete(source_for_id)
-
- def create_for_iteration(
- self,
- source_for_id: str,
- iteration_index: int,
- collection: list[Any],
- state: "LoopState",
- iteration_path: tuple[int, ...],
- ) -> str:
- node = self._state.graph.get_node(source_for_id)
- if not isinstance(node, ForInvocation):
- raise TypeError(f"Expected source ForInvocation, got {type(node).__name__}")
-
- new_node = self._create_execution_node_copy(node, source_for_id, iteration_index, deep_copy=False)
- assert isinstance(new_node, ForInvocation)
- self._state._tx_set_attr(new_node, "collection", copydeep(collection))
- self._state._tx_set_attr(new_node, "state", copydeep(state))
- self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
- self._initialize_execution_node(new_node.id)
- return new_node.id
-
- def create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
- graph = self._state._get_source_graph_flat()
- execution_graph = self._state._get_execution_graph_flat()
- nested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)
- if nested_body is not None:
- return self._create_nested_iterate_body_iteration(
- source_for_id, prepared_for_id, graph, execution_graph, nested_body
- )
- nested_for_body = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
- if nested_for_body is not None:
- return self._create_nested_for_body_iteration(
- source_for_id, prepared_for_id, graph, execution_graph, nested_for_body
- )
-
- body_path_to_return = self._state.graph._get_for_body_path_to_return(source_for_id, graph)
- if body_path_to_return is None:
- return None
-
- body_path_nodes, source_return_id = body_path_to_return
- source_to_prepared = {source_for_id: prepared_for_id}
- prepared_return_id: Optional[str] = None
-
- for source_node_id in nx.topological_sort(graph):
- if source_node_id not in body_path_nodes:
- continue
-
- node = self._state.graph.get_node(source_node_id)
- new_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_node_id):
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- if prepared_source_id is None:
- prepared_source_id = self.get_iteration_node(
- edge.source.node_id,
- graph,
- execution_graph,
- [prepared_for_id],
- )
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize For body input {edge}: no prepared source node is available"
- )
- new_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
-
- new_node = self._create_execution_node_copy(node, source_node_id, -1)
- source_to_prepared[source_node_id] = new_node.id
- self._state._prepared_registry().set_iteration_path(
- new_node.id, self._state._get_iteration_path(prepared_for_id)
- )
- self._state._discard_source_executed(source_node_id)
- attached_edges = self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id, attached_edges)
-
- if source_node_id == source_return_id:
- prepared_return_id = new_node.id
-
- return prepared_return_id
-
- def _is_deferred_nested_for_return(self, node_id: str, graph: "nx.DiGraph") -> bool:
- return any(
- (nested_body := self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)) is not None
- and nested_body.outer_return_id == node_id
- for source_for_id, source_node in self._state.graph.nodes.items()
- if isinstance(source_node, ForInvocation)
- )
-
- def _get_final_prepared_for_id(self, source_for_id: str, parent_iteration_path: tuple[int, ...]) -> str:
- self._state._get_prepared_for_index()
- assert self._state._final_prepared_for_index is not None
- prepared_for_id = self._state._final_prepared_for_index.get((source_for_id, parent_iteration_path))
- if prepared_for_id is None:
- raise RuntimeError(f"Unable to find finalized nested For '{source_for_id}' for {parent_iteration_path}")
- return prepared_for_id
-
- def create_nested_for_return(self, inner_for_id: str, prepared_inner_for_id: str) -> Optional[str]:
- graph = self._state._get_source_graph_flat()
- inner_iteration_path = self._state._get_iteration_path(prepared_inner_for_id)
- outer_for_id: Optional[str] = None
- nested_body: Optional[_SupportedNestedForBody] = None
- for source_for_id, source_node in self._state.graph.nodes.items():
- if not isinstance(source_node, ForInvocation):
- continue
- candidate = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
- if candidate is not None and inner_for_id in candidate.inner_for_ids:
- outer_for_id = source_for_id
- nested_body = candidate
- break
- if outer_for_id is None or nested_body is None:
- return None
-
- prepared_inner_for = self._state.execution_graph.get_node(prepared_inner_for_id)
- outer_iteration_path = (
- inner_iteration_path
- if isinstance(prepared_inner_for, ForInvocation) and prepared_inner_for.index == -1
- else inner_iteration_path[:-1]
- )
- prepared_outer_for_id = next(
- (
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(outer_for_id)
- if self._state._get_iteration_path(prepared_id) == outer_iteration_path
- ),
- None,
- )
- if prepared_outer_for_id is None:
- raise RuntimeError("Unable to rematerialize nested ForReturn: owning outer For is unavailable")
-
- source_return_id = nested_body.outer_return_id
- existing_return_ids = [
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_return_id)
- if self._state._get_iteration_path(prepared_id) == outer_iteration_path
- ]
- if len(existing_return_ids) > 1:
- raise RuntimeError(
- f"Multiple nested ForReturn executions exist for {source_return_id} at {outer_iteration_path}"
- )
- if existing_return_ids:
- return existing_return_ids[0]
-
- continuation_nodes = self._state.graph._get_for_nested_for_continuation_nodes(nested_body)
- prepared_inner_ids: dict[str, str] = {inner_for_id: prepared_inner_for_id}
- if any(
- not self._state._is_loop_context_finalized(inner_id, outer_iteration_path)
- for inner_id in nested_body.inner_for_ids
- ):
- return None
- for inner_id in nested_body.inner_for_ids:
- if inner_id in prepared_inner_ids:
- continue
- prepared_inner_ids[inner_id] = self._get_final_prepared_for_id(inner_id, outer_iteration_path)
- source_to_prepared: dict[str, str] = {
- outer_for_id: prepared_outer_for_id,
- **prepared_inner_ids,
- }
- for source_node_id in nx.topological_sort(graph):
- if source_node_id not in continuation_nodes:
- continue
-
- new_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_node_id):
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- if prepared_source_id is None:
- prepared_source_id = self.get_iteration_node(
- edge.source.node_id,
- graph,
- self._state._get_execution_graph_flat(),
- [prepared_outer_for_id],
- )
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize nested For continuation input {edge}: no prepared source node is available"
- )
- new_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
-
- new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
- source_to_prepared[source_node_id] = new_node.id
- self._state._prepared_registry().set_iteration_path(new_node.id, outer_iteration_path)
- self._state._discard_source_executed(source_node_id)
- attached_edges = self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id, attached_edges)
-
- self._state._discard_source_executed(source_return_id)
- return_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_return_id):
- if edge.destination.field == "output":
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- source_field = edge.source.field
- elif edge.destination.field == "state":
- prepared_source_id = prepared_outer_for_id
- source_field = edge.source.field
- elif edge.destination.field == "continue_condition":
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- source_field = edge.source.field
- else:
- raise RuntimeError(f"Unable to rematerialize nested ForReturn input {edge}")
- if prepared_source_id is None:
- raise RuntimeError(f"Unable to rematerialize nested ForReturn input {edge}")
- return_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=source_field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
-
- prepared_return_node = self._create_execution_node_copy(
- self._state.graph.get_node(source_return_id), source_return_id, -1
- )
- self._state._prepared_registry().set_iteration_path(prepared_return_node.id, outer_iteration_path)
- attached_return_edges = self._attach_execution_edges(prepared_return_node.id, return_edges)
- self._initialize_execution_node(prepared_return_node.id, attached_return_edges)
- return prepared_return_node.id
-
- def _create_nested_for_body_iteration(
- self,
- source_for_id: str,
- prepared_for_id: str,
- graph: "nx.DiGraph",
- execution_graph: "nx.DiGraph",
- nested_body: _SupportedNestedForBody,
- ) -> Optional[str]:
- """Materialize one nested-For body at the owning outer iteration path.
-
- The source graph is shaped as ``outer For -> inner For(s) -> outer ForReturn``. Existing execution nodes
- are reused at the current path; missing ordinary body nodes are copied, then each inner For is allowed to
- advance independently before the outer return is rematerialized.
- """
- body_path_nodes = nested_body.body_path_nodes
- source_return_id = nested_body.outer_return_id
- prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)
- outer_iteration_path = self._state._get_iteration_path(prepared_for_id)
- if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:
- outer_iteration_path = (
- *self._state._get_for_parent_iteration_path(prepared_for_id),
- prepared_for_node.index,
- )
-
- source_to_prepared: dict[str, str] = {source_for_id: prepared_for_id}
- for source_node_id in nx.topological_sort(graph):
- if source_node_id not in body_path_nodes or source_node_id in {
- *nested_body.inner_for_ids,
- source_return_id,
- }:
- continue
- if not any(nx.has_path(graph, source_node_id, inner_for_id) for inner_for_id in nested_body.inner_for_ids):
- continue
-
- existing_prepared_ids = [
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_node_id)
- if self._state._get_iteration_path(prepared_id) == outer_iteration_path
- ]
- if len(existing_prepared_ids) == 1:
- source_to_prepared[source_node_id] = existing_prepared_ids[0]
- continue
-
- new_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_node_id):
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- if prepared_source_id is None:
- prepared_source_id = self.get_iteration_node(
- edge.source.node_id, graph, execution_graph, [prepared_for_id]
- )
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize nested For input {edge}: no prepared source node is available"
- )
- new_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
-
- new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
- source_to_prepared[source_node_id] = new_node.id
- self._state._prepared_registry().set_iteration_path(new_node.id, outer_iteration_path)
- self._state._discard_source_executed(source_node_id)
- attached_edges = self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id, attached_edges)
-
- for body_node_id in body_path_nodes:
- if body_node_id in nested_body.inner_for_ids or not any(
- nx.has_path(graph, body_node_id, inner_for_id) for inner_for_id in nested_body.inner_for_ids
- ):
- self._state._discard_source_executed(body_node_id)
- self._state._discard_source_executed(source_return_id)
-
- for source_inner_for_id in nested_body.inner_for_ids:
- existing_prepared_ids = [
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_inner_for_id)
- if self._state._get_for_parent_iteration_path(prepared_id) == outer_iteration_path
- ]
- if existing_prepared_ids:
- continue
-
- inner_input_map: list[tuple[str, str]] = []
- for edge in self._state.graph._get_input_edges(source_inner_for_id):
- prepared_source_id = source_to_prepared.get(edge.source.node_id)
- if prepared_source_id is None:
- prepared_source_id = self.get_iteration_node(
- edge.source.node_id, graph, execution_graph, [prepared_for_id]
- )
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize nested For input {edge}: no prepared source node is available"
- )
- inner_input_map.append((edge.source.node_id, prepared_source_id))
-
- if any(prepared_source_id not in self._state.results for _, prepared_source_id in inner_input_map):
- return None
-
- self._state._discard_source_executed(source_inner_for_id)
- inner_prepared_ids = self.create_execution_node(
- source_inner_for_id, inner_input_map, iteration_path=outer_iteration_path
- )
- if not inner_prepared_ids:
- self._mark_source_node_empty(source_inner_for_id)
- elif all(
- isinstance(self._state.execution_graph.get_node(inner_id), ForInvocation)
- and self._state.execution_graph.get_node(inner_id).index == -1
- for inner_id in inner_prepared_ids
- ):
- self._mark_empty_for_complete(source_inner_for_id)
- for inner_prepared_id in inner_prepared_ids:
- self.create_nested_for_return(source_inner_for_id, inner_prepared_id)
- else:
- for inner_prepared_id in inner_prepared_ids:
- self.create_for_body_iteration(
- source_for_id=source_inner_for_id,
- prepared_for_id=inner_prepared_id,
- )
-
- return None
-
- def _create_nested_iterate_body_iteration(
- self,
- source_for_id: str,
- prepared_for_id: str,
- graph: "nx.DiGraph",
- execution_graph: "nx.DiGraph",
- nested_body: _SupportedNestedIterateBody,
- ) -> Optional[str]:
- body_path_nodes = nested_body.body_path_nodes
- source_return_id = nested_body.return_node_id
- source_iterate_id = nested_body.iterate_node_id
- source_collect_id = nested_body.collect_node_id
- prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)
- outer_iteration_path = self._state._get_iteration_path(prepared_for_id)
- if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:
- outer_iteration_path = (
- *self._state._get_for_parent_iteration_path(prepared_for_id),
- prepared_for_node.index,
- )
- source_to_prepared: dict[str, str] = {source_for_id: prepared_for_id}
- inner_prepared_by_source: dict[tuple[str, str], str] = {}
-
- def resolve_outer_input(source_node_id: str) -> Optional[str]:
- prepared_source_id = source_to_prepared.get(source_node_id)
- if prepared_source_id is not None:
- return prepared_source_id
- return self.get_iteration_node(source_node_id, graph, execution_graph, [prepared_for_id])
-
- def create_body_copy(source_node_id: str, input_resolver, iteration_path: tuple[int, ...]) -> str:
- new_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_node_id):
- prepared_source_id = input_resolver(edge.source.node_id)
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize For body input {edge}: no prepared source node is available"
- )
- new_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
-
- new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
- self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
- attached_edges = self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id, attached_edges)
- return new_node.id
-
- def get_existing_body_node(source_node_id: str) -> Optional[str]:
- matching_ids = [
- prepared_id
- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_node_id)
- if self._state._get_iteration_path(prepared_id) == outer_iteration_path
- ]
- if len(matching_ids) == 1:
- return matching_ids[0]
- return None
-
- for source_node_id in nx.topological_sort(graph):
- if source_node_id not in body_path_nodes or source_node_id in {
- source_iterate_id,
- source_collect_id,
- source_return_id,
- }:
- continue
- if not nx.has_path(graph, source_node_id, source_iterate_id):
- continue
- source_to_prepared[source_node_id] = get_existing_body_node(source_node_id) or create_body_copy(
- source_node_id, resolve_outer_input, outer_iteration_path
- )
-
- iterate_input_map: list[tuple[str, str]] = []
- for edge in self._state.graph._get_input_edges(source_iterate_id):
- prepared_source_id = resolve_outer_input(edge.source.node_id)
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize For body input {edge}: no prepared source node is available"
- )
- iterate_input_map.append((edge.source.node_id, prepared_source_id))
-
- if any(prepared_source_id not in self._state.results for _, prepared_source_id in iterate_input_map):
- return None
-
- self._state._discard_source_executed(source_iterate_id)
- inner_prepared_ids = self.create_execution_node(
- source_iterate_id, iterate_input_map, iteration_path=outer_iteration_path
- )
- if not inner_prepared_ids:
- self._mark_source_node_empty(source_iterate_id, outer_iteration_path)
-
- for inner_prepared_id in inner_prepared_ids:
- inner_iteration_path = self._state._get_iteration_path(inner_prepared_id)
- for source_node_id in nx.topological_sort(graph):
- if source_node_id not in body_path_nodes:
- continue
- if source_node_id in {source_iterate_id, source_collect_id, source_return_id}:
- continue
- if nx.has_path(graph, source_node_id, source_iterate_id):
- continue
- if not nx.has_path(graph, source_iterate_id, source_node_id):
- continue
-
- def resolve_inner_input(
- input_source_node_id: str, current_inner_prepared_id: str = inner_prepared_id
- ) -> Optional[str]:
- if input_source_node_id == source_iterate_id:
- return current_inner_prepared_id
- prepared_source_id = source_to_prepared.get(input_source_node_id)
- if prepared_source_id is not None:
- return prepared_source_id
- prepared_source_id = inner_prepared_by_source.get((input_source_node_id, current_inner_prepared_id))
- if prepared_source_id is not None:
- return prepared_source_id
- return self.get_iteration_node(
- input_source_node_id, graph, execution_graph, [current_inner_prepared_id]
- )
-
- self._state._discard_source_executed(source_node_id)
- prepared_id = create_body_copy(source_node_id, resolve_inner_input, inner_iteration_path)
- inner_prepared_by_source[(source_node_id, inner_prepared_id)] = prepared_id
-
- if not inner_prepared_ids:
- for source_node_id in body_path_nodes:
- if source_node_id in {source_iterate_id, source_collect_id, source_return_id}:
- continue
- if nx.has_path(graph, source_iterate_id, source_node_id):
- self._mark_source_node_empty(source_node_id, outer_iteration_path)
-
- collect_item_edge = self._state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]
- collect_edges: list[Edge] = []
- for inner_prepared_id in inner_prepared_ids:
- prepared_source_id = inner_prepared_by_source.get((collect_item_edge.source.node_id, inner_prepared_id))
- if prepared_source_id is None and collect_item_edge.source.node_id == source_iterate_id:
- prepared_source_id = inner_prepared_id
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize For body input {collect_item_edge}: no prepared source node is available"
- )
- collect_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=collect_item_edge.source.field),
- destination=EdgeConnection(node_id="", field=ITEM_FIELD),
- )
- )
-
- self._state._discard_source_executed(source_collect_id)
- collect_node = self._state.graph.get_node(source_collect_id)
- prepared_collect_node = self._create_execution_node_copy(collect_node, source_collect_id, -1)
- self._state._prepared_registry().set_iteration_path(prepared_collect_node.id, outer_iteration_path)
- attached_collect_edges = self._attach_execution_edges(prepared_collect_node.id, collect_edges)
- self._initialize_execution_node(prepared_collect_node.id, attached_collect_edges)
-
- return_edges: list[Edge] = []
- for edge in self._state.graph._get_input_edges(source_return_id):
- if edge.destination.field == "output":
- prepared_source_id = prepared_collect_node.id
- source_field = COLLECTION_FIELD
- else:
- prepared_source_id = resolve_outer_input(edge.source.node_id)
- source_field = edge.source.field
- if prepared_source_id is None:
- raise RuntimeError(
- f"Unable to rematerialize For body input {edge}: no prepared source node is available"
- )
- return_edges.append(
- Edge(
- source=EdgeConnection(node_id=prepared_source_id, field=source_field),
- destination=EdgeConnection(node_id="", field=edge.destination.field),
- )
- )
- self._state._discard_source_executed(source_return_id)
- prepared_return_node = self._create_execution_node_copy(
- self._state.graph.get_node(source_return_id), source_return_id, -1
- )
- self._state._prepared_registry().set_iteration_path(prepared_return_node.id, outer_iteration_path)
- attached_return_edges = self._attach_execution_edges(prepared_return_node.id, return_edges)
- self._initialize_execution_node(prepared_return_node.id, attached_return_edges)
- return prepared_return_node.id
-
- def _attach_execution_edges(self, exec_node_id: str, new_edges: list[Edge]) -> list[Edge]:
- attached_edges = [
- Edge(
- source=edge.source,
- destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
- )
- for edge in new_edges
- ]
- self._state._tx_add_execution_edges(attached_edges)
- self._state._add_execution_graph_edges(attached_edges)
- return attached_edges
-
- def _initialize_execution_node(self, exec_node_id: str, input_edges: Optional[list[Edge]] = None) -> None:
- inputs = input_edges if input_edges is not None else self._state.execution_graph._get_input_edges(exec_node_id)
- unmet = sum(1 for edge in inputs if edge.source.node_id not in self._state.executed)
- self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
- scheduler = self._state._scheduler()
- # Resolve a known conditional before registering its generic plan node so
- # generic retirement can release unselected prerequisites without
- # mutating the append-only execution graph.
- if isinstance(scheduler, _GenericGraphSchedulerAdapter):
- self._state._try_resolve_if_node(exec_node_id)
- if self._state._is_pending_if(exec_node_id):
- self._state._tx_add_set(self._state._pending_if_exec_nodes, exec_node_id)
- return
- scheduler.register_node(exec_node_id)
- else:
- self._state._try_resolve_if_node(exec_node_id, enqueue=False)
- if self._state._is_pending_if(exec_node_id):
- self._state._tx_add_set(self._state._pending_if_exec_nodes, exec_node_id)
- return
- self._state._enqueue_if_ready(exec_node_id)
-
- def _get_collect_iteration_group_key(self, edge: Edge, sibling_depth: Optional[int] = None) -> tuple[int, ...]:
- path = self._state._get_iteration_path(edge.source.node_id)
- source_node = self._state.execution_graph.get_node(edge.source.node_id)
- if (
- isinstance(source_node, ForInvocation)
- and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
- ):
- return self._state._get_for_parent_iteration_path(edge.source.node_id)
- if edge.destination.field == ITEM_FIELD:
- if isinstance(source_node, ForInvocation) and source_node.index == -1:
- return path
- # Ragged siblings need the deepest path to identify their shared outer group.
- depth = len(path) if sibling_depth is None else sibling_depth
- return path[: max(depth - 1, 0)]
- return path
-
- def _get_collect_source_iterator_ids(self, source_node_id: str) -> list[str]:
- iterator_node_ids = self.get_node_iterators(source_node_id)
- if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
- iterator_node_ids.append(source_node_id)
- return iterator_node_ids
-
- def _get_ordered_prepared_nodes_for_source(self, source_node_id: str) -> list[str]:
- return sorted(
- self._get_prepared_nodes_for_source(source_node_id),
- key=lambda exec_node_id: (self._state._get_iteration_path(exec_node_id), exec_node_id),
- )
-
- def _get_ordered_prepared_nodes_for_edge(self, edge: Edge) -> list[str]:
- prepared_nodes = self._get_ordered_prepared_nodes_for_source(edge.source.node_id)
- source_node = self._state.graph.get_node(edge.source.node_id)
- if not (
- isinstance(source_node, ForInvocation)
- and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
- ):
- return prepared_nodes
-
- final_nodes_by_parent_path: dict[tuple[int, ...], str] = {}
- for prepared_id in prepared_nodes:
- parent_path = self._state._get_for_parent_iteration_path(prepared_id)
- previous_id = final_nodes_by_parent_path.get(parent_path)
- if previous_id is None:
- final_nodes_by_parent_path[parent_path] = prepared_id
- continue
- previous_node = self._state.execution_graph.get_node(previous_id)
- prepared_node = self._state.execution_graph.get_node(prepared_id)
- assert isinstance(previous_node, ForInvocation)
- assert isinstance(prepared_node, ForInvocation)
- if prepared_node.index > previous_node.index:
- final_nodes_by_parent_path[parent_path] = prepared_id
-
- return [final_nodes_by_parent_path[parent_path] for parent_path in sorted(final_nodes_by_parent_path)]
-
- def _get_prepared_edge_iteration_path(self, edge: Edge, prepared_id: str) -> tuple[int, ...]:
- source_node = self._state.graph.get_node(edge.source.node_id)
- if (
- isinstance(source_node, ForInvocation)
- and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
- ):
- return self._state._get_for_parent_iteration_path(prepared_id)
- return self._state._get_iteration_path(prepared_id)
-
- def _get_iterator_input_iteration_paths(self, iterator_node_id: str) -> set[tuple[int, ...]]:
- iteration_paths: set[tuple[int, ...]] = set()
- for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD):
- source_node_id = edge.source.node_id
- prepared_nodes = self._get_ordered_prepared_nodes_for_source(source_node_id)
- iteration_paths.update(
- self._get_prepared_edge_iteration_path(edge, prepared_id) for prepared_id in prepared_nodes
- )
- return iteration_paths
-
- def _get_collect_candidate_group_keys(self, edge: Edge) -> set[tuple[int, ...]]:
- source_node_id = edge.source.node_id
- iterator_node_ids = self._get_collect_source_iterator_ids(source_node_id)
-
- group_depth = len(iterator_node_ids)
- if edge.destination.field == ITEM_FIELD:
- group_depth = max(group_depth - 1, 0)
-
- group_keys: set[tuple[int, ...]] = set()
- for iterator_node_id in iterator_node_ids:
- prepared_nodes = self._get_ordered_prepared_nodes_for_source(iterator_node_id)
- # Prepared paths use the active group depth. Input paths stay full to preserve scope across collectors.
- if prepared_nodes and group_depth:
- group_keys.update(
- iteration_path[:group_depth]
- for prepared_id in prepared_nodes
- if len(iteration_path := self._state._get_iteration_path(prepared_id)) >= group_depth
- )
- group_keys.update(self._get_iterator_input_iteration_paths(iterator_node_id))
-
- if group_keys:
- return group_keys
- if group_depth == 0:
- return {()}
- return set()
-
- def _get_collect_iteration_mapping_groups(
- self, input_edges: list[Edge]
- ) -> list[tuple[tuple[int, ...], list[tuple[str, str]]]]:
- prepared_inputs: list[tuple[Edge, str, str, tuple[int, ...]]] = []
- group_keys: set[tuple[int, ...]] = set()
- for edge in input_edges:
- group_keys.update(self._get_collect_candidate_group_keys(edge))
- prepared_nodes = self._get_ordered_prepared_nodes_for_edge(edge)
- sibling_depth = max(
- (len(self._get_prepared_edge_iteration_path(edge, prepared_id)) for prepared_id in prepared_nodes),
- default=0,
- )
- for prepared_id in prepared_nodes:
- prepared_edge = Edge(
- source=EdgeConnection(node_id=prepared_id, field=edge.source.field),
- destination=edge.destination,
- )
- group_key = self._get_collect_iteration_group_key(prepared_edge, sibling_depth)
- group_keys.add(group_key)
- prepared_inputs.append(
- (
- prepared_edge,
- edge.source.node_id,
- prepared_id,
- self._get_prepared_edge_iteration_path(edge, prepared_id),
- )
- )
-
- if not group_keys:
- group_keys.add(())
-
- final_group_keys = sorted(
- group_key
- for group_key in group_keys
- if not any(
- group_key != other_group_key and other_group_key[: len(group_key)] == group_key
- for other_group_key in group_keys
- )
- )
-
- return [
- (
- group_key,
- [
- (source_node_id, prepared_id)
- for prepared_edge, source_node_id, prepared_id, iteration_path in prepared_inputs
- if (
- prepared_edge.destination.field == ITEM_FIELD
- and (
- group_key[: len(iteration_path)] == iteration_path
- or iteration_path[: len(group_key)] == group_key
- )
- )
- or (
- prepared_edge.destination.field != ITEM_FIELD
- and group_key[: len(iteration_path)] == iteration_path
- )
- ],
- )
- for group_key in final_group_keys
- ]
-
- def _get_parent_iteration_mappings_without_iterators(
- self, next_node_id: str, input_edges: Optional[list[Edge]] = None
- ) -> list[list[tuple[str, str]]]:
- input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)
- parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))
- parent_prepared_nodes = {
- node_id: list(
- dict.fromkeys(
- (prepared_id, self._get_prepared_edge_iteration_path(edge, prepared_id))
- for edge in input_edges
- if edge.source.node_id == node_id
- for prepared_id in self._get_ordered_prepared_nodes_for_edge(edge)
- )
- )
- for node_id in parent_node_ids
- }
- all_iteration_paths = {
- iteration_path
- for prepared_nodes in parent_prepared_nodes.values()
- for _prepared_id, iteration_path in prepared_nodes
- if iteration_path != ()
- }
- iteration_paths = sorted(
- iteration_path
- for iteration_path in all_iteration_paths
- if not any(
- iteration_path != other_path and other_path[: len(iteration_path)] == iteration_path
- for other_path in all_iteration_paths
- )
- )
- if not iteration_paths:
- iteration_paths = [()]
-
- mappings: list[list[tuple[str, str]]] = []
- for iteration_path in iteration_paths:
- mapping: list[tuple[str, str]] = []
- for node_id, prepared_nodes in parent_prepared_nodes.items():
- matching_prepared = next(
- iter(
- sorted(
- (
- (prepared_id, prepared_path)
- for prepared_id, prepared_path in prepared_nodes
- if iteration_path[: len(prepared_path)] == prepared_path
- ),
- key=lambda prepared: (-len(prepared[1]), prepared[0]),
- )
- ),
- None,
- )
- if matching_prepared is None:
- break
- mapping.append((node_id, matching_prepared[0]))
- if len(mapping) == len(parent_node_ids):
- mappings.append(mapping)
- return mappings
-
- def _mark_source_node_empty(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> None:
- self._state._tx_set_mapping(self._state.source_prepared_mapping, source_node_id, set())
- self._state._mark_source_executed(source_node_id)
- if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
- self._state._record_empty_iterate_stream(source_node_id, iteration_path)
-
- def _index_prepared_nodes_by_iteration_path(
- self, prepared_nodes: set[str], input_edges: list[Edge]
- ) -> dict[tuple[int, ...], list[str]]:
- prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]] = {}
- for prepared_id in prepared_nodes:
- iteration_path = self._get_prepared_edge_iteration_path(input_edges[0], prepared_id)
- prepared_nodes_by_iteration_path.setdefault(iteration_path, []).append(prepared_id)
- return prepared_nodes_by_iteration_path
-
- def _get_target_iteration_path(
- self, source_node_id: str, graph: "nx.DiGraph", prepared_iterator_nodes: tuple[str, ...]
- ) -> Optional[tuple[int, ...]]:
- parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, list(prepared_iterator_nodes))
- parent_paths = [self._state._get_iteration_path(prepared_id) for prepared_id, _ in parent_iterators]
- if not parent_paths:
- return ()
-
- target_path = max(parent_paths, key=len)
- if all(target_path[: len(parent_path)] == parent_path for parent_path in parent_paths):
- return target_path
- return None
-
- def _get_indexed_iteration_node(
- self,
- source_node_id: str,
- graph: "nx.DiGraph",
- prepared_iterator_nodes: tuple[str, ...],
- prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]],
- ) -> Optional[str]:
- target_path = self._get_target_iteration_path(source_node_id, graph, prepared_iterator_nodes)
- if target_path is None:
- return None
-
- for path_length in range(len(target_path), -1, -1):
- candidates = prepared_nodes_by_iteration_path.get(target_path[:path_length], [])
- if len(candidates) == 1:
- return candidates[0]
- if len(candidates) > 1:
- return None
- return None
-
- def _get_parent_iteration_mappings(
- self, next_node_id: str, graph: "nx.DiGraph", input_edges: Optional[list[Edge]] = None
- ) -> Iterable[list[tuple[str, str]]]:
- input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)
- parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))
- iterator_graph = self.iterator_graph(graph)
- iterator_nodes = self.get_node_iterators(next_node_id, iterator_graph)
- if not iterator_nodes:
- return iter(self._get_parent_iteration_mappings_without_iterators(next_node_id, input_edges))
-
- iterator_nodes_prepared = [
- sorted(self._state.source_prepared_mapping[node_id], key=self._state._get_iteration_path)
- for node_id in iterator_nodes
- ]
- prepared_nodes_by_source = {
- node_id: self._get_prepared_nodes_for_source(node_id) for node_id in parent_node_ids
- }
- prepared_nodes_by_source_and_path = {
- node_id: self._index_prepared_nodes_by_iteration_path(
- prepared_nodes,
- [edge for edge in input_edges if edge.source.node_id == node_id],
- )
- for node_id, prepared_nodes in prepared_nodes_by_source.items()
- }
-
- def iter_mappings() -> Iterable[list[tuple[str, str]]]:
- execution_graph: Optional["nx.DiGraph"] = None
- for prepared_iterators in itertools.product(*iterator_nodes_prepared):
- mapping: list[tuple[str, str]] = []
- for node_id in parent_node_ids:
- prepared_id = self._get_indexed_iteration_node(
- node_id,
- graph,
- prepared_iterators,
- prepared_nodes_by_source_and_path[node_id],
- )
- if prepared_id is None:
- if execution_graph is None:
- execution_graph = self._state._get_execution_graph_flat()
- prepared_id = self.get_iteration_node(
- node_id,
- graph,
- execution_graph,
- list(prepared_iterators),
- prepared_nodes_by_source[node_id],
- )
- if prepared_id is None:
- break
- mapping.append((node_id, prepared_id))
- if len(mapping) == len(parent_node_ids):
- yield mapping
-
- return iter(iter_mappings())
-
- def create_execution_node(
- self,
- node_id: str,
- iteration_node_map: list[tuple[str, str]],
- iteration_path: Optional[tuple[int, ...]] = None,
- input_fields: Optional[set[str]] = None,
- enforce_admission: bool = True,
- ) -> list[str]:
- """Prepares an iteration node and connects all edges, returning the new node id"""
-
- node = self._state.graph.get_node(node_id)
- iteration_indexes = self._get_new_node_iterations(node, node_id, iteration_node_map)
- if not iteration_indexes:
- if isinstance(node, ForInvocation):
- return [self._create_empty_for_final_output(node_id, node, iteration_node_map)]
- return []
-
- new_edges = self._build_execution_edges_for_fields(node_id, iteration_node_map, input_fields)
- new_nodes: list[str] = []
- for iteration_index in iteration_indexes:
- new_node_iteration_path = iteration_path
- if new_node_iteration_path is None:
- new_node_iteration_path = self._get_known_iteration_path(iteration_index, iteration_node_map)
- elif isinstance(node, (ForInvocation, IterateInvocation)):
- new_node_iteration_path += (iteration_index,)
- if enforce_admission and not self._state._is_source_activation_admitted(
- node_id, new_node_iteration_path or ()
- ):
- continue
- new_node = self._create_execution_node_copy(node, node_id, iteration_index)
- if new_node_iteration_path is not None:
- self._state._prepared_registry().set_iteration_path(new_node.id, new_node_iteration_path)
- self._state._record_activation_dependencies(new_node.id)
- attached_edges = self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id, attached_edges)
- new_nodes.append(new_node.id)
-
- return new_nodes
-
- def _has_admitted_source_mapping(self, node_id: str, graph: "nx.DiGraph") -> bool:
- if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
- return True
- if isinstance(self._state.graph.get_node(node_id), IfInvocation):
- mappings = self._get_if_condition_iteration_mappings(node_id, graph)
- else:
- mappings = self._get_parent_iteration_mappings(node_id, graph)
- mappings = list(mappings)
- if not mappings:
- return self._state._is_source_activation_admitted(node_id)
- return any(
- self._state._is_source_activation_admitted(
- node_id, self._get_known_iteration_path(-1, iteration_mapping) or ()
- )
- for iteration_mapping in mappings
- )
-
- def _get_if_condition_iteration_mappings(
- self, node_id: str, graph: "nx.DiGraph"
- ) -> Iterable[list[tuple[str, str]]]:
- condition_edges = self._state.graph._get_input_edges(node_id, "condition")
- if not condition_edges:
- return iter([[]])
- return self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
-
- def _is_if_condition_ready(self, node_id: str) -> bool:
- return all(
- edge.source.node_id in self._state.source_prepared_mapping or edge.source.node_id in self._state.executed
- for edge in self._state.graph._get_input_edges(node_id, "condition")
- )
-
- def _attach_pending_if_inputs(self) -> None:
- """Attach only the selected branch edge to condition-ready If executions."""
-
- source_graph = self._state._get_source_graph_flat()
- source_order = {node_id: index for index, node_id in enumerate(nx.topological_sort(source_graph))}
- pending_exec_nodes = sorted(
- self._state._pending_if_exec_nodes,
- key=lambda exec_node_id: (
- source_order.get(self._state._prepared_registry().get_source_node_id(exec_node_id), 0),
- self._state._get_iteration_path(exec_node_id),
- exec_node_id,
- ),
- )
- for exec_node_id in pending_exec_nodes:
- self._state._try_resolve_if_node(exec_node_id, enqueue=False)
- selected_field = self._state._resolved_if_exec_branches.get(exec_node_id)
- if selected_field is None:
- continue
- if any(
- edge.destination.field == selected_field
- for edge in self._state.execution_graph._get_input_edges(exec_node_id)
- ):
- self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
- continue
-
- source_if_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
- target_path = self._state._get_iteration_path(exec_node_id)
- selected_edges = self._state.graph._get_input_edges(source_if_id, selected_field)
- attached_edges: list[Edge] = []
- selected_exec_ids: list[str] = []
- for source_edge in selected_edges:
- if source_edge.source.node_id not in self._state.source_prepared_mapping:
- continue
- candidates = [
- prepared_id
- for prepared_id in self._get_ordered_prepared_nodes_for_edge(source_edge)
- if self._get_prepared_edge_iteration_path(source_edge, prepared_id) == target_path
- ]
- if not candidates:
- continue
- selected_exec_ids.append(candidates[0])
- attached_edges.append(
- Edge(
- source=EdgeConnection(node_id=candidates[0], field=source_edge.source.field),
- destination=EdgeConnection(node_id=exec_node_id, field=selected_field),
- )
- )
- if not attached_edges or any(
- self._state._is_pending_if(candidate_id)
- or (
- isinstance(self._state.execution_graph.get_node(candidate_id), IfInvocation)
- and candidate_id not in self._state.executed
- )
- for candidate_id in selected_exec_ids
- ):
- continue
-
- self._attach_execution_edges(exec_node_id, attached_edges)
- input_edges = self._state.execution_graph._get_input_edges(exec_node_id)
- unmet = sum(1 for edge in input_edges if edge.source.node_id not in self._state.executed)
- self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
- self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
- scheduler = self._state._scheduler()
- if isinstance(scheduler, _GenericGraphSchedulerAdapter):
- scheduler.register_node(exec_node_id)
- self._state._enqueue_if_ready(exec_node_id)
-
- def iterator_graph(self, base: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
- """Gets a DiGraph with edges to collectors removed so an ancestor search produces all active iterators for any node"""
- g = base.copy() if base is not None else self._state._get_source_graph_flat().copy()
- collectors = (
- n for n in self._state.graph.nodes if isinstance(self._state.graph.get_node(n), CollectInvocation)
- )
- for c in collectors:
- g.remove_edges_from(list(g.in_edges(c)))
- for edge in self._state.graph.edges:
- source_node = self._state.graph.get_node(edge.source.node_id)
- if (
- isinstance(source_node, ForInvocation)
- and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
- ):
- if g.has_edge(edge.source.node_id, edge.destination.node_id):
- g.remove_edge(edge.source.node_id, edge.destination.node_id)
- return g
-
- def get_node_iterators(self, node_id: str, it_graph: Optional["nx.DiGraph"] = None) -> list[str]:
- g = it_graph or self.iterator_graph()
- return [
- n
- for n in nx.ancestors(g, node_id)
- if isinstance(self._state.graph.get_node(n), (ForInvocation, IterateInvocation))
- ]
-
- def _get_prepared_nodes_for_source(self, source_node_id: str) -> set[str]:
- return {
- exec_node_id
- for exec_node_id in self._state.source_prepared_mapping[source_node_id]
- if self._state._get_prepared_exec_metadata(exec_node_id).state != "skipped"
- }
-
- def _get_parent_iterator_exec_nodes(
- self, source_node_id: str, graph: "nx.DiGraph", prepared_iterator_nodes: list[str]
- ) -> list[tuple[str, str]]:
- iterator_source_node_mapping = [
- (prepared_exec_node_id, self._state.prepared_source_mapping[prepared_exec_node_id])
- for prepared_exec_node_id in prepared_iterator_nodes
- ]
- return [
- iterator_mapping
- for iterator_mapping in iterator_source_node_mapping
- if nx.has_path(graph, iterator_mapping[1], source_node_id)
- ]
-
- def _matches_parent_iterators(
- self, candidate_exec_node_id: str, parent_iterators: list[tuple[str, str]], execution_graph: "nx.DiGraph"
- ) -> bool:
- return all(
- nx.has_path(execution_graph, parent_iterator_exec_id, candidate_exec_node_id)
- for parent_iterator_exec_id, _ in parent_iterators
- )
-
- def _get_direct_prepared_iterator_match(
- self,
- prepared_nodes: set[str],
- prepared_iterator_nodes: list[str],
- parent_iterators: list[tuple[str, str]],
- execution_graph: "nx.DiGraph",
- ) -> Optional[str]:
- prepared_iterator = next((node_id for node_id in prepared_iterator_nodes if node_id in prepared_nodes), None)
- if prepared_iterator is None:
- return None
- if self._matches_parent_iterators(prepared_iterator, parent_iterators, execution_graph):
- return prepared_iterator
- return None
-
- def _find_prepared_node_matching_iterators(
- self, prepared_nodes: set[str], parent_iterators: list[tuple[str, str]], execution_graph: "nx.DiGraph"
- ) -> Optional[str]:
- return next(
- (
- node_id
- for node_id in prepared_nodes
- if self._matches_parent_iterators(node_id, parent_iterators, execution_graph)
- ),
- None,
- )
-
- def _get_final_for_exec_node(self, prepared_nodes: set[str]) -> Optional[str]:
- prepared_for_nodes = [(node_id, self._state.execution_graph.nodes.get(node_id)) for node_id in prepared_nodes]
- prepared_for_nodes = [
- (node_id, node) for node_id, node in prepared_for_nodes if isinstance(node, ForInvocation)
- ]
- if not prepared_for_nodes:
- return None
- return max(prepared_for_nodes, key=lambda item: item[1].index)[0]
-
- def get_iteration_node(
- self,
- source_node_id: str,
- graph: "nx.DiGraph",
- execution_graph: "nx.DiGraph",
- prepared_iterator_nodes: list[str],
- prepared_nodes: Optional[set[str]] = None,
- ) -> Optional[str]:
- if prepared_nodes is None:
- prepared_nodes = self._get_prepared_nodes_for_source(source_node_id)
- if len(prepared_nodes) == 1 and not prepared_iterator_nodes:
- return next(iter(prepared_nodes))
-
- parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, prepared_iterator_nodes)
- if not parent_iterators and isinstance(self._state.graph.get_node(source_node_id), ForInvocation):
- return self._get_final_for_exec_node(prepared_nodes)
- if len(prepared_nodes) == 1:
- prepared_node_id = next(iter(prepared_nodes))
- if self._matches_parent_iterators(prepared_node_id, parent_iterators, execution_graph):
- return prepared_node_id
- return None
-
- direct_iterator_match = self._get_direct_prepared_iterator_match(
- prepared_nodes, prepared_iterator_nodes, parent_iterators, execution_graph
- )
- if direct_iterator_match is not None:
- return direct_iterator_match
-
- return self._find_prepared_node_matching_iterators(prepared_nodes, parent_iterators, execution_graph)
-
- def prepare(self, base_g: Optional["nx.DiGraph"] = None) -> Optional[str]:
- g = base_g if base_g is not None else self._state._get_source_graph_flat()
- self._attach_pending_if_inputs()
- next_node_id = next(
- (
- node_id
- for node_id in nx.topological_sort(g)
- if node_id not in self._state.source_prepared_mapping
- and node_id not in self._state.executed
- and not (
- isinstance(self._state.graph.get_node(node_id), ForReturnInvocation)
- and self._is_deferred_nested_for_return(node_id, g)
- )
- and not self._has_unmaterializable_for_final_input(node_id)
- and (
- all(
- edge.source.node_id in self._state.source_prepared_mapping
- or edge.source.node_id in self._state.executed
- for edge in self._state.graph._get_input_edges(node_id, "condition")
- )
- if isinstance(self._state.graph.get_node(node_id), IfInvocation)
- else all(
- source_id in self._state.source_prepared_mapping or source_id in self._state.executed
- for source_id, _ in g.in_edges(node_id)
- )
- )
- and (
- isinstance(self._state.graph.get_node(node_id), IfInvocation)
- and self._is_if_condition_ready(node_id)
- or not isinstance(self._state.graph.get_node(node_id), IfInvocation)
- )
- and self._has_admitted_source_mapping(node_id, g)
- and (
- not isinstance(self._state.graph.get_node(node_id), (ForInvocation, IterateInvocation))
- or all(source_id in self._state.executed for source_id, _ in g.in_edges(node_id))
- )
- and not any(
- isinstance(self._state.graph.get_node(ancestor_id), (ForInvocation, IterateInvocation))
- and ancestor_id not in self._state.executed
- for ancestor_id in nx.ancestors(g, node_id)
- )
- ),
- None,
- )
-
- if next_node_id is None:
- return None
-
- next_node = self._state.graph.get_node(next_node_id)
- new_node_ids: list[str] = []
-
- if isinstance(next_node, CollectInvocation):
- iteration_mapping_groups = self._get_collect_iteration_mapping_groups(
- self._state.graph._get_input_edges(next_node_id)
- )
- for iteration_path, iteration_mappings in iteration_mapping_groups:
- create_results = self.create_execution_node(next_node_id, iteration_mappings, iteration_path)
- new_node_ids.extend(create_results)
- else:
- parent_iterator_nodes = self.get_node_iterators(next_node_id)
- iteration_mappings_iter = (
- self._get_if_condition_iteration_mappings(next_node_id, g)
- if isinstance(next_node, IfInvocation)
- else self._get_parent_iteration_mappings(next_node_id, g)
- )
- for iteration_mappings in iteration_mappings_iter:
- iteration_path = None
- if not parent_iterator_nodes:
- input_edges = self._state.graph._get_input_edges(next_node_id)
- iteration_path = max(
- (
- self._get_prepared_edge_iteration_path(edge, prepared_id)
- for source_id, prepared_id in iteration_mappings
- for edge in input_edges
- if edge.source.node_id == source_id
- ),
- key=lambda path: (len(path), path),
- default=(),
- )
- create_results = self.create_execution_node(
- next_node_id,
- iteration_mappings,
- iteration_path,
- input_fields={"condition"} if isinstance(next_node, IfInvocation) else None,
- )
- new_node_ids.extend(create_results)
-
- if not new_node_ids:
- # No parent mappings means zero loop contexts, unlike a context with an empty collection.
- self._mark_source_node_empty(next_node_id)
- self._state._invalidate_loop_caches_for_source(next_node_id)
- return next_node_id
-
- if isinstance(next_node, ForInvocation) and all(
- self._state.execution_graph.get_node(exec_node_id).index == -1 for exec_node_id in new_node_ids
- ):
- self._mark_empty_for_complete(next_node_id)
-
- return new_node_ids[0]
-
-
class _ExecutionScheduler:
"""Owns ready-queue ordering and indegree-driven execution transitions."""
@@ -2861,6 +1430,12 @@ class GraphExecutionState(BaseModel):
self._execution_scheduler = _ExecutionScheduler(self)
return self._execution_scheduler
+ def _is_generic_graph_scheduler(self, scheduler: Any) -> bool:
+ return isinstance(scheduler, _GenericGraphSchedulerAdapter)
+
+ def _new_execution_node_id(self) -> str:
+ return uuid_string()
+
def _runtime(self) -> _ExecutionRuntime:
if self._execution_runtime is None:
self._execution_runtime = _ExecutionRuntime(self)
@@ -4292,515 +2867,46 @@ class GraphExecutionState(BaseModel):
def _get_direct_iterate_collect_fan_in(
self, iterator_ids: list[str], collector_id: str
) -> Optional[_DirectIterateCollectFanIn]:
- 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) != 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
- ):
- return None
-
- branches: list[tuple[str, str]] = []
- for iterator_id in iterator_ids:
- collection_edges = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
- if len(collection_edges) != 1:
- return None
- collection_edge = collection_edges[0]
- if collection_edge.destination.node_id != iterator_id or collection_edge.source.field != COLLECTION_FIELD:
- return None
-
- source_id = collection_edge.source.node_id
- source = self.graph.get_node(source_id)
- if isinstance(
- source,
- (
- CallSavedWorkflowInvocation,
- ForInvocation,
- ForReturnInvocation,
- IfInvocation,
- IterateInvocation,
- CollectInvocation,
- ),
- ):
- return None
- if self.graph._get_input_edges(source_id) or self.graph._get_output_edges(source_id) != [collection_edge]:
- return None
-
- iterator_item_edges = self.graph._get_output_edges(iterator_id, ITEM_FIELD)
- if len(iterator_item_edges) != 1 or iterator_item_edges[0] not in item_edges:
- return None
- if self.graph._get_output_edges(iterator_id) != iterator_item_edges:
- return None
- branches.append((source_id, iterator_id))
-
- branches.sort(key=lambda branch: branch[0])
- return _DirectIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+ return _get_direct_iterate_collect_fan_in(self, iterator_ids, collector_id)
def _get_body_iterate_collect_fan_in(
self, iterator_ids: list[str], collector_id: str
) -> Optional[_BodyIterateCollectFanIn]:
- if len(iterator_ids) != 2 or len(self.graph.nodes) != 7 or len(self.graph.edges) != 6:
- 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):
- return None
- if any(edge.destination.field != ITEM_FIELD for edge in item_edges):
- return None
-
- item_edges_by_body = {edge.source.node_id: edge for edge in item_edges}
- branches: list[tuple[str, str, str]] = []
- for iterator_id in iterator_ids:
- collection_edges = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
- if len(collection_edges) != 1:
- return None
- collection_edge = collection_edges[0]
- if collection_edge.destination.node_id != iterator_id or collection_edge.source.field != COLLECTION_FIELD:
- return None
-
- source_id = collection_edge.source.node_id
- source = self.graph.get_node(source_id)
- if isinstance(
- source,
- (
- CallSavedWorkflowInvocation,
- ForInvocation,
- ForReturnInvocation,
- IfInvocation,
- IterateInvocation,
- CollectInvocation,
- ),
- ):
- return None
- if self.graph._get_input_edges(source_id) or self.graph._get_output_edges(source_id) != [collection_edge]:
- return None
-
- iterator_item_edges = self.graph._get_output_edges(iterator_id, ITEM_FIELD)
- if len(iterator_item_edges) != 1 or iterator_item_edges[0].source.node_id != iterator_id:
- return None
- if self.graph._get_output_edges(iterator_id) != iterator_item_edges:
- return None
-
- body_edge = iterator_item_edges[0]
- if body_edge.source.field != ITEM_FIELD:
- return None
- body_id = body_edge.destination.node_id
- if body_id in {source_id, iterator_id, collector_id} or body_id not in item_edges_by_body:
- return None
- body = self.graph.get_node(body_id)
- if isinstance(
- body,
- (
- CallSavedWorkflowInvocation,
- ForInvocation,
- ForReturnInvocation,
- IfInvocation,
- IterateInvocation,
- CollectInvocation,
- ),
- ):
- return None
- body_input_edges = self.graph._get_input_edges(body_id)
- if len(body_input_edges) != 1 or body_input_edges[0] != body_edge:
- return None
-
- collect_item_edge = item_edges_by_body[body_id]
- if self.graph._get_output_edges(body_id) != [collect_item_edge]:
- return None
- branches.append((source_id, iterator_id, body_id))
-
- if len({source_id for source_id, _iterator_id, _body_id in branches}) != 2:
- return None
- if len({iterator_id for _source_id, iterator_id, _body_id in branches}) != 2:
- return None
- if len({body_id for _source_id, _iterator_id, body_id in branches}) != 2:
- return None
-
- branches.sort(key=lambda branch: branch[0])
- return _BodyIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+ return _get_body_iterate_collect_fan_in(self, iterator_ids, collector_id)
def _get_direct_iterate_collect_nodes(
self,
) -> Optional[tuple[str, str, str, str, tuple[str, ...]] | _DirectIterateCollectFanIn | _BodyIterateCollectFanIn]:
- """Return fresh direct/body planner nodes, including ordinary downstream consumers."""
-
- if (
- self._legacy_snapshot_loaded
- or len(self.graph.nodes) < 4
- or len(self.graph.edges) != len(self.graph.nodes) - 1
- ):
- return None
-
- 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) in {2, 3} and len(collector_ids) == 1:
- if len(iterator_ids) == 2:
- body_fan_in = self._get_body_iterate_collect_fan_in(iterator_ids, collector_ids[0])
- if body_fan_in is not None:
- return body_fan_in
- 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
- iterator_id = iterator_ids[0]
- collector_id = collector_ids[0]
-
- collection_edges = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
- item_edges = self.graph._get_input_edges(collector_id, ITEM_FIELD)
- if len(collection_edges) != 1 or len(item_edges) != 1:
- return None
- collection_edge = collection_edges[0]
- item_edge = item_edges[0]
- if collection_edge.source.field != COLLECTION_FIELD or item_edge.destination.field != ITEM_FIELD:
- return None
- if collection_edge.destination.node_id != iterator_id:
- return None
-
- body_id = item_edge.source.node_id
- if body_id in {iterator_id, collector_id}:
- return None
- body = self.graph.get_node(body_id)
- if isinstance(body, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)):
- return None
- body_input_edges = self.graph._get_input_edges(body_id)
- if len(body_input_edges) != 1 or body_input_edges[0] != Edge(
- source=EdgeConnection(node_id=iterator_id, field=ITEM_FIELD),
- destination=EdgeConnection(node_id=body_id, field=body_input_edges[0].destination.field),
- ):
- return None
- if body_input_edges[0].source.field != ITEM_FIELD:
- return None
-
- source_id = collection_edge.source.node_id
- if source_id in {iterator_id, body_id, collector_id}:
- return None
- source = self.graph.get_node(source_id)
- if isinstance(source, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)):
- return None
- if self.graph._get_input_edges(source_id):
- return None
- if self.graph._get_output_edges(source_id) != [collection_edge]:
- return None
- if self.graph._get_output_edges(iterator_id) != [body_input_edges[0]]:
- return None
- if self.graph._get_output_edges(body_id) != [item_edge]:
- return None
- if self.graph._get_input_edges(collector_id) != [item_edge]:
- return None
-
- downstream_edges = self.graph._get_output_edges(collector_id, COLLECTION_FIELD)
- if len(downstream_edges) != len(self.graph.nodes) - 4:
- return None
- downstream_ids: list[str] = []
- for downstream_edge in downstream_edges:
- downstream_id = downstream_edge.destination.node_id
- downstream = self.graph.get_node(downstream_id)
- if downstream_id in {source_id, iterator_id, body_id, collector_id} or isinstance(
- downstream, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)
- ):
- return None
- if self.graph._get_input_edges(downstream_id) != [downstream_edge]:
- return None
- downstream_ids.append(downstream_id)
-
- return source_id, iterator_id, body_id, collector_id, tuple(downstream_ids)
+ return _get_direct_iterate_collect_nodes(self)
def _can_use_direct_iterate_collect_planner(self) -> bool:
- """Use fresh planner ownership only for the exact direct stream shape."""
-
- return self._get_direct_iterate_collect_nodes() is not None
+ return _can_use_direct_iterate_collect_planner(self)
def _create_direct_execution_node_copy(
self, source_node_id: str, iteration_index: int = -1, iteration_path: tuple[int, ...] = ()
) -> BaseInvocation:
- source_node = self.graph.get_node(source_node_id)
- new_node = source_node.model_copy(deep=True)
- new_node.id = uuid_string()
- if isinstance(new_node, IterateInvocation):
- new_node.index = iteration_index
- if iteration_index >= 0 or isinstance(new_node, CollectInvocation):
- new_node.use_cache = False
- self._tx_add_execution_node(new_node)
- self._add_execution_graph_node(new_node.id)
- self._register_prepared_exec_node(new_node.id, source_node_id)
- self._prepared_registry().set_iteration_path(new_node.id, iteration_path)
- return new_node
+ return _create_direct_execution_node_copy(self, source_node_id, iteration_index, iteration_path)
def _attach_direct_execution_edges(self, exec_node_id: str, edges: Iterable[Edge]) -> list[Edge]:
- attached_edges = [
- Edge(
- source=edge.source,
- destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
- )
- for edge in edges
- ]
- self._tx_add_execution_edges(attached_edges)
- self._add_execution_graph_edges(attached_edges)
- return attached_edges
+ return _attach_direct_execution_edges(self, exec_node_id, edges)
def _initialize_direct_execution_node(self, exec_node_id: str, input_edges: Iterable[Edge]) -> None:
- input_edges = list(input_edges)
- self._tx_set_mapping(
- self.indegree,
- exec_node_id,
- sum(1 for edge in input_edges if edge.source.node_id not in self.executed),
- )
- scheduler = self._scheduler()
- assert isinstance(scheduler, _GenericGraphSchedulerAdapter)
- scheduler.register_node(exec_node_id)
- self._enqueue_if_ready(exec_node_id)
+ _initialize_direct_execution_node(self, exec_node_id, input_edges)
def _mark_direct_source_empty(self, source_node_id: str) -> None:
- """Record an empty direct iterator source without entering the legacy materializer."""
-
- self._tx_set_mapping(self.source_prepared_mapping, source_node_id, set())
- self._mark_source_executed(source_node_id)
- if isinstance(self.graph.get_node(source_node_id), IterateInvocation):
- self._record_empty_iterate_stream(source_node_id)
+ _mark_direct_source_empty(self, source_node_id)
def _prepare_direct_iterate_collect_fan_in_unchecked(self, fan_in: _DirectIterateCollectFanIn) -> None:
- source_exec_ids: dict[str, str] = {}
- for source_id, _iterator_id in fan_in.branches:
- if source_id not in self.source_prepared_mapping:
- source_node = self._create_direct_execution_node_copy(source_id)
- self._initialize_direct_execution_node(source_node.id, ())
- if source_id in self.executed:
- source_exec_ids[source_id] = sorted(self.source_prepared_mapping[source_id])[0]
-
- if len(source_exec_ids) != len(fan_in.branches):
- return
- if fan_in.collector_id in self.source_prepared_mapping:
- return
-
- iterator_exec_ids: list[tuple[str, str]] = []
- collector_item_edges = {
- edge.source.node_id: edge for edge in self.graph._get_input_edges(fan_in.collector_id, ITEM_FIELD)
- }
- for source_id, iterator_id in fan_in.branches:
- collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
- collection = getattr(self.results[source_exec_ids[source_id]], collection_edge.source.field)
- if not isinstance(collection, list):
- raise ValueError("Direct Iterate collection source must produce a list")
-
- for index in range(len(collection)):
- iterator_node = self._create_direct_execution_node_copy(iterator_id, index, (index,))
- attached_iterator_edges = self._attach_direct_execution_edges(
- iterator_node.id,
- [
- Edge(
- source=EdgeConnection(
- node_id=source_exec_ids[source_id], field=collection_edge.source.field
- ),
- destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
- )
- ],
- )
- self._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
- iterator_exec_ids.append((iterator_node.id, iterator_id))
-
- if not collection:
- self._mark_direct_source_empty(iterator_id)
-
- collector_node = self._create_direct_execution_node_copy(fan_in.collector_id, iteration_path=())
- collector_edges = [
- Edge(
- source=EdgeConnection(node_id=iterator_exec_id, field=ITEM_FIELD),
- destination=EdgeConnection(node_id="", field=collector_item_edges[iterator_id].destination.field),
- )
- for iterator_exec_id, iterator_id in iterator_exec_ids
- ]
- attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
- self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+ _prepare_direct_iterate_collect_fan_in_unchecked(self, fan_in)
def _prepare_body_iterate_collect_fan_in_unchecked(self, fan_in: _BodyIterateCollectFanIn) -> None:
- source_exec_ids: dict[str, str] = {}
- for source_id, _iterator_id, _body_id in fan_in.branches:
- if source_id not in self.source_prepared_mapping:
- source_node = self._create_direct_execution_node_copy(source_id)
- self._initialize_direct_execution_node(source_node.id, ())
- if source_id in self.executed:
- source_exec_ids[source_id] = sorted(self.source_prepared_mapping[source_id])[0]
-
- if len(source_exec_ids) != len(fan_in.branches):
- return
- if fan_in.collector_id in self.source_prepared_mapping:
- return
-
- collections: dict[str, list[Any]] = {}
- for source_id, iterator_id, _body_id in fan_in.branches:
- collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
- collection = getattr(self.results[source_exec_ids[source_id]], collection_edge.source.field)
- if not isinstance(collection, list):
- raise ValueError("Body Iterate collection source must produce a list")
- collections[source_id] = collection
-
- collector_item_edges = {
- edge.source.node_id: edge for edge in self.graph._get_input_edges(fan_in.collector_id, ITEM_FIELD)
- }
- for source_id, iterator_id, body_id in fan_in.branches:
- collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
- body_input_edge = self.graph._get_input_edges(body_id)[0]
- collect_item_edge = collector_item_edges[body_id]
- source_exec_id = source_exec_ids[source_id]
- collection = collections[source_id]
- for index in range(len(collection)):
- iterator_node = self._create_direct_execution_node_copy(iterator_id, index, (index,))
- attached_iterator_edges = self._attach_direct_execution_edges(
- iterator_node.id,
- [
- Edge(
- source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),
- destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
- )
- ],
- )
- self._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
-
- body_node = self._create_direct_execution_node_copy(body_id, iteration_path=(index,))
- attached_body_edges = self._attach_direct_execution_edges(
- body_node.id,
- [
- Edge(
- source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),
- destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
- )
- ],
- )
- self._initialize_direct_execution_node(body_node.id, attached_body_edges)
-
- if not collection:
- self._mark_direct_source_empty(iterator_id)
- self._mark_direct_source_empty(body_id)
-
- collector_node = self._create_direct_execution_node_copy(fan_in.collector_id, iteration_path=())
- collector_edges: list[Edge] = []
- for _source_id, _iterator_id, body_id in fan_in.branches:
- collect_item_edge = collector_item_edges[body_id]
- for body_exec_id in sorted(
- self.source_prepared_mapping.get(body_id, set()),
- key=lambda exec_id: self._get_iteration_path(exec_id),
- ):
- collector_edges.append(
- Edge(
- source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
- destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
- )
- )
- attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
- self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+ _prepare_body_iterate_collect_fan_in_unchecked(self, fan_in)
def _prepare_direct_iterate_collect(self) -> None:
- """Expand the fresh direct stream shape atomically, without the legacy materializer."""
-
- if self._apply_transaction is not None:
- self._prepare_direct_iterate_collect_unchecked()
- return
-
- transaction = _ApplyTransaction()
- object.__setattr__(self, "_apply_transaction", transaction)
- try:
- self._prepare_direct_iterate_collect_unchecked()
- except Exception:
- try:
- transaction.rollback()
- finally:
- self._reset_apply_derived_caches()
- self._rehydrate_ready_queues()
- raise
- finally:
- object.__setattr__(self, "_apply_transaction", None)
+ _prepare_direct_iterate_collect(self)
def _prepare_direct_iterate_collect_unchecked(self) -> None:
- """Expand the direct stream shape while the caller owns mutation rollback."""
-
- node_ids = self._get_direct_iterate_collect_nodes()
- if node_ids is None:
- return
- if isinstance(node_ids, _BodyIterateCollectFanIn):
- self._prepare_body_iterate_collect_fan_in_unchecked(node_ids)
- return
- if isinstance(node_ids, _DirectIterateCollectFanIn):
- self._prepare_direct_iterate_collect_fan_in_unchecked(node_ids)
- return
- source_id, iterator_id, body_id, collector_id, downstream_ids = node_ids
-
- if source_id not in self.source_prepared_mapping:
- source_node = self._create_direct_execution_node_copy(source_id)
- self._initialize_direct_execution_node(source_node.id, ())
- return
-
- if collector_id in self.source_prepared_mapping:
- return
-
- if source_id not in self.executed:
- return
- source_exec_id = next(iter(self.source_prepared_mapping[source_id]))
- source_output = self.results[source_exec_id]
- collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
- collection = getattr(source_output, collection_edge.source.field)
- if not isinstance(collection, list):
- raise ValueError("Direct Iterate collection source must produce a list")
-
- iterator_exec_ids: list[str] = []
- body_exec_ids: list[str] = []
- body_input_edge = self.graph._get_input_edges(body_id)[0]
- collect_item_edge = self.graph._get_input_edges(collector_id, ITEM_FIELD)[0]
- for index in range(len(collection)):
- iterator_node = self._create_direct_execution_node_copy(iterator_id, index, (index,))
- iterator_edges = [
- Edge(
- source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),
- destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
- )
- ]
- attached_iterator_edges = self._attach_direct_execution_edges(iterator_node.id, iterator_edges)
- self._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
- iterator_exec_ids.append(iterator_node.id)
-
- body_node = self._create_direct_execution_node_copy(body_id, iteration_path=(index,))
- body_edges = [
- Edge(
- source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),
- destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
- )
- ]
- attached_body_edges = self._attach_direct_execution_edges(body_node.id, body_edges)
- self._initialize_direct_execution_node(body_node.id, attached_body_edges)
- body_exec_ids.append(body_node.id)
-
- if not iterator_exec_ids:
- self._mark_direct_source_empty(iterator_id)
- self._mark_direct_source_empty(body_id)
-
- collector_node = self._create_direct_execution_node_copy(collector_id, iteration_path=())
- collector_edges = [
- Edge(
- source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
- destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
- )
- for body_exec_id in body_exec_ids
- ]
- attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
- self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
-
- for downstream_id in downstream_ids:
- downstream_node = self._create_direct_execution_node_copy(downstream_id)
- downstream_edge = self.graph._get_input_edges(downstream_id)[0]
- attached_downstream_edges = self._attach_direct_execution_edges(
- downstream_node.id,
- [
- Edge(
- source=EdgeConnection(node_id=collector_node.id, field=downstream_edge.source.field),
- destination=EdgeConnection(node_id="", field=downstream_edge.destination.field),
- )
- ],
- )
- self._initialize_direct_execution_node(downstream_node.id, attached_downstream_edges)
+ _prepare_direct_iterate_collect_unchecked(self)
def _reset_runtime_caches(self) -> None:
self._ready_queues = {}
diff --git a/invokeai/app/services/shared/graph_iterate_planner.py b/invokeai/app/services/shared/graph_iterate_planner.py
new file mode 100644
index 0000000000..bcf977343c
--- /dev/null
+++ b/invokeai/app/services/shared/graph_iterate_planner.py
@@ -0,0 +1,554 @@
+"""Direct Iterate/Collect planner helpers for graph execution state."""
+
+from typing import TYPE_CHECKING, Any, Iterable, Optional
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation
+from invokeai.app.services.shared.graph_execution_runtime import (
+ _BodyIterateCollectFanIn,
+ _DirectIterateCollectFanIn,
+)
+from invokeai.app.services.shared.graph_models import Edge, EdgeConnection
+from invokeai.app.services.shared.graph_runtime_records import _ApplyTransaction
+from invokeai.app.services.shared.graph_validation import (
+ COLLECTION_FIELD,
+ ITEM_FIELD,
+ CollectInvocation,
+ IterateInvocation,
+)
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+def _get_direct_iterate_collect_fan_in(
+ state: "GraphExecutionState", iterator_ids: list[str], collector_id: str
+) -> Optional[_DirectIterateCollectFanIn]:
+ branch_count = len(iterator_ids)
+ if branch_count not in {2, 3} or len(state.graph.nodes) != 2 * branch_count + 1:
+ return None
+ if len(state.graph.edges) != 2 * branch_count:
+ return None
+
+ item_edges = state.graph._get_input_edges(collector_id, ITEM_FIELD)
+ if len(item_edges) != branch_count or state.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
+ ):
+ return None
+
+ branches: list[tuple[str, str]] = []
+ for iterator_id in iterator_ids:
+ collection_edges = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
+ if len(collection_edges) != 1:
+ return None
+ collection_edge = collection_edges[0]
+ if collection_edge.destination.node_id != iterator_id or collection_edge.source.field != COLLECTION_FIELD:
+ return None
+
+ source_id = collection_edge.source.node_id
+ source = state.graph.get_node(source_id)
+ if isinstance(
+ source,
+ (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IfInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ ),
+ ):
+ return None
+ if state.graph._get_input_edges(source_id) or state.graph._get_output_edges(source_id) != [collection_edge]:
+ return None
+
+ iterator_item_edges = state.graph._get_output_edges(iterator_id, ITEM_FIELD)
+ if len(iterator_item_edges) != 1 or iterator_item_edges[0] not in item_edges:
+ return None
+ if state.graph._get_output_edges(iterator_id) != iterator_item_edges:
+ return None
+ branches.append((source_id, iterator_id))
+
+ branches.sort(key=lambda branch: branch[0])
+ return _DirectIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+
+
+def _get_body_iterate_collect_fan_in(
+ state: "GraphExecutionState", iterator_ids: list[str], collector_id: str
+) -> Optional[_BodyIterateCollectFanIn]:
+ if len(iterator_ids) != 2 or len(state.graph.nodes) != 7 or len(state.graph.edges) != 6:
+ return None
+
+ item_edges = state.graph._get_input_edges(collector_id, ITEM_FIELD)
+ if len(item_edges) != 2 or state.graph._get_input_edges(collector_id, COLLECTION_FIELD):
+ return None
+ if any(edge.destination.field != ITEM_FIELD for edge in item_edges):
+ return None
+
+ item_edges_by_body = {edge.source.node_id: edge for edge in item_edges}
+ branches: list[tuple[str, str, str]] = []
+ for iterator_id in iterator_ids:
+ collection_edges = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
+ if len(collection_edges) != 1:
+ return None
+ collection_edge = collection_edges[0]
+ if collection_edge.destination.node_id != iterator_id or collection_edge.source.field != COLLECTION_FIELD:
+ return None
+
+ source_id = collection_edge.source.node_id
+ source = state.graph.get_node(source_id)
+ if isinstance(
+ source,
+ (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IfInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ ),
+ ):
+ return None
+ if state.graph._get_input_edges(source_id) or state.graph._get_output_edges(source_id) != [collection_edge]:
+ return None
+
+ iterator_item_edges = state.graph._get_output_edges(iterator_id, ITEM_FIELD)
+ if len(iterator_item_edges) != 1 or iterator_item_edges[0].source.node_id != iterator_id:
+ return None
+ if state.graph._get_output_edges(iterator_id) != iterator_item_edges:
+ return None
+
+ body_edge = iterator_item_edges[0]
+ if body_edge.source.field != ITEM_FIELD:
+ return None
+ body_id = body_edge.destination.node_id
+ if body_id in {source_id, iterator_id, collector_id} or body_id not in item_edges_by_body:
+ return None
+ body = state.graph.get_node(body_id)
+ if isinstance(
+ body,
+ (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IfInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ ),
+ ):
+ return None
+ body_input_edges = state.graph._get_input_edges(body_id)
+ if len(body_input_edges) != 1 or body_input_edges[0] != body_edge:
+ return None
+
+ collect_item_edge = item_edges_by_body[body_id]
+ if state.graph._get_output_edges(body_id) != [collect_item_edge]:
+ return None
+ branches.append((source_id, iterator_id, body_id))
+
+ if len({source_id for source_id, _iterator_id, _body_id in branches}) != 2:
+ return None
+ if len({iterator_id for _source_id, iterator_id, _body_id in branches}) != 2:
+ return None
+ if len({body_id for _source_id, _iterator_id, body_id in branches}) != 2:
+ return None
+
+ branches.sort(key=lambda branch: branch[0])
+ return _BodyIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+
+
+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."""
+
+ if (
+ state._legacy_snapshot_loaded
+ or len(state.graph.nodes) < 4
+ or len(state.graph.edges) != len(state.graph.nodes) - 1
+ ):
+ return None
+
+ iterator_ids = [node_id for node_id, node in state.graph.nodes.items() if isinstance(node, IterateInvocation)]
+ collector_ids = [node_id for node_id, node in state.graph.nodes.items() if isinstance(node, CollectInvocation)]
+ if len(iterator_ids) in {2, 3} and len(collector_ids) == 1:
+ if len(iterator_ids) == 2:
+ body_fan_in = state._get_body_iterate_collect_fan_in(iterator_ids, collector_ids[0])
+ if body_fan_in is not None:
+ return body_fan_in
+ return state._get_direct_iterate_collect_fan_in(iterator_ids, collector_ids[0])
+ if len(iterator_ids) != 1 or len(collector_ids) != 1:
+ return None
+ iterator_id = iterator_ids[0]
+ collector_id = collector_ids[0]
+
+ collection_edges = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
+ item_edges = state.graph._get_input_edges(collector_id, ITEM_FIELD)
+ if len(collection_edges) != 1 or len(item_edges) != 1:
+ return None
+ collection_edge = collection_edges[0]
+ item_edge = item_edges[0]
+ if collection_edge.source.field != COLLECTION_FIELD or item_edge.destination.field != ITEM_FIELD:
+ return None
+ if collection_edge.destination.node_id != iterator_id:
+ return None
+
+ body_id = item_edge.source.node_id
+ if body_id in {iterator_id, collector_id}:
+ return None
+ body = state.graph.get_node(body_id)
+ if isinstance(body, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)):
+ return None
+ body_input_edges = state.graph._get_input_edges(body_id)
+ if len(body_input_edges) != 1 or body_input_edges[0] != Edge(
+ source=EdgeConnection(node_id=iterator_id, field=ITEM_FIELD),
+ destination=EdgeConnection(node_id=body_id, field=body_input_edges[0].destination.field),
+ ):
+ return None
+ if body_input_edges[0].source.field != ITEM_FIELD:
+ return None
+
+ source_id = collection_edge.source.node_id
+ if source_id in {iterator_id, body_id, collector_id}:
+ return None
+ 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):
+ return None
+ if state.graph._get_output_edges(source_id) != [collection_edge]:
+ return None
+ if state.graph._get_output_edges(iterator_id) != [body_input_edges[0]]:
+ return None
+ if state.graph._get_output_edges(body_id) != [item_edge]:
+ return None
+ if state.graph._get_input_edges(collector_id) != [item_edge]:
+ return None
+
+ downstream_edges = state.graph._get_output_edges(collector_id, COLLECTION_FIELD)
+ if len(downstream_edges) != len(state.graph.nodes) - 4:
+ return None
+ downstream_ids: list[str] = []
+ for downstream_edge in downstream_edges:
+ downstream_id = downstream_edge.destination.node_id
+ downstream = state.graph.get_node(downstream_id)
+ if downstream_id in {source_id, iterator_id, body_id, collector_id} or isinstance(
+ downstream, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)
+ ):
+ return None
+ if state.graph._get_input_edges(downstream_id) != [downstream_edge]:
+ return None
+ downstream_ids.append(downstream_id)
+
+ return source_id, iterator_id, body_id, collector_id, tuple(downstream_ids)
+
+
+def _can_use_direct_iterate_collect_planner(state: "GraphExecutionState") -> bool:
+ """Use fresh planner ownership only for the exact direct stream shape."""
+
+ return state._get_direct_iterate_collect_nodes() is not None
+
+
+def _create_direct_execution_node_copy(
+ state: "GraphExecutionState", source_node_id: str, iteration_index: int = -1, iteration_path: tuple[int, ...] = ()
+) -> BaseInvocation:
+ source_node = state.graph.get_node(source_node_id)
+ new_node = source_node.model_copy(deep=True)
+ new_node.id = state._new_execution_node_id()
+ if isinstance(new_node, IterateInvocation):
+ new_node.index = iteration_index
+ if iteration_index >= 0 or isinstance(new_node, CollectInvocation):
+ new_node.use_cache = False
+ state._tx_add_execution_node(new_node)
+ state._add_execution_graph_node(new_node.id)
+ state._register_prepared_exec_node(new_node.id, source_node_id)
+ state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
+ return new_node
+
+
+def _attach_direct_execution_edges(
+ state: "GraphExecutionState", exec_node_id: str, edges: Iterable[Edge]
+) -> list[Edge]:
+ attached_edges = [
+ Edge(
+ source=edge.source,
+ destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
+ )
+ for edge in edges
+ ]
+ state._tx_add_execution_edges(attached_edges)
+ state._add_execution_graph_edges(attached_edges)
+ return attached_edges
+
+
+def _initialize_direct_execution_node(
+ state: "GraphExecutionState", exec_node_id: str, input_edges: Iterable[Edge]
+) -> None:
+ input_edges = list(input_edges)
+ state._tx_set_mapping(
+ state.indegree,
+ exec_node_id,
+ sum(1 for edge in input_edges if edge.source.node_id not in state.executed),
+ )
+ scheduler = state._scheduler()
+ assert state._is_generic_graph_scheduler(scheduler)
+ scheduler.register_node(exec_node_id)
+ state._enqueue_if_ready(exec_node_id)
+
+
+def _mark_direct_source_empty(state: "GraphExecutionState", source_node_id: str) -> None:
+ """Record an empty direct iterator source without entering the legacy materializer."""
+
+ state._tx_set_mapping(state.source_prepared_mapping, source_node_id, set())
+ state._mark_source_executed(source_node_id)
+ if isinstance(state.graph.get_node(source_node_id), IterateInvocation):
+ state._record_empty_iterate_stream(source_node_id)
+
+
+def _prepare_direct_iterate_collect_fan_in_unchecked(
+ state: "GraphExecutionState", fan_in: _DirectIterateCollectFanIn
+) -> None:
+ source_exec_ids: dict[str, str] = {}
+ for source_id, _iterator_id in fan_in.branches:
+ if source_id not in state.source_prepared_mapping:
+ source_node = state._create_direct_execution_node_copy(source_id)
+ state._initialize_direct_execution_node(source_node.id, ())
+ if source_id in state.executed:
+ source_exec_ids[source_id] = sorted(state.source_prepared_mapping[source_id])[0]
+
+ if len(source_exec_ids) != len(fan_in.branches):
+ return
+ if fan_in.collector_id in state.source_prepared_mapping:
+ return
+
+ iterator_exec_ids: list[tuple[str, str]] = []
+ collector_item_edges = {
+ edge.source.node_id: edge for edge in state.graph._get_input_edges(fan_in.collector_id, ITEM_FIELD)
+ }
+ for source_id, iterator_id in fan_in.branches:
+ collection_edge = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ collection = getattr(state.results[source_exec_ids[source_id]], collection_edge.source.field)
+ if not isinstance(collection, list):
+ raise ValueError("Direct Iterate collection source must produce a list")
+
+ for index in range(len(collection)):
+ iterator_node = state._create_direct_execution_node_copy(iterator_id, index, (index,))
+ attached_iterator_edges = state._attach_direct_execution_edges(
+ iterator_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=source_exec_ids[source_id], field=collection_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
+ )
+ ],
+ )
+ state._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
+ iterator_exec_ids.append((iterator_node.id, iterator_id))
+
+ if not collection:
+ state._mark_direct_source_empty(iterator_id)
+
+ collector_node = state._create_direct_execution_node_copy(fan_in.collector_id, iteration_path=())
+ collector_edges = [
+ Edge(
+ source=EdgeConnection(node_id=iterator_exec_id, field=ITEM_FIELD),
+ destination=EdgeConnection(node_id="", field=collector_item_edges[iterator_id].destination.field),
+ )
+ for iterator_exec_id, iterator_id in iterator_exec_ids
+ ]
+ attached_collector_edges = state._attach_direct_execution_edges(collector_node.id, collector_edges)
+ state._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+
+
+def _prepare_body_iterate_collect_fan_in_unchecked(
+ state: "GraphExecutionState", fan_in: _BodyIterateCollectFanIn
+) -> None:
+ source_exec_ids: dict[str, str] = {}
+ for source_id, _iterator_id, _body_id in fan_in.branches:
+ if source_id not in state.source_prepared_mapping:
+ source_node = state._create_direct_execution_node_copy(source_id)
+ state._initialize_direct_execution_node(source_node.id, ())
+ if source_id in state.executed:
+ source_exec_ids[source_id] = sorted(state.source_prepared_mapping[source_id])[0]
+
+ if len(source_exec_ids) != len(fan_in.branches):
+ return
+ if fan_in.collector_id in state.source_prepared_mapping:
+ return
+
+ collections: dict[str, list[Any]] = {}
+ for source_id, iterator_id, _body_id in fan_in.branches:
+ collection_edge = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ collection = getattr(state.results[source_exec_ids[source_id]], collection_edge.source.field)
+ if not isinstance(collection, list):
+ raise ValueError("Body Iterate collection source must produce a list")
+ collections[source_id] = collection
+
+ collector_item_edges = {
+ edge.source.node_id: edge for edge in state.graph._get_input_edges(fan_in.collector_id, ITEM_FIELD)
+ }
+ for source_id, iterator_id, body_id in fan_in.branches:
+ collection_edge = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ body_input_edge = state.graph._get_input_edges(body_id)[0]
+ collect_item_edge = collector_item_edges[body_id]
+ source_exec_id = source_exec_ids[source_id]
+ collection = collections[source_id]
+ for index in range(len(collection)):
+ iterator_node = state._create_direct_execution_node_copy(iterator_id, index, (index,))
+ attached_iterator_edges = state._attach_direct_execution_edges(
+ iterator_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
+ )
+ ],
+ )
+ state._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
+
+ body_node = state._create_direct_execution_node_copy(body_id, iteration_path=(index,))
+ attached_body_edges = state._attach_direct_execution_edges(
+ body_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
+ )
+ ],
+ )
+ state._initialize_direct_execution_node(body_node.id, attached_body_edges)
+
+ if not collection:
+ state._mark_direct_source_empty(iterator_id)
+ state._mark_direct_source_empty(body_id)
+
+ collector_node = state._create_direct_execution_node_copy(fan_in.collector_id, iteration_path=())
+ collector_edges: list[Edge] = []
+ for _source_id, _iterator_id, body_id in fan_in.branches:
+ collect_item_edge = collector_item_edges[body_id]
+ for body_exec_id in sorted(
+ state.source_prepared_mapping.get(body_id, set()),
+ key=lambda exec_id: state._get_iteration_path(exec_id),
+ ):
+ collector_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
+ )
+ )
+ attached_collector_edges = state._attach_direct_execution_edges(collector_node.id, collector_edges)
+ state._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+
+
+def _prepare_direct_iterate_collect(state: "GraphExecutionState") -> None:
+ """Expand the fresh direct stream shape atomically, without the legacy materializer."""
+
+ if state._apply_transaction is not None:
+ state._prepare_direct_iterate_collect_unchecked()
+ return
+
+ transaction = _ApplyTransaction()
+ object.__setattr__(state, "_apply_transaction", transaction)
+ try:
+ state._prepare_direct_iterate_collect_unchecked()
+ except Exception:
+ try:
+ transaction.rollback()
+ finally:
+ state._reset_apply_derived_caches()
+ state._rehydrate_ready_queues()
+ raise
+ finally:
+ object.__setattr__(state, "_apply_transaction", None)
+
+
+def _prepare_direct_iterate_collect_unchecked(state: "GraphExecutionState") -> None:
+ """Expand the direct stream shape while the caller owns mutation rollback."""
+
+ node_ids = state._get_direct_iterate_collect_nodes()
+ if node_ids is None:
+ return
+ if isinstance(node_ids, _BodyIterateCollectFanIn):
+ state._prepare_body_iterate_collect_fan_in_unchecked(node_ids)
+ return
+ if isinstance(node_ids, _DirectIterateCollectFanIn):
+ state._prepare_direct_iterate_collect_fan_in_unchecked(node_ids)
+ return
+ source_id, iterator_id, body_id, collector_id, downstream_ids = node_ids
+
+ if source_id not in state.source_prepared_mapping:
+ source_node = state._create_direct_execution_node_copy(source_id)
+ state._initialize_direct_execution_node(source_node.id, ())
+ return
+
+ if collector_id in state.source_prepared_mapping:
+ return
+
+ if source_id not in state.executed:
+ return
+ source_exec_id = next(iter(state.source_prepared_mapping[source_id]))
+ source_output = state.results[source_exec_id]
+ collection_edge = state.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ collection = getattr(source_output, collection_edge.source.field)
+ if not isinstance(collection, list):
+ raise ValueError("Direct Iterate collection source must produce a list")
+
+ iterator_exec_ids: list[str] = []
+ body_exec_ids: list[str] = []
+ body_input_edge = state.graph._get_input_edges(body_id)[0]
+ collect_item_edge = state.graph._get_input_edges(collector_id, ITEM_FIELD)[0]
+ for index in range(len(collection)):
+ iterator_node = state._create_direct_execution_node_copy(iterator_id, index, (index,))
+ iterator_edges = [
+ Edge(
+ source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
+ )
+ ]
+ attached_iterator_edges = state._attach_direct_execution_edges(iterator_node.id, iterator_edges)
+ state._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
+ iterator_exec_ids.append(iterator_node.id)
+
+ body_node = state._create_direct_execution_node_copy(body_id, iteration_path=(index,))
+ body_edges = [
+ Edge(
+ source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
+ )
+ ]
+ attached_body_edges = state._attach_direct_execution_edges(body_node.id, body_edges)
+ state._initialize_direct_execution_node(body_node.id, attached_body_edges)
+ body_exec_ids.append(body_node.id)
+
+ if not iterator_exec_ids:
+ state._mark_direct_source_empty(iterator_id)
+ state._mark_direct_source_empty(body_id)
+
+ collector_node = state._create_direct_execution_node_copy(collector_id, iteration_path=())
+ collector_edges = [
+ Edge(
+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
+ )
+ for body_exec_id in body_exec_ids
+ ]
+ attached_collector_edges = state._attach_direct_execution_edges(collector_node.id, collector_edges)
+ state._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+
+ for downstream_id in downstream_ids:
+ downstream_node = state._create_direct_execution_node_copy(downstream_id)
+ downstream_edge = state.graph._get_input_edges(downstream_id)[0]
+ attached_downstream_edges = state._attach_direct_execution_edges(
+ downstream_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=collector_node.id, field=downstream_edge.source.field),
+ destination=EdgeConnection(node_id="", field=downstream_edge.destination.field),
+ )
+ ],
+ )
+ state._initialize_direct_execution_node(downstream_node.id, attached_downstream_edges)
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
new file mode 100644
index 0000000000..3c89257b37
--- /dev/null
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -0,0 +1,1475 @@
+"""Compatibility materialization for graph execution state."""
+
+import itertools
+from typing import TYPE_CHECKING, Any, Iterable, Optional
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.fields import OutputScope
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.loops import (
+ LOOP_LINKAGE_FIELD,
+ ForInvocation,
+ ForInvocationOutput,
+ ForReturnInvocation,
+ LoopState,
+)
+from invokeai.app.services.shared.graph_models import Edge, EdgeConnection
+from invokeai.app.services.shared.graph_validation import (
+ COLLECTION_FIELD,
+ ITEM_FIELD,
+ CollectInvocation,
+ IterateInvocation,
+ _SupportedNestedForBody,
+ _SupportedNestedIterateBody,
+ copydeep,
+ get_output_field_scope,
+ nx,
+)
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+class _ExecutionMaterializer:
+ """Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
+
+ `GraphExecutionState.next()` calls into this helper when no prepared exec node is ready. The materializer chooses
+ the next source node that can be expanded, creates the corresponding exec nodes in the execution graph, wires their
+ inputs, and initializes their scheduler state.
+ """
+
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+ self._iteration_axes_by_source: dict[str, tuple[str, ...]] = {}
+
+ def _get_iteration_axes(self, source_node_id: str) -> tuple[str, ...]:
+ cached = self._iteration_axes_by_source.get(source_node_id)
+ if cached is not None:
+ return cached
+
+ axes = self._state._runtime()._get_ordered_iterator_sources(source_node_id)
+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
+ axes.append(source_node_id)
+ result = tuple(axes)
+ self._iteration_axes_by_source[source_node_id] = result
+ return result
+
+ def _get_known_iteration_path(
+ self,
+ iteration_index: int,
+ iteration_node_map: list[tuple[str, str]],
+ ) -> Optional[tuple[int, ...]]:
+ parent_paths: list[tuple[int, ...]] = []
+ parent_iteration_axes: list[tuple[str, ...]] = []
+ registry = self._state._prepared_registry()
+ for source_node_id, prepared_id in iteration_node_map:
+ parent_path = registry.get_iteration_path(prepared_id)
+ if parent_path is None:
+ return None
+ if parent_path:
+ parent_paths.append(parent_path)
+ parent_iteration_axes.append(self._get_iteration_axes(source_node_id))
+
+ unique_parent_paths = set(parent_paths)
+ paths_share_iteration_axes = len(set(parent_iteration_axes)) <= 1
+
+ # Materialized iteration boundaries use non-negative indexes; ordinary execution nodes use -1. Keeping this
+ # generic allows other scheduler-managed loop nodes to reuse the same path cache.
+ if iteration_index >= 0:
+ if len(unique_parent_paths) > 1 or not paths_share_iteration_axes:
+ return None
+ parent_path = next(iter(unique_parent_paths), ())
+ return (*parent_path, iteration_index)
+
+ if not unique_parent_paths:
+ return ()
+ if len(unique_parent_paths) == 1 and paths_share_iteration_axes:
+ return next(iter(unique_parent_paths))
+ return None
+
+ def _get_iterator_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
+ input_collection_edge = next(iter(self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)))
+ input_collection_prepared_node_id = next(
+ prepared_id
+ for source_id, prepared_id in iteration_node_map
+ if source_id == input_collection_edge.source.node_id
+ )
+ input_collection_output = self._state.results[input_collection_prepared_node_id]
+ input_collection = getattr(input_collection_output, input_collection_edge.source.field)
+ return len(input_collection)
+
+ def _get_for_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
+ input_collection_edges = self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)
+ if len(input_collection_edges) == 0:
+ node = self._state.graph.get_node(node_id)
+ assert isinstance(node, ForInvocation)
+ return len(node.collection)
+
+ input_collection_edge = input_collection_edges[0]
+ input_collection_prepared_node_id = next(
+ prepared_id
+ for source_id, prepared_id in iteration_node_map
+ if source_id == input_collection_edge.source.node_id
+ )
+ input_collection_output = self._state.results[input_collection_prepared_node_id]
+ input_collection = getattr(input_collection_output, input_collection_edge.source.field)
+ if not isinstance(input_collection, list):
+ raise ValueError("For collection input must be a list")
+ return len(input_collection)
+
+ def _get_new_node_iterations(
+ self, node: BaseInvocation, node_id: str, iteration_node_map: list[tuple[str, str]]
+ ) -> list[int]:
+ if isinstance(node, IterateInvocation):
+ iteration_count = self._get_iterator_iteration_count(node_id, iteration_node_map)
+ if iteration_count == 0:
+ return []
+ return list(range(iteration_count))
+
+ if isinstance(node, ForInvocation):
+ iteration_count = self._get_for_iteration_count(node_id, iteration_node_map)
+ if iteration_count == 0:
+ return []
+ return [0]
+
+ return [-1]
+
+ def _build_execution_edges(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[Edge]:
+ return self._build_execution_edges_for_fields(node_id, iteration_node_map)
+
+ def _build_execution_edges_for_fields(
+ self,
+ node_id: str,
+ iteration_node_map: list[tuple[str, str]],
+ input_fields: Optional[set[str]] = None,
+ ) -> list[Edge]:
+ input_edges = self._state.graph._get_input_edges(node_id)
+ new_edges: list[Edge] = []
+ for edge in input_edges:
+ if input_fields is not None and edge.destination.field not in input_fields:
+ continue
+ matching_inputs = [
+ prepared_id for source_id, prepared_id in iteration_node_map if source_id == edge.source.node_id
+ ]
+ for input_node_id in matching_inputs:
+ new_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=input_node_id, field=edge.source.field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+ return new_edges
+
+ def _has_unmaterializable_for_final_input(self, node_id: str) -> bool:
+ final_for_source_ids = set()
+ for edge in self._state.graph._get_input_edges(node_id):
+ source_node = self._state.graph.get_node(edge.source.node_id)
+ if not isinstance(source_node, ForInvocation):
+ continue
+ if get_output_field_scope(source_node, edge.source.field) == OutputScope.Final:
+ final_for_source_ids.add(edge.source.node_id)
+
+ return any(not self._state._all_for_contexts_finalized(source_for_id) for source_for_id in final_for_source_ids)
+
+ def _create_execution_node_copy(
+ self, node: BaseInvocation, node_id: str, iteration_index: int, *, deep_copy: bool = True
+ ) -> BaseInvocation:
+ new_node = node.model_copy(deep=deep_copy)
+ new_node.id = self._state._new_execution_node_id()
+
+ if isinstance(new_node, IterateInvocation):
+ new_node.index = iteration_index
+ if isinstance(new_node, ForInvocation):
+ new_node.index = iteration_index
+
+ # Scheduler-managed iteration boundaries and collectors are cheaper to execute than to hash, especially when
+ # their inputs contain large collections. Loop body nodes retain their normal cache behavior.
+ if iteration_index >= 0 or isinstance(new_node, CollectInvocation):
+ new_node.use_cache = False
+
+ self._state._tx_add_execution_node(new_node)
+ self._state._add_execution_graph_node(new_node.id)
+ self._state._register_prepared_exec_node(new_node.id, node_id)
+ return new_node
+
+ def _create_empty_for_final_output(
+ self,
+ source_for_id: str,
+ node: "ForInvocation",
+ iteration_node_map: list[tuple[str, str]],
+ ) -> str:
+ new_node = self._create_execution_node_copy(node, source_for_id, -1, deep_copy=False)
+ assert isinstance(new_node, ForInvocation)
+ new_edges = self._build_execution_edges(source_for_id, iteration_node_map)
+ iteration_path = self._get_known_iteration_path(-1, iteration_node_map)
+ if iteration_path is not None:
+ self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
+ self._attach_execution_edges(new_node.id, new_edges)
+ self._state._runtime().prepare_inputs(new_node)
+
+ initial_state = copydeep(new_node.state or LoopState())
+ self._state._tx_set_attr(new_node, "collection", [])
+ self._state._tx_set_attr(new_node, "state", initial_state)
+
+ self._state._tx_set_mapping(
+ self._state.results,
+ new_node.id,
+ ForInvocationOutput(
+ loop_linkage=LOOP_LINKAGE_FIELD,
+ item=None,
+ index=-1,
+ total=0,
+ state=initial_state,
+ output_collection=[],
+ final_state=initial_state,
+ ),
+ )
+ self._state._tx_add_set(self._state.executed, new_node.id)
+ self._state._set_prepared_exec_state(new_node.id, "executed")
+
+ return new_node.id
+
+ def _mark_empty_for_complete(self, source_for_id: str) -> None:
+ prepared_for_ids = [
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_for_id)
+ if isinstance(self._state.execution_graph.get_node(prepared_id), ForInvocation)
+ and self._state.execution_graph.get_node(prepared_id).index == -1
+ ]
+ assert prepared_for_ids, f"Empty For '{source_for_id}' did not create a final execution node"
+ for prepared_for_id in prepared_for_ids:
+ self._state._mark_loop_context_finalized(source_for_id, prepared_for_id)
+
+ self._state._mark_for_source_complete(source_for_id)
+
+ def create_for_iteration(
+ self,
+ source_for_id: str,
+ iteration_index: int,
+ collection: list[Any],
+ state: "LoopState",
+ iteration_path: tuple[int, ...],
+ ) -> str:
+ node = self._state.graph.get_node(source_for_id)
+ if not isinstance(node, ForInvocation):
+ raise TypeError(f"Expected source ForInvocation, got {type(node).__name__}")
+
+ new_node = self._create_execution_node_copy(node, source_for_id, iteration_index, deep_copy=False)
+ assert isinstance(new_node, ForInvocation)
+ self._state._tx_set_attr(new_node, "collection", copydeep(collection))
+ self._state._tx_set_attr(new_node, "state", copydeep(state))
+ self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
+ self._initialize_execution_node(new_node.id)
+ return new_node.id
+
+ def create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
+ graph = self._state._get_source_graph_flat()
+ execution_graph = self._state._get_execution_graph_flat()
+ nested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)
+ if nested_body is not None:
+ return self._create_nested_iterate_body_iteration(
+ source_for_id, prepared_for_id, graph, execution_graph, nested_body
+ )
+ nested_for_body = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
+ if nested_for_body is not None:
+ return self._create_nested_for_body_iteration(
+ source_for_id, prepared_for_id, graph, execution_graph, nested_for_body
+ )
+
+ body_path_to_return = self._state.graph._get_for_body_path_to_return(source_for_id, graph)
+ if body_path_to_return is None:
+ return None
+
+ body_path_nodes, source_return_id = body_path_to_return
+ source_to_prepared = {source_for_id: prepared_for_id}
+ prepared_return_id: Optional[str] = None
+
+ for source_node_id in nx.topological_sort(graph):
+ if source_node_id not in body_path_nodes:
+ continue
+
+ node = self._state.graph.get_node(source_node_id)
+ new_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_node_id):
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ if prepared_source_id is None:
+ prepared_source_id = self.get_iteration_node(
+ edge.source.node_id,
+ graph,
+ execution_graph,
+ [prepared_for_id],
+ )
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize For body input {edge}: no prepared source node is available"
+ )
+ new_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+
+ new_node = self._create_execution_node_copy(node, source_node_id, -1)
+ source_to_prepared[source_node_id] = new_node.id
+ self._state._prepared_registry().set_iteration_path(
+ new_node.id, self._state._get_iteration_path(prepared_for_id)
+ )
+ self._state._discard_source_executed(source_node_id)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
+
+ if source_node_id == source_return_id:
+ prepared_return_id = new_node.id
+
+ return prepared_return_id
+
+ def _is_deferred_nested_for_return(self, node_id: str, graph: "nx.DiGraph") -> bool:
+ return any(
+ (nested_body := self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)) is not None
+ and nested_body.outer_return_id == node_id
+ for source_for_id, source_node in self._state.graph.nodes.items()
+ if isinstance(source_node, ForInvocation)
+ )
+
+ def _get_final_prepared_for_id(self, source_for_id: str, parent_iteration_path: tuple[int, ...]) -> str:
+ self._state._get_prepared_for_index()
+ assert self._state._final_prepared_for_index is not None
+ prepared_for_id = self._state._final_prepared_for_index.get((source_for_id, parent_iteration_path))
+ if prepared_for_id is None:
+ raise RuntimeError(f"Unable to find finalized nested For '{source_for_id}' for {parent_iteration_path}")
+ return prepared_for_id
+
+ def create_nested_for_return(self, inner_for_id: str, prepared_inner_for_id: str) -> Optional[str]:
+ graph = self._state._get_source_graph_flat()
+ inner_iteration_path = self._state._get_iteration_path(prepared_inner_for_id)
+ outer_for_id: Optional[str] = None
+ nested_body: Optional[_SupportedNestedForBody] = None
+ for source_for_id, source_node in self._state.graph.nodes.items():
+ if not isinstance(source_node, ForInvocation):
+ continue
+ candidate = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)
+ if candidate is not None and inner_for_id in candidate.inner_for_ids:
+ outer_for_id = source_for_id
+ nested_body = candidate
+ break
+ if outer_for_id is None or nested_body is None:
+ return None
+
+ prepared_inner_for = self._state.execution_graph.get_node(prepared_inner_for_id)
+ outer_iteration_path = (
+ inner_iteration_path
+ if isinstance(prepared_inner_for, ForInvocation) and prepared_inner_for.index == -1
+ else inner_iteration_path[:-1]
+ )
+ prepared_outer_for_id = next(
+ (
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(outer_for_id)
+ if self._state._get_iteration_path(prepared_id) == outer_iteration_path
+ ),
+ None,
+ )
+ if prepared_outer_for_id is None:
+ raise RuntimeError("Unable to rematerialize nested ForReturn: owning outer For is unavailable")
+
+ source_return_id = nested_body.outer_return_id
+ existing_return_ids = [
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_return_id)
+ if self._state._get_iteration_path(prepared_id) == outer_iteration_path
+ ]
+ if len(existing_return_ids) > 1:
+ raise RuntimeError(
+ f"Multiple nested ForReturn executions exist for {source_return_id} at {outer_iteration_path}"
+ )
+ if existing_return_ids:
+ return existing_return_ids[0]
+
+ continuation_nodes = self._state.graph._get_for_nested_for_continuation_nodes(nested_body)
+ prepared_inner_ids: dict[str, str] = {inner_for_id: prepared_inner_for_id}
+ if any(
+ not self._state._is_loop_context_finalized(inner_id, outer_iteration_path)
+ for inner_id in nested_body.inner_for_ids
+ ):
+ return None
+ for inner_id in nested_body.inner_for_ids:
+ if inner_id in prepared_inner_ids:
+ continue
+ prepared_inner_ids[inner_id] = self._get_final_prepared_for_id(inner_id, outer_iteration_path)
+ source_to_prepared: dict[str, str] = {
+ outer_for_id: prepared_outer_for_id,
+ **prepared_inner_ids,
+ }
+ for source_node_id in nx.topological_sort(graph):
+ if source_node_id not in continuation_nodes:
+ continue
+
+ new_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_node_id):
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ if prepared_source_id is None:
+ prepared_source_id = self.get_iteration_node(
+ edge.source.node_id,
+ graph,
+ self._state._get_execution_graph_flat(),
+ [prepared_outer_for_id],
+ )
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize nested For continuation input {edge}: no prepared source node is available"
+ )
+ new_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+
+ new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
+ source_to_prepared[source_node_id] = new_node.id
+ self._state._prepared_registry().set_iteration_path(new_node.id, outer_iteration_path)
+ self._state._discard_source_executed(source_node_id)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
+
+ self._state._discard_source_executed(source_return_id)
+ return_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_return_id):
+ if edge.destination.field == "output":
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ source_field = edge.source.field
+ elif edge.destination.field == "state":
+ prepared_source_id = prepared_outer_for_id
+ source_field = edge.source.field
+ elif edge.destination.field == "continue_condition":
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ source_field = edge.source.field
+ else:
+ raise RuntimeError(f"Unable to rematerialize nested ForReturn input {edge}")
+ if prepared_source_id is None:
+ raise RuntimeError(f"Unable to rematerialize nested ForReturn input {edge}")
+ return_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=source_field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+
+ prepared_return_node = self._create_execution_node_copy(
+ self._state.graph.get_node(source_return_id), source_return_id, -1
+ )
+ self._state._prepared_registry().set_iteration_path(prepared_return_node.id, outer_iteration_path)
+ attached_return_edges = self._attach_execution_edges(prepared_return_node.id, return_edges)
+ self._initialize_execution_node(prepared_return_node.id, attached_return_edges)
+ return prepared_return_node.id
+
+ def _create_nested_for_body_iteration(
+ self,
+ source_for_id: str,
+ prepared_for_id: str,
+ graph: "nx.DiGraph",
+ execution_graph: "nx.DiGraph",
+ nested_body: _SupportedNestedForBody,
+ ) -> Optional[str]:
+ """Materialize one nested-For body at the owning outer iteration path.
+
+ The source graph is shaped as ``outer For -> inner For(s) -> outer ForReturn``. Existing execution nodes
+ are reused at the current path; missing ordinary body nodes are copied, then each inner For is allowed to
+ advance independently before the outer return is rematerialized.
+ """
+ body_path_nodes = nested_body.body_path_nodes
+ source_return_id = nested_body.outer_return_id
+ prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)
+ outer_iteration_path = self._state._get_iteration_path(prepared_for_id)
+ if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:
+ outer_iteration_path = (
+ *self._state._get_for_parent_iteration_path(prepared_for_id),
+ prepared_for_node.index,
+ )
+
+ source_to_prepared: dict[str, str] = {source_for_id: prepared_for_id}
+ for source_node_id in nx.topological_sort(graph):
+ if source_node_id not in body_path_nodes or source_node_id in {
+ *nested_body.inner_for_ids,
+ source_return_id,
+ }:
+ continue
+ if not any(nx.has_path(graph, source_node_id, inner_for_id) for inner_for_id in nested_body.inner_for_ids):
+ continue
+
+ existing_prepared_ids = [
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_node_id)
+ if self._state._get_iteration_path(prepared_id) == outer_iteration_path
+ ]
+ if len(existing_prepared_ids) == 1:
+ source_to_prepared[source_node_id] = existing_prepared_ids[0]
+ continue
+
+ new_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_node_id):
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ if prepared_source_id is None:
+ prepared_source_id = self.get_iteration_node(
+ edge.source.node_id, graph, execution_graph, [prepared_for_id]
+ )
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize nested For input {edge}: no prepared source node is available"
+ )
+ new_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+
+ new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
+ source_to_prepared[source_node_id] = new_node.id
+ self._state._prepared_registry().set_iteration_path(new_node.id, outer_iteration_path)
+ self._state._discard_source_executed(source_node_id)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
+
+ for body_node_id in body_path_nodes:
+ if body_node_id in nested_body.inner_for_ids or not any(
+ nx.has_path(graph, body_node_id, inner_for_id) for inner_for_id in nested_body.inner_for_ids
+ ):
+ self._state._discard_source_executed(body_node_id)
+ self._state._discard_source_executed(source_return_id)
+
+ for source_inner_for_id in nested_body.inner_for_ids:
+ existing_prepared_ids = [
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_inner_for_id)
+ if self._state._get_for_parent_iteration_path(prepared_id) == outer_iteration_path
+ ]
+ if existing_prepared_ids:
+ continue
+
+ inner_input_map: list[tuple[str, str]] = []
+ for edge in self._state.graph._get_input_edges(source_inner_for_id):
+ prepared_source_id = source_to_prepared.get(edge.source.node_id)
+ if prepared_source_id is None:
+ prepared_source_id = self.get_iteration_node(
+ edge.source.node_id, graph, execution_graph, [prepared_for_id]
+ )
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize nested For input {edge}: no prepared source node is available"
+ )
+ inner_input_map.append((edge.source.node_id, prepared_source_id))
+
+ if any(prepared_source_id not in self._state.results for _, prepared_source_id in inner_input_map):
+ return None
+
+ self._state._discard_source_executed(source_inner_for_id)
+ inner_prepared_ids = self.create_execution_node(
+ source_inner_for_id, inner_input_map, iteration_path=outer_iteration_path
+ )
+ if not inner_prepared_ids:
+ self._mark_source_node_empty(source_inner_for_id)
+ elif all(
+ isinstance(self._state.execution_graph.get_node(inner_id), ForInvocation)
+ and self._state.execution_graph.get_node(inner_id).index == -1
+ for inner_id in inner_prepared_ids
+ ):
+ self._mark_empty_for_complete(source_inner_for_id)
+ for inner_prepared_id in inner_prepared_ids:
+ self.create_nested_for_return(source_inner_for_id, inner_prepared_id)
+ else:
+ for inner_prepared_id in inner_prepared_ids:
+ self.create_for_body_iteration(
+ source_for_id=source_inner_for_id,
+ prepared_for_id=inner_prepared_id,
+ )
+
+ return None
+
+ def _create_nested_iterate_body_iteration(
+ self,
+ source_for_id: str,
+ prepared_for_id: str,
+ graph: "nx.DiGraph",
+ execution_graph: "nx.DiGraph",
+ nested_body: _SupportedNestedIterateBody,
+ ) -> Optional[str]:
+ body_path_nodes = nested_body.body_path_nodes
+ source_return_id = nested_body.return_node_id
+ source_iterate_id = nested_body.iterate_node_id
+ source_collect_id = nested_body.collect_node_id
+ prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)
+ outer_iteration_path = self._state._get_iteration_path(prepared_for_id)
+ if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:
+ outer_iteration_path = (
+ *self._state._get_for_parent_iteration_path(prepared_for_id),
+ prepared_for_node.index,
+ )
+ source_to_prepared: dict[str, str] = {source_for_id: prepared_for_id}
+ inner_prepared_by_source: dict[tuple[str, str], str] = {}
+
+ def resolve_outer_input(source_node_id: str) -> Optional[str]:
+ prepared_source_id = source_to_prepared.get(source_node_id)
+ if prepared_source_id is not None:
+ return prepared_source_id
+ return self.get_iteration_node(source_node_id, graph, execution_graph, [prepared_for_id])
+
+ def create_body_copy(source_node_id: str, input_resolver, iteration_path: tuple[int, ...]) -> str:
+ new_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_node_id):
+ prepared_source_id = input_resolver(edge.source.node_id)
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize For body input {edge}: no prepared source node is available"
+ )
+ new_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=edge.source.field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+
+ new_node = self._create_execution_node_copy(self._state.graph.get_node(source_node_id), source_node_id, -1)
+ self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
+ return new_node.id
+
+ def get_existing_body_node(source_node_id: str) -> Optional[str]:
+ matching_ids = [
+ prepared_id
+ for prepared_id in self._state._prepared_registry().get_prepared_ids(source_node_id)
+ if self._state._get_iteration_path(prepared_id) == outer_iteration_path
+ ]
+ if len(matching_ids) == 1:
+ return matching_ids[0]
+ return None
+
+ for source_node_id in nx.topological_sort(graph):
+ if source_node_id not in body_path_nodes or source_node_id in {
+ source_iterate_id,
+ source_collect_id,
+ source_return_id,
+ }:
+ continue
+ if not nx.has_path(graph, source_node_id, source_iterate_id):
+ continue
+ source_to_prepared[source_node_id] = get_existing_body_node(source_node_id) or create_body_copy(
+ source_node_id, resolve_outer_input, outer_iteration_path
+ )
+
+ iterate_input_map: list[tuple[str, str]] = []
+ for edge in self._state.graph._get_input_edges(source_iterate_id):
+ prepared_source_id = resolve_outer_input(edge.source.node_id)
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize For body input {edge}: no prepared source node is available"
+ )
+ iterate_input_map.append((edge.source.node_id, prepared_source_id))
+
+ if any(prepared_source_id not in self._state.results for _, prepared_source_id in iterate_input_map):
+ return None
+
+ self._state._discard_source_executed(source_iterate_id)
+ inner_prepared_ids = self.create_execution_node(
+ source_iterate_id, iterate_input_map, iteration_path=outer_iteration_path
+ )
+ if not inner_prepared_ids:
+ self._mark_source_node_empty(source_iterate_id, outer_iteration_path)
+
+ for inner_prepared_id in inner_prepared_ids:
+ inner_iteration_path = self._state._get_iteration_path(inner_prepared_id)
+ for source_node_id in nx.topological_sort(graph):
+ if source_node_id not in body_path_nodes:
+ continue
+ if source_node_id in {source_iterate_id, source_collect_id, source_return_id}:
+ continue
+ if nx.has_path(graph, source_node_id, source_iterate_id):
+ continue
+ if not nx.has_path(graph, source_iterate_id, source_node_id):
+ continue
+
+ def resolve_inner_input(
+ input_source_node_id: str, current_inner_prepared_id: str = inner_prepared_id
+ ) -> Optional[str]:
+ if input_source_node_id == source_iterate_id:
+ return current_inner_prepared_id
+ prepared_source_id = source_to_prepared.get(input_source_node_id)
+ if prepared_source_id is not None:
+ return prepared_source_id
+ prepared_source_id = inner_prepared_by_source.get((input_source_node_id, current_inner_prepared_id))
+ if prepared_source_id is not None:
+ return prepared_source_id
+ return self.get_iteration_node(
+ input_source_node_id, graph, execution_graph, [current_inner_prepared_id]
+ )
+
+ self._state._discard_source_executed(source_node_id)
+ prepared_id = create_body_copy(source_node_id, resolve_inner_input, inner_iteration_path)
+ inner_prepared_by_source[(source_node_id, inner_prepared_id)] = prepared_id
+
+ if not inner_prepared_ids:
+ for source_node_id in body_path_nodes:
+ if source_node_id in {source_iterate_id, source_collect_id, source_return_id}:
+ continue
+ if nx.has_path(graph, source_iterate_id, source_node_id):
+ self._mark_source_node_empty(source_node_id, outer_iteration_path)
+
+ collect_item_edge = self._state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]
+ collect_edges: list[Edge] = []
+ for inner_prepared_id in inner_prepared_ids:
+ prepared_source_id = inner_prepared_by_source.get((collect_item_edge.source.node_id, inner_prepared_id))
+ if prepared_source_id is None and collect_item_edge.source.node_id == source_iterate_id:
+ prepared_source_id = inner_prepared_id
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize For body input {collect_item_edge}: no prepared source node is available"
+ )
+ collect_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=collect_item_edge.source.field),
+ destination=EdgeConnection(node_id="", field=ITEM_FIELD),
+ )
+ )
+
+ self._state._discard_source_executed(source_collect_id)
+ collect_node = self._state.graph.get_node(source_collect_id)
+ prepared_collect_node = self._create_execution_node_copy(collect_node, source_collect_id, -1)
+ self._state._prepared_registry().set_iteration_path(prepared_collect_node.id, outer_iteration_path)
+ attached_collect_edges = self._attach_execution_edges(prepared_collect_node.id, collect_edges)
+ self._initialize_execution_node(prepared_collect_node.id, attached_collect_edges)
+
+ return_edges: list[Edge] = []
+ for edge in self._state.graph._get_input_edges(source_return_id):
+ if edge.destination.field == "output":
+ prepared_source_id = prepared_collect_node.id
+ source_field = COLLECTION_FIELD
+ else:
+ prepared_source_id = resolve_outer_input(edge.source.node_id)
+ source_field = edge.source.field
+ if prepared_source_id is None:
+ raise RuntimeError(
+ f"Unable to rematerialize For body input {edge}: no prepared source node is available"
+ )
+ return_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=prepared_source_id, field=source_field),
+ destination=EdgeConnection(node_id="", field=edge.destination.field),
+ )
+ )
+ self._state._discard_source_executed(source_return_id)
+ prepared_return_node = self._create_execution_node_copy(
+ self._state.graph.get_node(source_return_id), source_return_id, -1
+ )
+ self._state._prepared_registry().set_iteration_path(prepared_return_node.id, outer_iteration_path)
+ attached_return_edges = self._attach_execution_edges(prepared_return_node.id, return_edges)
+ self._initialize_execution_node(prepared_return_node.id, attached_return_edges)
+ return prepared_return_node.id
+
+ def _attach_execution_edges(self, exec_node_id: str, new_edges: list[Edge]) -> list[Edge]:
+ attached_edges = [
+ Edge(
+ source=edge.source,
+ destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
+ )
+ for edge in new_edges
+ ]
+ self._state._tx_add_execution_edges(attached_edges)
+ self._state._add_execution_graph_edges(attached_edges)
+ return attached_edges
+
+ def _initialize_execution_node(self, exec_node_id: str, input_edges: Optional[list[Edge]] = None) -> None:
+ inputs = input_edges if input_edges is not None else self._state.execution_graph._get_input_edges(exec_node_id)
+ unmet = sum(1 for edge in inputs if edge.source.node_id not in self._state.executed)
+ self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
+ scheduler = self._state._scheduler()
+ # Resolve a known conditional before registering its generic plan node so
+ # generic retirement can release unselected prerequisites without
+ # mutating the append-only execution graph.
+ if self._state._is_generic_graph_scheduler(scheduler):
+ self._state._try_resolve_if_node(exec_node_id)
+ if self._state._is_pending_if(exec_node_id):
+ self._state._tx_add_set(self._state._pending_if_exec_nodes, exec_node_id)
+ return
+ scheduler.register_node(exec_node_id)
+ else:
+ self._state._try_resolve_if_node(exec_node_id, enqueue=False)
+ if self._state._is_pending_if(exec_node_id):
+ self._state._tx_add_set(self._state._pending_if_exec_nodes, exec_node_id)
+ return
+ self._state._enqueue_if_ready(exec_node_id)
+
+ def _get_collect_iteration_group_key(self, edge: Edge, sibling_depth: Optional[int] = None) -> tuple[int, ...]:
+ path = self._state._get_iteration_path(edge.source.node_id)
+ source_node = self._state.execution_graph.get_node(edge.source.node_id)
+ if (
+ isinstance(source_node, ForInvocation)
+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
+ ):
+ return self._state._get_for_parent_iteration_path(edge.source.node_id)
+ if edge.destination.field == ITEM_FIELD:
+ if isinstance(source_node, ForInvocation) and source_node.index == -1:
+ return path
+ # Ragged siblings need the deepest path to identify their shared outer group.
+ depth = len(path) if sibling_depth is None else sibling_depth
+ return path[: max(depth - 1, 0)]
+ return path
+
+ def _get_collect_source_iterator_ids(self, source_node_id: str) -> list[str]:
+ iterator_node_ids = self.get_node_iterators(source_node_id)
+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
+ iterator_node_ids.append(source_node_id)
+ return iterator_node_ids
+
+ def _get_ordered_prepared_nodes_for_source(self, source_node_id: str) -> list[str]:
+ return sorted(
+ self._get_prepared_nodes_for_source(source_node_id),
+ key=lambda exec_node_id: (self._state._get_iteration_path(exec_node_id), exec_node_id),
+ )
+
+ def _get_ordered_prepared_nodes_for_edge(self, edge: Edge) -> list[str]:
+ prepared_nodes = self._get_ordered_prepared_nodes_for_source(edge.source.node_id)
+ source_node = self._state.graph.get_node(edge.source.node_id)
+ if not (
+ isinstance(source_node, ForInvocation)
+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
+ ):
+ return prepared_nodes
+
+ final_nodes_by_parent_path: dict[tuple[int, ...], str] = {}
+ for prepared_id in prepared_nodes:
+ parent_path = self._state._get_for_parent_iteration_path(prepared_id)
+ previous_id = final_nodes_by_parent_path.get(parent_path)
+ if previous_id is None:
+ final_nodes_by_parent_path[parent_path] = prepared_id
+ continue
+ previous_node = self._state.execution_graph.get_node(previous_id)
+ prepared_node = self._state.execution_graph.get_node(prepared_id)
+ assert isinstance(previous_node, ForInvocation)
+ assert isinstance(prepared_node, ForInvocation)
+ if prepared_node.index > previous_node.index:
+ final_nodes_by_parent_path[parent_path] = prepared_id
+
+ return [final_nodes_by_parent_path[parent_path] for parent_path in sorted(final_nodes_by_parent_path)]
+
+ def _get_prepared_edge_iteration_path(self, edge: Edge, prepared_id: str) -> tuple[int, ...]:
+ source_node = self._state.graph.get_node(edge.source.node_id)
+ if (
+ isinstance(source_node, ForInvocation)
+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
+ ):
+ return self._state._get_for_parent_iteration_path(prepared_id)
+ return self._state._get_iteration_path(prepared_id)
+
+ def _get_iterator_input_iteration_paths(self, iterator_node_id: str) -> set[tuple[int, ...]]:
+ iteration_paths: set[tuple[int, ...]] = set()
+ for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD):
+ source_node_id = edge.source.node_id
+ prepared_nodes = self._get_ordered_prepared_nodes_for_source(source_node_id)
+ iteration_paths.update(
+ self._get_prepared_edge_iteration_path(edge, prepared_id) for prepared_id in prepared_nodes
+ )
+ return iteration_paths
+
+ def _get_collect_candidate_group_keys(self, edge: Edge) -> set[tuple[int, ...]]:
+ source_node_id = edge.source.node_id
+ iterator_node_ids = self._get_collect_source_iterator_ids(source_node_id)
+
+ group_depth = len(iterator_node_ids)
+ if edge.destination.field == ITEM_FIELD:
+ group_depth = max(group_depth - 1, 0)
+
+ group_keys: set[tuple[int, ...]] = set()
+ for iterator_node_id in iterator_node_ids:
+ prepared_nodes = self._get_ordered_prepared_nodes_for_source(iterator_node_id)
+ # Prepared paths use the active group depth. Input paths stay full to preserve scope across collectors.
+ if prepared_nodes and group_depth:
+ group_keys.update(
+ iteration_path[:group_depth]
+ for prepared_id in prepared_nodes
+ if len(iteration_path := self._state._get_iteration_path(prepared_id)) >= group_depth
+ )
+ group_keys.update(self._get_iterator_input_iteration_paths(iterator_node_id))
+
+ if group_keys:
+ return group_keys
+ if group_depth == 0:
+ return {()}
+ return set()
+
+ def _get_collect_iteration_mapping_groups(
+ self, input_edges: list[Edge]
+ ) -> list[tuple[tuple[int, ...], list[tuple[str, str]]]]:
+ prepared_inputs: list[tuple[Edge, str, str, tuple[int, ...]]] = []
+ group_keys: set[tuple[int, ...]] = set()
+ for edge in input_edges:
+ group_keys.update(self._get_collect_candidate_group_keys(edge))
+ prepared_nodes = self._get_ordered_prepared_nodes_for_edge(edge)
+ sibling_depth = max(
+ (len(self._get_prepared_edge_iteration_path(edge, prepared_id)) for prepared_id in prepared_nodes),
+ default=0,
+ )
+ for prepared_id in prepared_nodes:
+ prepared_edge = Edge(
+ source=EdgeConnection(node_id=prepared_id, field=edge.source.field),
+ destination=edge.destination,
+ )
+ group_key = self._get_collect_iteration_group_key(prepared_edge, sibling_depth)
+ group_keys.add(group_key)
+ prepared_inputs.append(
+ (
+ prepared_edge,
+ edge.source.node_id,
+ prepared_id,
+ self._get_prepared_edge_iteration_path(edge, prepared_id),
+ )
+ )
+
+ if not group_keys:
+ group_keys.add(())
+
+ final_group_keys = sorted(
+ group_key
+ for group_key in group_keys
+ if not any(
+ group_key != other_group_key and other_group_key[: len(group_key)] == group_key
+ for other_group_key in group_keys
+ )
+ )
+
+ return [
+ (
+ group_key,
+ [
+ (source_node_id, prepared_id)
+ for prepared_edge, source_node_id, prepared_id, iteration_path in prepared_inputs
+ if (
+ prepared_edge.destination.field == ITEM_FIELD
+ and (
+ group_key[: len(iteration_path)] == iteration_path
+ or iteration_path[: len(group_key)] == group_key
+ )
+ )
+ or (
+ prepared_edge.destination.field != ITEM_FIELD
+ and group_key[: len(iteration_path)] == iteration_path
+ )
+ ],
+ )
+ for group_key in final_group_keys
+ ]
+
+ def _get_parent_iteration_mappings_without_iterators(
+ self, next_node_id: str, input_edges: Optional[list[Edge]] = None
+ ) -> list[list[tuple[str, str]]]:
+ input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)
+ parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))
+ parent_prepared_nodes = {
+ node_id: list(
+ dict.fromkeys(
+ (prepared_id, self._get_prepared_edge_iteration_path(edge, prepared_id))
+ for edge in input_edges
+ if edge.source.node_id == node_id
+ for prepared_id in self._get_ordered_prepared_nodes_for_edge(edge)
+ )
+ )
+ for node_id in parent_node_ids
+ }
+ all_iteration_paths = {
+ iteration_path
+ for prepared_nodes in parent_prepared_nodes.values()
+ for _prepared_id, iteration_path in prepared_nodes
+ if iteration_path != ()
+ }
+ iteration_paths = sorted(
+ iteration_path
+ for iteration_path in all_iteration_paths
+ if not any(
+ iteration_path != other_path and other_path[: len(iteration_path)] == iteration_path
+ for other_path in all_iteration_paths
+ )
+ )
+ if not iteration_paths:
+ iteration_paths = [()]
+
+ mappings: list[list[tuple[str, str]]] = []
+ for iteration_path in iteration_paths:
+ mapping: list[tuple[str, str]] = []
+ for node_id, prepared_nodes in parent_prepared_nodes.items():
+ matching_prepared = next(
+ iter(
+ sorted(
+ (
+ (prepared_id, prepared_path)
+ for prepared_id, prepared_path in prepared_nodes
+ if iteration_path[: len(prepared_path)] == prepared_path
+ ),
+ key=lambda prepared: (-len(prepared[1]), prepared[0]),
+ )
+ ),
+ None,
+ )
+ if matching_prepared is None:
+ break
+ mapping.append((node_id, matching_prepared[0]))
+ if len(mapping) == len(parent_node_ids):
+ mappings.append(mapping)
+ return mappings
+
+ def _mark_source_node_empty(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> None:
+ self._state._tx_set_mapping(self._state.source_prepared_mapping, source_node_id, set())
+ self._state._mark_source_executed(source_node_id)
+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
+ self._state._record_empty_iterate_stream(source_node_id, iteration_path)
+
+ def _index_prepared_nodes_by_iteration_path(
+ self, prepared_nodes: set[str], input_edges: list[Edge]
+ ) -> dict[tuple[int, ...], list[str]]:
+ prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]] = {}
+ for prepared_id in prepared_nodes:
+ iteration_path = self._get_prepared_edge_iteration_path(input_edges[0], prepared_id)
+ prepared_nodes_by_iteration_path.setdefault(iteration_path, []).append(prepared_id)
+ return prepared_nodes_by_iteration_path
+
+ def _get_target_iteration_path(
+ self, source_node_id: str, graph: "nx.DiGraph", prepared_iterator_nodes: tuple[str, ...]
+ ) -> Optional[tuple[int, ...]]:
+ parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, list(prepared_iterator_nodes))
+ parent_paths = [self._state._get_iteration_path(prepared_id) for prepared_id, _ in parent_iterators]
+ if not parent_paths:
+ return ()
+
+ target_path = max(parent_paths, key=len)
+ if all(target_path[: len(parent_path)] == parent_path for parent_path in parent_paths):
+ return target_path
+ return None
+
+ def _get_indexed_iteration_node(
+ self,
+ source_node_id: str,
+ graph: "nx.DiGraph",
+ prepared_iterator_nodes: tuple[str, ...],
+ prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]],
+ ) -> Optional[str]:
+ target_path = self._get_target_iteration_path(source_node_id, graph, prepared_iterator_nodes)
+ if target_path is None:
+ return None
+
+ for path_length in range(len(target_path), -1, -1):
+ candidates = prepared_nodes_by_iteration_path.get(target_path[:path_length], [])
+ if len(candidates) == 1:
+ return candidates[0]
+ if len(candidates) > 1:
+ return None
+ return None
+
+ def _get_parent_iteration_mappings(
+ self, next_node_id: str, graph: "nx.DiGraph", input_edges: Optional[list[Edge]] = None
+ ) -> Iterable[list[tuple[str, str]]]:
+ input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)
+ parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))
+ iterator_graph = self.iterator_graph(graph)
+ iterator_nodes = self.get_node_iterators(next_node_id, iterator_graph)
+ if not iterator_nodes:
+ return iter(self._get_parent_iteration_mappings_without_iterators(next_node_id, input_edges))
+
+ iterator_nodes_prepared = [
+ sorted(self._state.source_prepared_mapping[node_id], key=self._state._get_iteration_path)
+ for node_id in iterator_nodes
+ ]
+ prepared_nodes_by_source = {
+ node_id: self._get_prepared_nodes_for_source(node_id) for node_id in parent_node_ids
+ }
+ prepared_nodes_by_source_and_path = {
+ node_id: self._index_prepared_nodes_by_iteration_path(
+ prepared_nodes,
+ [edge for edge in input_edges if edge.source.node_id == node_id],
+ )
+ for node_id, prepared_nodes in prepared_nodes_by_source.items()
+ }
+
+ def iter_mappings() -> Iterable[list[tuple[str, str]]]:
+ execution_graph: Optional["nx.DiGraph"] = None
+ for prepared_iterators in itertools.product(*iterator_nodes_prepared):
+ mapping: list[tuple[str, str]] = []
+ for node_id in parent_node_ids:
+ prepared_id = self._get_indexed_iteration_node(
+ node_id,
+ graph,
+ prepared_iterators,
+ prepared_nodes_by_source_and_path[node_id],
+ )
+ if prepared_id is None:
+ if execution_graph is None:
+ execution_graph = self._state._get_execution_graph_flat()
+ prepared_id = self.get_iteration_node(
+ node_id,
+ graph,
+ execution_graph,
+ list(prepared_iterators),
+ prepared_nodes_by_source[node_id],
+ )
+ if prepared_id is None:
+ break
+ mapping.append((node_id, prepared_id))
+ if len(mapping) == len(parent_node_ids):
+ yield mapping
+
+ return iter(iter_mappings())
+
+ def create_execution_node(
+ self,
+ node_id: str,
+ iteration_node_map: list[tuple[str, str]],
+ iteration_path: Optional[tuple[int, ...]] = None,
+ input_fields: Optional[set[str]] = None,
+ enforce_admission: bool = True,
+ ) -> list[str]:
+ """Prepares an iteration node and connects all edges, returning the new node id"""
+
+ node = self._state.graph.get_node(node_id)
+ iteration_indexes = self._get_new_node_iterations(node, node_id, iteration_node_map)
+ if not iteration_indexes:
+ if isinstance(node, ForInvocation):
+ return [self._create_empty_for_final_output(node_id, node, iteration_node_map)]
+ return []
+
+ new_edges = self._build_execution_edges_for_fields(node_id, iteration_node_map, input_fields)
+ new_nodes: list[str] = []
+ for iteration_index in iteration_indexes:
+ new_node_iteration_path = iteration_path
+ if new_node_iteration_path is None:
+ new_node_iteration_path = self._get_known_iteration_path(iteration_index, iteration_node_map)
+ elif isinstance(node, (ForInvocation, IterateInvocation)):
+ new_node_iteration_path += (iteration_index,)
+ if enforce_admission and not self._state._is_source_activation_admitted(
+ node_id, new_node_iteration_path or ()
+ ):
+ continue
+ new_node = self._create_execution_node_copy(node, node_id, iteration_index)
+ if new_node_iteration_path is not None:
+ self._state._prepared_registry().set_iteration_path(new_node.id, new_node_iteration_path)
+ self._state._record_activation_dependencies(new_node.id)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
+ new_nodes.append(new_node.id)
+
+ return new_nodes
+
+ def _has_admitted_source_mapping(self, node_id: str, graph: "nx.DiGraph") -> bool:
+ if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
+ return True
+ if isinstance(self._state.graph.get_node(node_id), IfInvocation):
+ mappings = self._get_if_condition_iteration_mappings(node_id, graph)
+ else:
+ mappings = self._get_parent_iteration_mappings(node_id, graph)
+ mappings = list(mappings)
+ if not mappings:
+ return self._state._is_source_activation_admitted(node_id)
+ return any(
+ self._state._is_source_activation_admitted(
+ node_id, self._get_known_iteration_path(-1, iteration_mapping) or ()
+ )
+ for iteration_mapping in mappings
+ )
+
+ def _get_if_condition_iteration_mappings(
+ self, node_id: str, graph: "nx.DiGraph"
+ ) -> Iterable[list[tuple[str, str]]]:
+ condition_edges = self._state.graph._get_input_edges(node_id, "condition")
+ if not condition_edges:
+ return iter([[]])
+ return self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
+
+ def _is_if_condition_ready(self, node_id: str) -> bool:
+ return all(
+ edge.source.node_id in self._state.source_prepared_mapping or edge.source.node_id in self._state.executed
+ for edge in self._state.graph._get_input_edges(node_id, "condition")
+ )
+
+ def _attach_pending_if_inputs(self) -> None:
+ """Attach only the selected branch edge to condition-ready If executions."""
+
+ source_graph = self._state._get_source_graph_flat()
+ source_order = {node_id: index for index, node_id in enumerate(nx.topological_sort(source_graph))}
+ pending_exec_nodes = sorted(
+ self._state._pending_if_exec_nodes,
+ key=lambda exec_node_id: (
+ source_order.get(self._state._prepared_registry().get_source_node_id(exec_node_id), 0),
+ self._state._get_iteration_path(exec_node_id),
+ exec_node_id,
+ ),
+ )
+ for exec_node_id in pending_exec_nodes:
+ self._state._try_resolve_if_node(exec_node_id, enqueue=False)
+ selected_field = self._state._resolved_if_exec_branches.get(exec_node_id)
+ if selected_field is None:
+ continue
+ if any(
+ edge.destination.field == selected_field
+ for edge in self._state.execution_graph._get_input_edges(exec_node_id)
+ ):
+ self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
+ continue
+
+ source_if_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
+ target_path = self._state._get_iteration_path(exec_node_id)
+ selected_edges = self._state.graph._get_input_edges(source_if_id, selected_field)
+ attached_edges: list[Edge] = []
+ selected_exec_ids: list[str] = []
+ for source_edge in selected_edges:
+ if source_edge.source.node_id not in self._state.source_prepared_mapping:
+ continue
+ candidates = [
+ prepared_id
+ for prepared_id in self._get_ordered_prepared_nodes_for_edge(source_edge)
+ if self._get_prepared_edge_iteration_path(source_edge, prepared_id) == target_path
+ ]
+ if not candidates:
+ continue
+ selected_exec_ids.append(candidates[0])
+ attached_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=candidates[0], field=source_edge.source.field),
+ destination=EdgeConnection(node_id=exec_node_id, field=selected_field),
+ )
+ )
+ if not attached_edges or any(
+ self._state._is_pending_if(candidate_id)
+ or (
+ isinstance(self._state.execution_graph.get_node(candidate_id), IfInvocation)
+ and candidate_id not in self._state.executed
+ )
+ for candidate_id in selected_exec_ids
+ ):
+ continue
+
+ self._attach_execution_edges(exec_node_id, attached_edges)
+ input_edges = self._state.execution_graph._get_input_edges(exec_node_id)
+ unmet = sum(1 for edge in input_edges if edge.source.node_id not in self._state.executed)
+ self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
+ self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
+ scheduler = self._state._scheduler()
+ if self._state._is_generic_graph_scheduler(scheduler):
+ scheduler.register_node(exec_node_id)
+ self._state._enqueue_if_ready(exec_node_id)
+
+ def iterator_graph(self, base: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
+ """Gets a DiGraph with edges to collectors removed so an ancestor search produces all active iterators for any node"""
+ g = base.copy() if base is not None else self._state._get_source_graph_flat().copy()
+ collectors = (
+ n for n in self._state.graph.nodes if isinstance(self._state.graph.get_node(n), CollectInvocation)
+ )
+ for c in collectors:
+ g.remove_edges_from(list(g.in_edges(c)))
+ for edge in self._state.graph.edges:
+ source_node = self._state.graph.get_node(edge.source.node_id)
+ if (
+ isinstance(source_node, ForInvocation)
+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final
+ ):
+ if g.has_edge(edge.source.node_id, edge.destination.node_id):
+ g.remove_edge(edge.source.node_id, edge.destination.node_id)
+ return g
+
+ def get_node_iterators(self, node_id: str, it_graph: Optional["nx.DiGraph"] = None) -> list[str]:
+ g = it_graph or self.iterator_graph()
+ return [
+ n
+ for n in nx.ancestors(g, node_id)
+ if isinstance(self._state.graph.get_node(n), (ForInvocation, IterateInvocation))
+ ]
+
+ def _get_prepared_nodes_for_source(self, source_node_id: str) -> set[str]:
+ return {
+ exec_node_id
+ for exec_node_id in self._state.source_prepared_mapping[source_node_id]
+ if self._state._get_prepared_exec_metadata(exec_node_id).state != "skipped"
+ }
+
+ def _get_parent_iterator_exec_nodes(
+ self, source_node_id: str, graph: "nx.DiGraph", prepared_iterator_nodes: list[str]
+ ) -> list[tuple[str, str]]:
+ iterator_source_node_mapping = [
+ (prepared_exec_node_id, self._state.prepared_source_mapping[prepared_exec_node_id])
+ for prepared_exec_node_id in prepared_iterator_nodes
+ ]
+ return [
+ iterator_mapping
+ for iterator_mapping in iterator_source_node_mapping
+ if nx.has_path(graph, iterator_mapping[1], source_node_id)
+ ]
+
+ def _matches_parent_iterators(
+ self, candidate_exec_node_id: str, parent_iterators: list[tuple[str, str]], execution_graph: "nx.DiGraph"
+ ) -> bool:
+ return all(
+ nx.has_path(execution_graph, parent_iterator_exec_id, candidate_exec_node_id)
+ for parent_iterator_exec_id, _ in parent_iterators
+ )
+
+ def _get_direct_prepared_iterator_match(
+ self,
+ prepared_nodes: set[str],
+ prepared_iterator_nodes: list[str],
+ parent_iterators: list[tuple[str, str]],
+ execution_graph: "nx.DiGraph",
+ ) -> Optional[str]:
+ prepared_iterator = next((node_id for node_id in prepared_iterator_nodes if node_id in prepared_nodes), None)
+ if prepared_iterator is None:
+ return None
+ if self._matches_parent_iterators(prepared_iterator, parent_iterators, execution_graph):
+ return prepared_iterator
+ return None
+
+ def _find_prepared_node_matching_iterators(
+ self, prepared_nodes: set[str], parent_iterators: list[tuple[str, str]], execution_graph: "nx.DiGraph"
+ ) -> Optional[str]:
+ return next(
+ (
+ node_id
+ for node_id in prepared_nodes
+ if self._matches_parent_iterators(node_id, parent_iterators, execution_graph)
+ ),
+ None,
+ )
+
+ def _get_final_for_exec_node(self, prepared_nodes: set[str]) -> Optional[str]:
+ prepared_for_nodes = [(node_id, self._state.execution_graph.nodes.get(node_id)) for node_id in prepared_nodes]
+ prepared_for_nodes = [
+ (node_id, node) for node_id, node in prepared_for_nodes if isinstance(node, ForInvocation)
+ ]
+ if not prepared_for_nodes:
+ return None
+ return max(prepared_for_nodes, key=lambda item: item[1].index)[0]
+
+ def get_iteration_node(
+ self,
+ source_node_id: str,
+ graph: "nx.DiGraph",
+ execution_graph: "nx.DiGraph",
+ prepared_iterator_nodes: list[str],
+ prepared_nodes: Optional[set[str]] = None,
+ ) -> Optional[str]:
+ if prepared_nodes is None:
+ prepared_nodes = self._get_prepared_nodes_for_source(source_node_id)
+ if len(prepared_nodes) == 1 and not prepared_iterator_nodes:
+ return next(iter(prepared_nodes))
+
+ parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, prepared_iterator_nodes)
+ if not parent_iterators and isinstance(self._state.graph.get_node(source_node_id), ForInvocation):
+ return self._get_final_for_exec_node(prepared_nodes)
+ if len(prepared_nodes) == 1:
+ prepared_node_id = next(iter(prepared_nodes))
+ if self._matches_parent_iterators(prepared_node_id, parent_iterators, execution_graph):
+ return prepared_node_id
+ return None
+
+ direct_iterator_match = self._get_direct_prepared_iterator_match(
+ prepared_nodes, prepared_iterator_nodes, parent_iterators, execution_graph
+ )
+ if direct_iterator_match is not None:
+ return direct_iterator_match
+
+ return self._find_prepared_node_matching_iterators(prepared_nodes, parent_iterators, execution_graph)
+
+ def prepare(self, base_g: Optional["nx.DiGraph"] = None) -> Optional[str]:
+ g = base_g if base_g is not None else self._state._get_source_graph_flat()
+ self._attach_pending_if_inputs()
+ next_node_id = next(
+ (
+ node_id
+ for node_id in nx.topological_sort(g)
+ if node_id not in self._state.source_prepared_mapping
+ and node_id not in self._state.executed
+ and not (
+ isinstance(self._state.graph.get_node(node_id), ForReturnInvocation)
+ and self._is_deferred_nested_for_return(node_id, g)
+ )
+ and not self._has_unmaterializable_for_final_input(node_id)
+ and (
+ all(
+ edge.source.node_id in self._state.source_prepared_mapping
+ or edge.source.node_id in self._state.executed
+ for edge in self._state.graph._get_input_edges(node_id, "condition")
+ )
+ if isinstance(self._state.graph.get_node(node_id), IfInvocation)
+ else all(
+ source_id in self._state.source_prepared_mapping or source_id in self._state.executed
+ for source_id, _ in g.in_edges(node_id)
+ )
+ )
+ and (
+ isinstance(self._state.graph.get_node(node_id), IfInvocation)
+ and self._is_if_condition_ready(node_id)
+ or not isinstance(self._state.graph.get_node(node_id), IfInvocation)
+ )
+ and self._has_admitted_source_mapping(node_id, g)
+ and (
+ not isinstance(self._state.graph.get_node(node_id), (ForInvocation, IterateInvocation))
+ or all(source_id in self._state.executed for source_id, _ in g.in_edges(node_id))
+ )
+ and not any(
+ isinstance(self._state.graph.get_node(ancestor_id), (ForInvocation, IterateInvocation))
+ and ancestor_id not in self._state.executed
+ for ancestor_id in nx.ancestors(g, node_id)
+ )
+ ),
+ None,
+ )
+
+ if next_node_id is None:
+ return None
+
+ next_node = self._state.graph.get_node(next_node_id)
+ new_node_ids: list[str] = []
+
+ if isinstance(next_node, CollectInvocation):
+ iteration_mapping_groups = self._get_collect_iteration_mapping_groups(
+ self._state.graph._get_input_edges(next_node_id)
+ )
+ for iteration_path, iteration_mappings in iteration_mapping_groups:
+ create_results = self.create_execution_node(next_node_id, iteration_mappings, iteration_path)
+ new_node_ids.extend(create_results)
+ else:
+ parent_iterator_nodes = self.get_node_iterators(next_node_id)
+ iteration_mappings_iter = (
+ self._get_if_condition_iteration_mappings(next_node_id, g)
+ if isinstance(next_node, IfInvocation)
+ else self._get_parent_iteration_mappings(next_node_id, g)
+ )
+ for iteration_mappings in iteration_mappings_iter:
+ iteration_path = None
+ if not parent_iterator_nodes:
+ input_edges = self._state.graph._get_input_edges(next_node_id)
+ iteration_path = max(
+ (
+ self._get_prepared_edge_iteration_path(edge, prepared_id)
+ for source_id, prepared_id in iteration_mappings
+ for edge in input_edges
+ if edge.source.node_id == source_id
+ ),
+ key=lambda path: (len(path), path),
+ default=(),
+ )
+ create_results = self.create_execution_node(
+ next_node_id,
+ iteration_mappings,
+ iteration_path,
+ input_fields={"condition"} if isinstance(next_node, IfInvocation) else None,
+ )
+ new_node_ids.extend(create_results)
+
+ if not new_node_ids:
+ # No parent mappings means zero loop contexts, unlike a context with an empty collection.
+ self._mark_source_node_empty(next_node_id)
+ self._state._invalidate_loop_caches_for_source(next_node_id)
+ return next_node_id
+
+ if isinstance(next_node, ForInvocation) and all(
+ self._state.execution_graph.get_node(exec_node_id).index == -1 for exec_node_id in new_node_ids
+ ):
+ self._mark_empty_for_complete(next_node_id)
+
+ return new_node_ids[0]
diff --git a/tests/app/services/shared/test_graph_iterate_planner.py b/tests/app/services/shared/test_graph_iterate_planner.py
new file mode 100644
index 0000000000..9e4e101627
--- /dev/null
+++ b/tests/app/services/shared/test_graph_iterate_planner.py
@@ -0,0 +1,93 @@
+import importlib
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+
[email protected]("planner_first", [True, False])
+def test_planner_import_boundary(planner_first: bool) -> None:
+ script = textwrap.dedent(
+ """
+ import importlib
+ import sys
+ from importlib.abc import MetaPathFinder
+
+ class BlockGraph(MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == "invokeai.app.services.shared.graph":
+ raise AssertionError("planner imported graph eagerly")
+
+ blocker = BlockGraph()
+ if PLANNER_FIRST:
+ sys.meta_path.insert(0, blocker)
+ planner = importlib.import_module("invokeai.app.services.shared.graph_iterate_planner")
+ assert "invokeai.app.services.shared.graph" not in sys.modules
+ sys.meta_path.remove(blocker)
+ from invokeai.app.services.shared import graph
+ planner = importlib.import_module("invokeai.app.services.shared.graph_iterate_planner")
+ state = graph.GraphExecutionState(graph=graph.Graph())
+ assert planner._get_direct_iterate_collect_nodes(state) is None
+ assert planner._can_use_direct_iterate_collect_planner(state) is False
+ """
+ ).replace("PLANNER_FIRST", repr(planner_first))
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=300, check=False)
+ assert result.returncode == 0, result.stderr
+
+
+def test_planner_dispatch_preserves_state_override_and_outer_transaction(monkeypatch: pytest.MonkeyPatch) -> None:
+ from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+ from invokeai.app.services.shared.graph_runtime_records import _ApplyTransaction
+
+ planner = importlib.import_module("invokeai.app.services.shared.graph_iterate_planner")
+ state = GraphExecutionState(graph=Graph())
+ transaction = _ApplyTransaction()
+ object.__setattr__(state, "_apply_transaction", transaction)
+ calls = []
+ monkeypatch.setattr(
+ state, "_prepare_direct_iterate_collect_unchecked", lambda: calls.append(state._apply_transaction)
+ )
+
+ planner._prepare_direct_iterate_collect(state)
+
+ assert calls == [transaction]
+ assert state._apply_transaction is transaction
+
+
+def test_execution_copy_preserves_graph_uuid_seam_and_iteration_metadata(monkeypatch: pytest.MonkeyPatch) -> None:
+ from invokeai.app.services.shared import graph
+
+ planner = importlib.import_module("invokeai.app.services.shared.graph_iterate_planner")
+ state = graph.GraphExecutionState(graph=graph.Graph())
+ source = graph.IterateInvocation(id="iterator", collection=[1, 2], use_cache=True)
+ state.graph.add_node(source)
+ monkeypatch.setattr(graph, "uuid_string", lambda: "prepared-iterator")
+
+ copied = planner._create_direct_execution_node_copy(state, "iterator", 1, (3, 1))
+
+ assert copied.id == "prepared-iterator"
+ assert copied.index == 1
+ assert copied.use_cache is False
+ assert source.id == "iterator"
+ assert source.use_cache is True
+ assert state.execution_graph.get_node(copied.id) is copied
+ assert state.prepared_source_mapping[copied.id] == "iterator"
+ assert state._prepared_registry().get_iteration_path(copied.id) == (3, 1)
+
+
+def test_planner_accepts_equivalent_generic_scheduler_instance() -> None:
+ from invokeai.app.invocations.math import AddInvocation
+ from invokeai.app.services.shared import graph
+
+ planner = importlib.import_module("invokeai.app.services.shared.graph_iterate_planner")
+ state = graph.GraphExecutionState(graph=graph.Graph(nodes={"source": AddInvocation(id="source", a=1, b=2)}))
+ facade_scheduler = graph._GenericGraphSchedulerAdapter(state)
+ planner_scheduler = graph._GenericGraphSchedulerAdapter(state)
+ object.__setattr__(state, "_generic_graph_scheduler", facade_scheduler)
+ object.__setattr__(state, "_execution_scheduler", planner_scheduler)
+
+ copied = planner._create_direct_execution_node_copy(state, "source")
+ planner._initialize_direct_execution_node(state, copied.id, ())
+
+ assert state._is_generic_graph_scheduler(planner_scheduler)
diff --git a/tests/app/services/shared/test_graph_materializer.py b/tests/app/services/shared/test_graph_materializer.py
new file mode 100644
index 0000000000..e407af8199
--- /dev/null
+++ b/tests/app/services/shared/test_graph_materializer.py
@@ -0,0 +1,70 @@
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.primitives import IntegerOutput
+from invokeai.app.services.shared import graph as graph_facade
+
+
+def test_materializer_import_is_leaf_and_keeps_networkx_lazy() -> None:
+ script = textwrap.dedent(
+ """
+ import sys
+ from invokeai.app.services.shared import graph_materializer
+
+ assert graph_materializer._ExecutionMaterializer
+ assert "invokeai.app.services.shared.graph" not in sys.modules
+ from invokeai.app.services.shared import graph
+ assert graph._ExecutionMaterializer is graph_materializer._ExecutionMaterializer
+ """
+ )
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False)
+ assert result.returncode == 0, result.stderr
+
+
+def test_materializer_facade_alias_and_class_patch_seam(monkeypatch: pytest.MonkeyPatch) -> None:
+ from invokeai.app.services.shared import graph_materializer
+
+ assert graph_facade._ExecutionMaterializer is graph_materializer._ExecutionMaterializer
+ state = graph_facade.GraphExecutionState(graph=graph_facade.Graph())
+ assert type(state._materializer()) is graph_materializer._ExecutionMaterializer
+ assert state._materializer() is state._materializer()
+ calls = []
+ monkeypatch.setattr(graph_facade._ExecutionMaterializer, "prepare", lambda self: calls.append(self))
+ state._materializer().prepare()
+ assert calls == [state._materializer()]
+
+
+def test_materializer_preserves_execution_edges_and_source_nodes() -> None:
+ from invokeai.app.services.shared import graph_materializer
+
+ source = AddInvocation(id="source", a=2, b=3)
+ sink = AddInvocation(id="sink", b=7)
+ graph = graph_facade.Graph(nodes={source.id: source, sink.id: sink})
+ graph.add_edge(
+ graph_facade.Edge(
+ source=graph_facade.EdgeConnection(node_id="source", field="value"),
+ destination=graph_facade.EdgeConnection(node_id="sink", field="a"),
+ )
+ )
+ state = graph_facade.GraphExecutionState(graph=graph)
+ assert isinstance(state._materializer(), graph_materializer._ExecutionMaterializer)
+ prepared_source = state.next()
+ assert prepared_source is not None
+ assert prepared_source.id != source.id
+ state.complete(prepared_source.id, IntegerOutput(value=5))
+ prepared_sink = state.next()
+ assert isinstance(prepared_sink, AddInvocation)
+ assert (prepared_sink.a, prepared_sink.b) == (5, 7)
+ assert state.execution_graph._get_input_edges(prepared_sink.id) == [
+ graph_facade.Edge(
+ source=graph_facade.EdgeConnection(node_id=prepared_source.id, field="value"),
+ destination=graph_facade.EdgeConnection(node_id=prepared_sink.id, field="a"),
+ )
+ ]
+ assert sink.a == 0
+ state.complete(prepared_sink.id, IntegerOutput(value=12))
+ assert state.is_complete()