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): make fresh If admission demand-driven

JPPhoto0f0df47f85aa
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 32283613a7..2e0a07ec2a 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -140,15 +140,14 @@ valid. A loaded terminal legacy state may retain its empty in-memory ledger for
`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the
selected branch, and the graph state validates and persists it after invocation. For a fresh generic `If`, the dedicated
-`_IfActivationController` produces opaque, frame-local activation dependencies; the legacy `_IfActivationCompiler`
-remains only as a compatibility lowering helper. `_GenericGraphSchedulerAdapter` consumes
-those dependencies through the opaque `ExecutionPlan` for readiness and rejects unselected prepared nodes through
-generic scheduler discard. The compatibility `_ExecutionScheduler` consumes the same dependencies and append-only
-discard projection; no type-specific branch scheduler prunes edges or propagates skips. Legacy skipped-state metadata
-remains as a compatibility projection for persisted snapshots and completion accounting. `apply()` replaces the
-activation token by stable identity, and activation effects are excluded from stream handling. This is an ownership
-seam, not final removal of all controller-derived branch analysis or skipped-state projection. The controller still
-derives branch membership from the current author graph; author-time activation
+`_IfActivationController` owns opaque, frame-local activation dependencies; the legacy `_IfActivationCompiler`
+remains only as a compatibility lowering helper for old snapshots. Fresh materialization prepares the condition boundary,
+resolves the activation token, and attaches only the selected branch input; unselected branch nodes remain unprepared.
+The generic and compatibility adapters consume the same decisions and append-only execution edges; no type-specific
+branch scheduler prunes edges or propagates skips. Legacy skipped-state metadata remains only for snapshots that already
+contain the old projection. `apply()` replaces the activation token by stable identity, and activation effects are
+excluded from stream handling. The controller still derives branch membership from the current author graph; author-time
+activation
ports and literal successor IDs remain absent, while unsupported loop shapes and saved-workflow control flow remain on
their compatibility paths until differential coverage proves their generic replacements.
@@ -160,8 +159,8 @@ the generic records preserve tested loop semantics first, while the old executio
lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-time
graph JSON.
This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing
-frontend/backend external interface remains frozen. The ownership seam does not remove all compiler-derived branch
-analysis or skipped-state projection yet.
+frontend/backend external interface remains frozen. Branch-membership analysis remains internal, while fresh execution
+no longer creates skipped-state projection and old snapshots retain it for compatibility.
The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and the
direct linkage edge. The current invocation templates provide output-scope metadata when a workflow is loaded. The
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index e949765b58..0a68187900 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -9,13 +9,13 @@ iterator patterns, tracks readiness via indegree (the number of incoming edges t
executes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution graph
instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If` graphs use the opaque `ExecutionPlan`
and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. For a fresh generic `If`, the dedicated
-`_IfActivationController` produces opaque, frame-local activation dependencies; the legacy
-`_IfActivationCompiler` remains only as a compatibility lowering helper. `_GenericGraphSchedulerAdapter` registers
-and consumes those dependencies through the opaque plan, then rejects unselected prepared nodes through generic scheduler
-discard. The compatibility `_ExecutionScheduler` path now consumes the same opaque dependencies and append-only
-retirement projection; it does not prune input edges or call a type-specific branch scheduler. Legacy skipped-state
-metadata remains a compatibility projection for runtime snapshots and completion accounting. This removes the
-branch-scheduler owner but does not yet remove all compiler-derived branch analysis or skipped-state projection.
+`_IfActivationController` owns fresh `If` admission and produces opaque, frame-local activation dependencies; the legacy
+`_IfActivationCompiler` remains only as a compatibility lowering helper for old snapshots. Fresh `If` materialization
+prepares the condition boundary first, resolves the activation token, and attaches only the selected branch input.
+Unselected branch nodes are never prepared, skipped, or added to fresh execution history. Both scheduler adapters
+consume the controller's decisions without pruning execution edges or calling a type-specific branch scheduler.
+Legacy skipped-state metadata remains only for snapshots that already contain the old projection. Branch-membership
+analysis remains an internal author-graph admission decision.
Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow also use
the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and generic
completion mirrors each Iterate result into that ledger before releasing `Collect`; materialization still owns copy
@@ -161,8 +161,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
- `graph: Graph` - source graph for the run; treated as stable during normal execution.
- `execution_graph: Graph` - materialized runtime nodes/edges. This is mutable runtime state, not an immutable audit
- log. `If` retirement is append-only: rejected prepared nodes are discarded through scheduler state without deleting
- input edges. Retry paths rebuild from `graph`, not from a previously persisted `execution_graph`.
+ log. Fresh `If` admission adds only the condition and selected-branch edges; legacy loaded execution graphs may still
+ contain append-only discarded nodes without deleted input edges. Retry paths rebuild from `graph`, not from a
+ previously persisted `execution_graph`.
- `executed: set[str]`, `executed_history: list[str]`.
- `results: dict[str, AnyInvocationOutput]`, `errors: dict[str, str]`.
- `prepared_source_mapping: dict[str, str]` - exec id -> source id.
@@ -227,14 +228,15 @@ rehydration, every activation token is bound to a currently prepared owner and i
declared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata
remains forward-compatible.
For a fresh generic `If`, `_IfActivationController` puts opaque, frame-local activation-dependency records on each
-branch-local plan node. The controller is an intermediate runtime admission owner: it still derives branch membership
-from the current author graph, but the schedulers no longer call the legacy compiler. `_GenericGraphSchedulerAdapter`
+branch-local plan node. The controller derives branch membership from the current author graph, but the schedulers no
+longer call the legacy compiler. Fresh materialization prepares the condition boundary, resolves the activation token,
+and attaches only the selected branch input; rejected branch sources remain unprepared. `_GenericGraphSchedulerAdapter`
consumes those records through the opaque plan: its readiness
callback accepts a node only when the required private `ActivationGate` runtime state is resolved and a matching
persisted activation token is present for its frame, while rejected dependencies cause scheduler discard. Both scheduler
adapters use this same dependency controller; neither prunes execution edges or calls a type-specific branch scheduler.
The compatibility path still projects discarded prepared nodes into legacy skipped metadata for rehydration and
-completion accounting. This is an ownership seam, not final removal of all compiler-derived branch analysis. `apply()`
+completion accounting when loading old execution graphs; fresh runs do not create those nodes. `apply()`
validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.
Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing
control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration
@@ -310,10 +312,9 @@ nested, multiple-loop, mixed-loop, and legacy-snapshot execution; those paths
retain their existing materialization and linkage ownership. The supported
fresh static flat `For`/`ForReturn` shape uses the generic adapter. For
`If`, generic readiness consumes opaque frame-local plan dependencies and requires
-both matching private `ActivationGate` runtime state and a persisted activation token;
-generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility
-`_ExecutionScheduler` path uses the same append-only discard projection; legacy skipped metadata remains until the
-no-skipped-state migration gate is complete.
+both matching private `ActivationGate` runtime state and a persisted activation token. Fresh resolution attaches only
+the selected branch edge; the forced compatibility `_ExecutionScheduler` path preserves this behavior for fresh states,
+while legacy skipped metadata remains only when loading old discarded projections.
This is not token-built successor topology. Loop and workflow-call adapters
still own materialization for unsupported shapes and durable queue lifecycle.
Those owners may be removed only after differential tests cover fresh, partially completed,
@@ -388,14 +389,14 @@ Workflow-call note:
be selected as live inputs.
- `_IfActivationController` Owns fresh runtime admission and compiles opaque, frame-local activation dependency
records for prepared nodes. `_IfActivationCompiler` remains the compatibility-only lowering helper for legacy
- callers. Neither helper owns execution-graph topology changes; removing this remaining branch-membership analysis is
- a later `If` migration gate.
+ callers. Fresh admission leaves rejected branch sources unprepared; legacy discarded projections remain loadable.
+ Branch-membership analysis remains internal to the controller.
- `_GenericGraphSchedulerAdapter` Projects the generic `ExecutionPlan`/`ExecutionScheduler` into the existing state
fields for ordinary static DAGs and legacy-shaped `If` graphs; the generic scheduler owns opaque readiness,
intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter registers
- the controller's activation dependencies, checks private gate state plus persisted activation tokens, and rejects
- unselected prepared nodes through generic scheduler discard. `If` scheduling does not call a type-specific branch
- scheduler, prune, or delete execution edges.
+ the controller's activation dependencies and checks private gate state plus persisted activation tokens. Fresh `If`
+ branch nodes are admitted before materialization; legacy prepared nodes may still be discarded for compatibility.
+ `If` scheduling does not call a type-specific branch scheduler, prune, or delete execution edges.
- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,
control-flow continuation scheduling, and the shared opaque activation-dependency projection for compatibility graphs.
- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.
@@ -438,6 +439,11 @@ legacy unmarked snapshots are treated as version 0, while unreadable snapshots a
iterator ancestors because the source path crosses a collector, prepared parent iteration paths are still used to
materialize one downstream exec node for each preserved collector path.
+- For a fresh **IfInvocation**: prepare only its condition inputs first. After the condition resolves, the activation
+ controller admits selected branch contexts and attaches only the selected branch input to the pending `If` execution.
+ Rejected branch sources are not materialized. Pending `If` state is reconstructed from its durable execution edges,
+ prepared mappings, and activation token after rehydration.
+
- For each new exec node:
- Deep-copy the source node; assign a fresh ID (and `index` for iterators).
@@ -453,10 +459,9 @@ legacy unmarked snapshots are treated as version 0, while unreadable snapshots a
- `_enqueue_if_ready(nid)` applies generic readiness: `indegree == 0`, not executed or claimed, and, for an `If`
branch-local node, both matching private `ActivationGate` runtime state and a persisted activation token are present
- for its frame. The generic adapter derives opaque dependencies and retires rejected nodes through generic scheduler
- discard. For direct `Collect` nodes, the adapter also requires available Iterate streams to be closed. Compatibility
- uses the same opaque activation dependencies and scheduler discard projection; legacy skipped metadata remains for
- snapshot compatibility.
+ for its frame. Fresh admission prevents rejected branch nodes from reaching this queue. For direct `Collect` nodes,
+ the adapter also requires available Iterate streams to be closed. Compatibility uses the same opaque activation
+ dependencies; legacy skipped metadata remains for old snapshots.
- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and legacy-shaped `If` graphs, projecting its
deterministic class/frame order into the compatibility queues. Loop and saved-workflow control-flow graphs use `_active_class`
and the legacy class queues. No batch-size or fairness cap is currently implemented.
@@ -493,19 +498,19 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.
`IfInvocation` now acts as a lazy branch boundary rather than a simple value multiplexer.
- The `condition` input must resolve first.
-- Nodes that are exclusive to the true or false branch can remain deferred even when their indegree is zero.
-- In `If` scheduling, once the prepared `If` node resolves its condition, the selected branch is released, unselected
- prepared nodes are retired through scheduler discard, and branch-exclusive ancestors of the unselected branch are
- never executed. The activation controller and both scheduler adapters use append-only execution edges; no
- type-specific branch scheduler performs pruning or skip propagation.
-- In compatibility `_ExecutionScheduler` scheduling, the same activation dependencies release selected work and discard
- rejected prepared nodes without deleting input edges. Legacy skipped metadata is still projected for persisted-state
- compatibility; removing that projection remains a later gate.
+- Nodes that are exclusive to the true or false branch remain unmaterialized until their branch is admitted, even when
+ their indegree would otherwise be zero.
+- Once the condition resolves, the controller records the selected activation token and attaches only the selected
+ branch input to the pending `If` execution. Branch-exclusive ancestors of the unselected branch are never prepared,
+ executed, or added to fresh execution history. The activation controller and both scheduler adapters use append-only
+ execution edges; no type-specific branch scheduler performs pruning or skip propagation.
+- Legacy snapshots that already contain skipped prepared nodes retain their compatibility metadata and scheduler
+ projection. Fresh execution does not create that projection.
- The SQLite queue/processor path has evidence for cancellation before and after `If` resolution and retry from each
boundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry starts
a fresh state and must emit a fresh matching activation token before selected-only completion.
-- Retired or skipped branch-local exec nodes may still be treated as executed for scheduling purposes, but they do not
- create entries in `results`.
+- Legacy retired or skipped branch-local exec nodes may still be treated as executed for compatibility scheduling, but
+ they do not create entries in `results`.
- Shared ancestors still execute if they are required by the selected branch or by any other live path in the graph.
This behavior is implemented in the runtime scheduler, not in the invocation body itself.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index e0b1d5df58..768135f620 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -419,8 +419,14 @@ class _IfActivationController:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
+ self._branch_sources_cache: dict[tuple[str, str], frozenset[str]] = {}
def _branch_sources(self, if_node_id: str, branch_field: str, source_graph: "nx.DiGraph") -> set[str]:
+ cache_key = (if_node_id, branch_field)
+ cached = self._branch_sources_cache.get(cache_key)
+ if cached is not None:
+ return set(cached)
+
direct_sources = {edge.source.node_id for edge in self._state.graph._get_input_edges(if_node_id, branch_field)}
branch_sources = set(direct_sources)
for source_node_id in direct_sources:
@@ -438,16 +444,25 @@ class _IfActivationController:
continue
branch_sources.remove(source_node_id)
changed = True
+ self._branch_sources_cache[cache_key] = frozenset(branch_sources)
return branch_sources
def get_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
"""Return activation requirements for one concrete prepared node."""
source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
+ if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
+ return ()
+ return self.get_source_dependencies(source_node_id, self._state._get_iteration_path(exec_node_id))
+
+ def get_source_dependencies(
+ self, source_node_id: str, iteration_path: tuple[int, ...] = ()
+ ) -> tuple[ActivationDependency, ...]:
+ """Return branch requirements before a source node is materialized."""
+
if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
return ()
source_graph = self._state._get_source_graph_flat()
- iteration_path = self._state._get_iteration_path(exec_node_id)
dependencies: list[ActivationDependency] = []
for source_if_id, source_if_node in self._state.graph.nodes.items():
if not isinstance(source_if_node, IfInvocation):
@@ -469,6 +484,55 @@ class _IfActivationController:
)
return tuple(dependencies)
+ def is_source_admitted(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:
+ dependencies = self.get_source_dependencies(source_node_id, iteration_path)
+ return bool(
+ not dependencies
+ or all(self._state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)
+ )
+
+ def is_source_rejected(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:
+ return any(
+ self._state._is_activation_dependency_rejected(dependency)
+ for dependency in self.get_source_dependencies(source_node_id, iteration_path)
+ )
+
+ def is_source_inactive(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:
+ """Return whether a source belongs exclusively to a rejected If branch."""
+
+ if iteration_path:
+ return self.is_source_rejected(source_node_id, iteration_path)
+
+ source_graph = self._state._get_source_graph_flat()
+ relevant_if_ids = {
+ if_node_id
+ for if_node_id, if_node in self._state.graph.nodes.items()
+ if isinstance(if_node, IfInvocation)
+ and any(
+ source_node_id in self._branch_sources(if_node_id, branch_field, source_graph)
+ for branch_field in ("true_input", "false_input")
+ )
+ }
+ if not relevant_if_ids:
+ return False
+
+ frames: set[tuple[int, ...]] = set()
+ for if_node_id in relevant_if_ids:
+ frames.update(
+ self._state._get_iteration_path(exec_node_id)
+ for exec_node_id in self._state._prepared_registry().get_prepared_ids(if_node_id)
+ )
+ if not frames:
+ return False
+
+ for frame in frames:
+ dependencies = self.get_source_dependencies(source_node_id, frame)
+ if dependencies and not any(
+ self._state._is_activation_dependency_rejected(dependency) for dependency in dependencies
+ ):
+ return False
+ return True
+
def _get_if_branch_exclusive_sources(state: "GraphExecutionState", if_node_id: str) -> dict[str, set[str]]:
"""Compatibility entry point for legacy ``If`` topology lowering."""
@@ -589,9 +653,19 @@ class _ExecutionMaterializer:
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
]
@@ -1233,9 +1307,15 @@ class _ExecutionMaterializer:
# 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)
+ 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, ...]:
@@ -1398,8 +1478,10 @@ class _ExecutionMaterializer:
for group_key in final_group_keys
]
- def _get_parent_iteration_mappings_without_iterators(self, next_node_id: str) -> list[list[tuple[str, str]]]:
- input_edges = self._state.graph._get_input_edges(next_node_id)
+ 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(
@@ -1500,12 +1582,15 @@ class _ExecutionMaterializer:
return None
return None
- def _get_parent_iteration_mappings(self, next_node_id: str, graph: "nx.DiGraph") -> Iterable[list[tuple[str, str]]]:
- parent_node_ids = [source_id for source_id, _ in graph.in_edges(next_node_id)]
+ 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))
+ 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)
@@ -1517,7 +1602,7 @@ class _ExecutionMaterializer:
prepared_nodes_by_source_and_path = {
node_id: self._index_prepared_nodes_by_iteration_path(
prepared_nodes,
- [edge for edge in self._state.graph._get_input_edges(next_node_id) if edge.source.node_id == node_id],
+ [edge for edge in input_edges if edge.source.node_id == node_id],
)
for node_id, prepared_nodes in prepared_nodes_by_source.items()
}
@@ -1556,6 +1641,8 @@ class _ExecutionMaterializer:
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"""
@@ -1566,15 +1653,19 @@ class _ExecutionMaterializer:
return [self._create_empty_for_final_output(node_id, node, iteration_node_map)]
return []
- new_edges = self._build_execution_edges(node_id, iteration_node_map)
+ 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 = self._create_execution_node_copy(node, node_id, iteration_index)
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._if_activation_controller().is_source_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)
attached_edges = self._attach_execution_edges(new_node.id, new_edges)
@@ -1583,6 +1674,104 @@ class _ExecutionMaterializer:
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._if_activation_controller().is_source_admitted(node_id)
+ return any(
+ self._state._if_activation_controller().is_source_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()
@@ -1704,6 +1893,7 @@ class _ExecutionMaterializer:
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
@@ -1715,10 +1905,24 @@ class _ExecutionMaterializer:
and self._is_deferred_nested_for_return(node_id, g)
)
and not self._has_unmaterializable_for_final_input(node_id)
- and 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 (
+ 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))
@@ -1747,7 +1951,12 @@ class _ExecutionMaterializer:
new_node_ids.extend(create_results)
else:
parent_iterator_nodes = self.get_node_iterators(next_node_id)
- for iteration_mappings in self._get_parent_iteration_mappings(next_node_id, g):
+ 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)
@@ -1761,7 +1970,12 @@ class _ExecutionMaterializer:
key=lambda path: (len(path), path),
default=(),
)
- create_results = self.create_execution_node(next_node_id, iteration_mappings, iteration_path)
+ 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:
@@ -1794,6 +2008,7 @@ class _ExecutionScheduler:
if (
self._state.indegree[exec_node_id] != 0
or exec_node_id in self._state.executed
+ or self._state._is_pending_if(exec_node_id)
or self._state._is_deferred_by_unresolved_if(exec_node_id)
):
return True
@@ -2099,6 +2314,8 @@ class _GenericGraphSchedulerAdapter:
def _is_node_activation_ready(self, exec_node_id: str) -> bool:
"""Require every frame-local activation dependency to be satisfied."""
+ if self._state._is_pending_if(exec_node_id):
+ return False
if not all(
self._state._is_activation_dependency_satisfied(dependency)
for dependency in self._scheduler.plan.nodes[exec_node_id].activation_dependencies
@@ -4367,6 +4584,7 @@ class GraphExecutionState(BaseModel):
indegree: dict[str, int] = Field(default_factory=dict, description="Remaining unmet input count for exec nodes")
_if_branch_exclusive_sources: dict[str, dict[str, set[str]]] = PrivateAttr(default_factory=dict)
_resolved_if_exec_branches: dict[str, str] = PrivateAttr(default_factory=dict)
+ _pending_if_exec_nodes: set[str] = PrivateAttr(default_factory=set)
_prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
_if_activation_compiler_instance: Optional[_IfActivationCompiler] = PrivateAttr(default=None)
@@ -4487,6 +4705,7 @@ class GraphExecutionState(BaseModel):
self._generic_graph_scheduler = None
self._if_activation_compiler_instance = None
self._if_activation_controller_instance = None
+ self._pending_if_exec_nodes = set()
self._execution_runtime = None
self._if_branch_exclusive_sources = {}
self._source_graph_flat = None
@@ -4568,6 +4787,7 @@ class GraphExecutionState(BaseModel):
(prepared_node_ids := self.source_prepared_mapping.get(source_node_id))
and all(exec_node_id in self.executed for exec_node_id in prepared_node_ids)
)
+ or self._if_activation_controller().is_source_inactive(source_node_id)
}
return self._completed_source_ids_cache
@@ -4908,6 +5128,7 @@ class GraphExecutionState(BaseModel):
branch,
)
if changed:
+ self._completed_source_ids_cache = None
self._tx_record(lambda: runtime.replace_gate(previous))
return changed
@@ -6227,7 +6448,7 @@ class GraphExecutionState(BaseModel):
def _remove_from_ready_queues(self, exec_node_id: str) -> None:
self._scheduler().remove_from_ready_queues(exec_node_id)
- def _try_resolve_if_node(self, exec_node_id: str) -> None:
+ def _try_resolve_if_node(self, exec_node_id: str, *, enqueue: bool = True) -> None:
scheduler = self._execution_scheduler
if isinstance(scheduler, _GenericGraphSchedulerAdapter):
scheduler.resolve_if_node(exec_node_id)
@@ -6246,7 +6467,22 @@ class GraphExecutionState(BaseModel):
assert isinstance(scheduler, _ExecutionScheduler)
scheduler._discard_rejected_activation_nodes()
scheduler._enqueue_activation_ready_nodes()
- self._enqueue_if_ready(exec_node_id)
+ if enqueue:
+ self._enqueue_if_ready(exec_node_id)
+
+ def _is_pending_if(self, exec_node_id: str) -> bool:
+ node = self.execution_graph.nodes.get(exec_node_id)
+ if not isinstance(node, IfInvocation):
+ return False
+ selected_field = self._resolved_if_exec_branches.get(exec_node_id)
+ if selected_field is None:
+ return True
+ source_node_id = self.prepared_source_mapping.get(exec_node_id)
+ if source_node_id is None or not self.graph._get_input_edges(source_node_id, selected_field):
+ return False
+ return not any(
+ edge.destination.field == selected_field for edge in self.execution_graph._get_input_edges(exec_node_id)
+ )
def set_ready_order(self, order: Iterable[Type[BaseInvocation] | str]) -> None:
names: list[str] = []
@@ -6261,8 +6497,11 @@ class GraphExecutionState(BaseModel):
def _prepare_until_node_ready(self) -> Optional[BaseInvocation]:
base_graph = self._get_source_graph_flat()
+ self._materializer()._attach_pending_if_inputs()
+ next_node = self._get_next_node()
+ if next_node is not None:
+ return next_node
prepared_id = self._materializer().prepare(base_graph)
- next_node: Optional[BaseInvocation] = None
while prepared_id is not None:
prepared_id = self._materializer().prepare(base_graph)
@@ -6277,6 +6516,7 @@ class GraphExecutionState(BaseModel):
self._active_class = None
self._if_branch_exclusive_sources = {}
self._resolved_if_exec_branches = {}
+ self._pending_if_exec_nodes = set()
self._prepared_exec_metadata = {}
self._prepared_exec_registry = None
self._if_activation_compiler_instance = None
@@ -6388,15 +6628,20 @@ class GraphExecutionState(BaseModel):
raise ValueError(f"Activation token for If execution node {exec_node_id} has a stale token id")
self._resolve_activation_gate(exec_node_id, selected_field)
self._resolved_if_exec_branches[exec_node_id] = selected_field
+ if self._is_pending_if(exec_node_id):
+ self._pending_if_exec_nodes.add(exec_node_id)
continue
if not self._apply_if_condition_inputs(exec_node_id, node):
+ self._pending_if_exec_nodes.add(exec_node_id)
continue
selected_field = "true_input" if node.condition else "false_input"
self._resolve_activation_gate(exec_node_id, selected_field)
self._resolved_if_exec_branches[exec_node_id] = selected_field
self._record_compatibility_activation_token(exec_node_id, selected_field)
+ if self._is_pending_if(exec_node_id):
+ self._pending_if_exec_nodes.add(exec_node_id)
def _rehydrate_execution_refs(self) -> None:
for exec_node_id in self.prepared_source_mapping:
@@ -6536,6 +6781,7 @@ class GraphExecutionState(BaseModel):
self._rehydrate_prepared_exec_metadata()
self._rehydrate_resolved_if_exec_branches()
self._rehydrate_generic_runtime_state()
+ self._materializer()._attach_pending_if_inputs()
self._rehydrate_ready_queues()
def model_post_init(self, __context: Any) -> None:
@@ -6682,7 +6928,11 @@ class GraphExecutionState(BaseModel):
return False
for source_node_id in nx.topological_sort(self._get_source_graph_flat()):
- if source_node_id in completed_source_ids and source_node_id not in self.executed:
+ if (
+ source_node_id in completed_source_ids
+ and source_node_id not in self.executed
+ and not self._if_activation_controller().is_source_inactive(source_node_id)
+ ):
self._mark_source_executed(source_node_id)
return True
@@ -6836,7 +7086,7 @@ class GraphExecutionState(BaseModel):
)
def _create_execution_node(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[str]:
- return self._materializer().create_execution_node(node_id, iteration_node_map)
+ return self._materializer().create_execution_node(node_id, iteration_node_map, enforce_admission=False)
def _iterator_graph(self, base: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
return self._materializer().iterator_graph(base)
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 5eb5b5a6e4..7b858bfb64 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -101,6 +101,29 @@ def _nested_if_graph() -> Graph:
return graph
+def _flat_if_graph(*, condition: bool = True) -> Graph:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=condition))
+ graph.add_node(AddInvocation(id="true_branch", a=2, b=3))
+ graph.add_node(AddInvocation(id="false_branch", a=10, b=20))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(AddInvocation(id="sink", b=1))
+
+ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=source, field=source_field),
+ destination=EdgeConnection(node_id=destination, field=destination_field),
+ )
+ )
+
+ connect("condition", "value", "if", "condition")
+ connect("true_branch", "value", "if", "true_input")
+ connect("false_branch", "value", "if", "false_input")
+ connect("if", "value", "sink", "a")
+ return graph
+
+
def _flat_for_graph(
*,
with_after: bool = False,
@@ -548,9 +571,25 @@ def _expected_edge_projection(
outer_condition: bool,
inner_condition: bool,
) -> tuple[tuple[str, str, str, str, str], ...]:
- """Project the append-only execution graph for both scheduler adapters."""
- del force_compatibility_scheduler, outer_condition, inner_condition
- return _source_edge_projection(graph)
+ """Project the live execution graph for either scheduler adapter."""
+ del force_compatibility_scheduler
+ live_edges = {("outer_condition", "value", "outer_if", "condition", "default")}
+ if outer_condition:
+ live_edges.add(("inner_condition", "value", "inner_if", "condition", "default"))
+ live_edges.add(
+ (
+ "inner_true" if inner_condition else "inner_false",
+ "value",
+ "inner_if",
+ "true_input" if inner_condition else "false_input",
+ "default",
+ )
+ )
+ live_edges.add(("inner_if", "value", "outer_if", "true_input", "default"))
+ else:
+ live_edges.add(("outer_false", "value", "outer_if", "false_input", "default"))
+ live_edges.add(("outer_if", "value", "sink", "a", "default"))
+ return tuple(sorted(live_edges))
def _normalized_indegree(state: GraphExecutionState) -> tuple[tuple[str, tuple[int, ...]], ...]:
@@ -578,21 +617,32 @@ def _expected_remaining_input_indegree(
outer_condition: bool,
inner_condition: bool,
) -> dict[str, int]:
- """Calculate remaining indegrees from source edges and durable source completion only."""
+ """Calculate remaining indegrees from an independent source-graph oracle."""
expected_edges = _expected_edge_projection(
state.graph,
force_compatibility_scheduler=force_compatibility_scheduler,
outer_condition=outer_condition,
inner_condition=inner_condition,
)
- completed_sources = {
- source_id for execution_id, source_id in state.prepared_source_mapping.items() if execution_id in state.executed
+ prepared_by_source = {
+ source_id: sorted(
+ prepared_ids,
+ key=lambda exec_id: (state._get_iteration_path(exec_id), exec_id),
+ )
+ for source_id, prepared_ids in state.source_prepared_mapping.items()
}
return {
execution_id: sum(
- source_id not in completed_sources
+ source_exec_id not in state.executed
for source_id, _source_field, destination_id, _destination_field, _edge_type in expected_edges
if destination_id == state.prepared_source_mapping[execution_id]
+ for source_exec_id in prepared_by_source.get(source_id, ())
+ if state._get_iteration_path(source_exec_id) == state._get_iteration_path(execution_id)
+ and not (
+ isinstance(state.execution_graph.get_node(execution_id), IfInvocation)
+ and isinstance(state.execution_graph.get_node(source_exec_id), IfInvocation)
+ and source_exec_id not in state.executed
+ )
)
for execution_id in state.prepared_source_mapping
}
@@ -1564,6 +1614,39 @@ def test_if_readiness_does_not_delegate_to_legacy_activation_compiler(
assert state.is_complete()
[email protected]("force_compatibility_scheduler", [False, True])
+def test_flat_if_admission_is_demand_driven_and_token_authoritative(
+ force_compatibility_scheduler: bool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_legacy_path(*_: object, **__: object) -> None:
+ raise AssertionError("fresh If execution used a legacy branch projection")
+
+ monkeypatch.setattr(_IfActivationCompiler, "get_activation_dependencies", fail_legacy_path)
+ monkeypatch.setattr(_IfActivationCompiler, "get_branch_exclusive_sources", fail_legacy_path)
+ monkeypatch.setattr(graph_module, "_get_if_branch_exclusive_sources", fail_legacy_path)
+
+ trace, state = _run_graph(
+ GraphExecutionState(graph=_flat_if_graph()),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+
+ assert trace == ["condition", "true_branch", "if", "sink"]
+ assert set(state.source_prepared_mapping) == {"condition", "true_branch", "if", "sink"}
+ assert "false_branch" not in state.source_prepared_mapping
+ assert state.executed_history == trace
+ assert all(
+ state._get_prepared_exec_metadata(exec_node_id).state != "skipped"
+ for exec_node_id in state.prepared_source_mapping
+ )
+ activation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]
+ assert len(activation_tokens) == 1
+ assert activation_tokens[0].port == "true_input"
+ sink_id = next(iter(state.source_prepared_mapping["sink"]))
+ assert state.results[sink_id].value == 6
+ assert state.is_complete()
+
+
@pytest.mark.parametrize(
("outer_condition", "inner_condition", "expected_trace", "expected_history", "expected_value"),
[
@@ -1662,19 +1745,19 @@ def test_fresh_generic_nested_if_preserves_state_without_legacy_branch_projectio
trace, state = _run_graph(GraphExecutionState(graph=graph))
assert trace == expected_trace
- assert state.executed_history == expected_history
+ assert state.executed_history == expected_trace
assert set(state.indegree) == set(state.prepared_source_mapping)
assert set(state.indegree.values()) == {0}
assert state.is_complete()
sink_id = next(iter(state.source_prepared_mapping["sink"]))
assert state.results[sink_id].value == expected_value
- assert _execution_edge_projection(state) == _source_edge_projection(graph)
- expected_retired_sources = (
- {"inner_false" if inner_condition else "inner_true", "outer_false"}
- if outer_condition
- else {"inner_condition", "inner_true", "inner_false", "inner_if"}
+ assert _execution_edge_projection(state) == _expected_edge_projection(
+ graph,
+ force_compatibility_scheduler=False,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
)
- assert {state.prepared_source_mapping[exec_id] for exec_id in generic_retired_nodes} == expected_retired_sources
+ assert generic_retired_nodes == []
@pytest.mark.parametrize("stop_after_source", ["outer_if", "inner_false"])
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
index c100127825..dfe8fb7c13 100644
--- a/tests/app/services/shared/test_execution_engine_scheduler.py
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -13,6 +13,7 @@ from invokeai.app.services.shared.execution_engine.scheduler import (
ExecutionPlan,
ExecutionScheduler,
)
+from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state
from invokeai.app.services.shared.graph import (
CollectInvocation,
Edge,
@@ -142,17 +143,12 @@ def test_graph_state_generic_if_readiness_uses_activation_dependency_records(mon
assert condition is not None
state.complete(condition.id, condition.invoke(Mock()))
- true_exec_id = next(
- execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "true_value"
- )
+ while "true_value" not in state.source_prepared_mapping:
+ assert state._materializer().prepare(state._get_source_graph_flat()) is not None
+ true_exec_id = next(iter(state.source_prepared_mapping["true_value"]))
plan_node = state._generic_graph_scheduler._scheduler.plan.nodes[true_exec_id]
assert plan_node.activation_dependencies == (ActivationDependency(owner_id="if", branch="true_input", frame=()),)
- false_exec_id = next(
- execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "false_value"
- )
- assert state._generic_graph_scheduler._scheduler.plan.nodes[false_exec_id].activation_dependencies == (
- ActivationDependency(owner_id="if", branch="false_input", frame=()),
- )
+ assert "false_value" not in state.source_prepared_mapping
if_exec_id = next(
execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "if"
@@ -228,6 +224,9 @@ def test_graph_state_rehydrates_legacy_if_without_activation_token() -> None:
condition = state.next()
assert condition is not None
state.complete(condition.id, condition.invoke(Mock()))
+ next_node = state.next()
+ assert next_node is not None
+ assert state.prepared_source_mapping[next_node.id] == "true_value"
snapshot = state.model_dump(mode="python")
snapshot["execution_tokens"] = {}
@@ -246,6 +245,73 @@ def test_graph_state_rehydrates_legacy_if_without_activation_token() -> None:
assert restored.prepared_source_mapping[next_node.id] == "true_value"
+def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=False))
+ graph.add_node(AddInvocation(id="true_value", a=2, b=2))
+ graph.add_node(AddInvocation(id="false_value", a=3, b=3))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="condition", field="value"),
+ destination=EdgeConnection(node_id="if", field="condition"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="true_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="false_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="false_input"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ condition = state.next()
+ assert condition is not None
+ state.complete(condition.id, condition.invoke(Mock()))
+ selected_branch = state.next()
+ assert selected_branch is not None
+ selected_branch_exec_id = selected_branch.id
+ assert state.prepared_source_mapping[selected_branch_exec_id] == "false_value"
+
+ # Recreate the prepared/skipped branch projection written by the legacy If scheduler.
+ skipped_exec_id = state._materializer().create_execution_node(
+ "true_value", [], iteration_path=(), enforce_admission=False
+ )[0]
+ assert state._get_prepared_exec_metadata(skipped_exec_id).state == "skipped"
+
+ snapshot = dump_execution_state(state)
+ snapshot.pop("execution_state_version")
+ snapshot.pop("execution_effects")
+ if_exec_id = next(
+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "if"
+ )
+ snapshot["execution_graph"]["edges"].append(
+ Edge(
+ source=EdgeConnection(node_id=skipped_exec_id, field="value"),
+ destination=EdgeConnection(node_id=if_exec_id, field="true_input"),
+ ).model_dump(mode="json")
+ )
+
+ restored = load_execution_state(snapshot)
+
+ assert restored._legacy_snapshot_loaded
+ assert restored._get_prepared_exec_metadata(skipped_exec_id).state == "skipped"
+ restored_scheduler = restored._scheduler()
+ assert isinstance(restored_scheduler, _GenericGraphSchedulerAdapter)
+ assert skipped_exec_id in restored_scheduler._scheduler.discarded
+
+ next_node = restored.next()
+ assert next_node is not None
+ assert next_node.id == selected_branch_exec_id
+ assert restored.prepared_source_mapping[next_node.id] == "false_value"
+
+
def test_generic_scheduler_discarded_claim_is_not_requeued() -> None:
plan = ExecutionPlan()
plan.add_node("source", "Source")
@@ -745,22 +811,14 @@ def test_graph_state_if_rehydrates_discarded_unselected_branch() -> None:
assert selected_branch is not None
selected_branch_exec_id = selected_branch.id
assert state.prepared_source_mapping[selected_branch_exec_id] == "false_value"
- skipped_exec_id = next(
- exec_node_id
- for exec_node_id, source_node_id in state.prepared_source_mapping.items()
- if source_node_id == "true_value"
- )
- assert state._get_prepared_exec_metadata(skipped_exec_id).state == "skipped"
+ assert "true_value" not in state.source_prepared_mapping
restored = GraphExecutionState.model_validate(state.model_dump(mode="python"), strict=False)
- restored_scheduler = restored._scheduler()
- assert skipped_exec_id in restored_scheduler._scheduler.discarded
next_node = restored.next()
assert next_node is not None
assert next_node.id == selected_branch_exec_id
assert restored.prepared_source_mapping[next_node.id] == "false_value"
- assert restored.next() is None
def test_graph_state_static_dag_rehydrates_generic_scheduler_after_partial_run() -> None:
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 694cac08d5..cdf545e2cc 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -3645,6 +3645,24 @@ def test_materializer_reuses_matching_parent_iteration_paths():
assert iteration_path == (2,)
+def test_materializer_deduplicates_one_iterator_source_used_by_multiple_inputs():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(TwoAnyTestInvocation(id="pair"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "pair", "first"))
+ graph.add_edge(create_edge("iterate", "item", "pair", "second"))
+ graph.add_edge(create_edge("pair", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+
+ execute_all_nodes(state)
+
+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[collect_exec_id].collection == [(0, 0), (1, 1)]
+
+
def test_materializer_does_not_merge_matching_paths_from_independent_iterators():
graph = Graph()
graph.add_node(RangeInvocation(id="left_range", start=0, stop=2, step=1))
@@ -4876,7 +4894,7 @@ def test_if_graph_optimized_behavior_executes_only_selected_simple_branch():
assert "false_value" not in executed_source_ids
-def test_if_graph_optimized_behavior_records_skipped_branch_in_execution_history():
+def test_if_graph_optimized_behavior_does_not_record_unselected_branch_in_execution_history():
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=True))
graph.add_node(PromptTestInvocation(id="true_value", prompt="true branch"))
@@ -4892,8 +4910,8 @@ def test_if_graph_optimized_behavior_records_skipped_branch_in_execution_history
g = GraphExecutionState(graph=graph)
execute_all_nodes(g)
- assert set(g.executed_history) == {"condition", "true_value", "false_value", "if", "selected_output"}
- assert g.executed_history.count("false_value") == 1
+ assert set(g.executed_history) == {"condition", "true_value", "if", "selected_output"}
+ assert "false_value" not in g.executed_history
def test_if_graph_lowers_legacy_branch_choice_to_frame_scoped_activation_token():
@@ -5234,6 +5252,7 @@ def test_if_graph_optimized_behavior_prunes_branches_per_iteration():
assert executed_source_ids.count("true_branch") == 2
assert executed_source_ids.count("false_branch") == 1
assert executed_source_ids.count("if") == 3
+ assert g.is_complete()
def test_if_graph_optimized_behavior_keeps_shared_live_consumers_per_iteration():
@@ -5272,6 +5291,7 @@ def test_if_graph_optimized_behavior_keeps_shared_live_consumers_per_iteration()
assert executed_source_ids.count("observer") == 3
assert executed_source_ids.count("true_leaf") == 1
assert executed_source_ids.count("false_branch") == 2
+ assert g.is_complete()
def test_if_graph_optimized_behavior_handles_selected_true_branch_with_shared_false_input_ancestor():