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): route bounded nested If generically

JPPhoto29a8370cf410
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index ca6ac41870..53f8e9766a 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -169,8 +169,9 @@ 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. Fresh graphs with one ordinary-node
-`If` compile opaque, frame-local activation dependencies in graph state; nested, mixed, loop-containing,
-saved-workflow, and legacy shapes use the dedicated `_IfActivationController` fallback. Legacy
+`If`, or the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no
+other consumer, compile opaque, frame-local activation dependencies in graph state. Sibling, deeper, fan-out, mixed,
+loop-containing, saved-workflow, and legacy shapes use the dedicated `_IfActivationController` fallback. Legacy
skipped-state projection remains only 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
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 98adf6f8d5..121b42e99f 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -8,11 +8,12 @@ Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**
iterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), and
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`. Fresh graphs with one ordinary-node `If`
-compile opaque, frame-local activation dependencies in `GraphExecutionState`; nested, mixed, loop-containing,
-saved-workflow, and legacy shapes use the dedicated `_IfActivationController` fallback. Legacy skipped-state projection
-remains only for old snapshots. Fresh `If` materialization prepares the condition boundary first, resolves the activation token, and
-attaches only the selected branch input.
+and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. Fresh graphs with one ordinary-node `If`, or
+the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no other
+consumer, compile opaque, frame-local activation dependencies in `GraphExecutionState`; sibling, deeper, fan-out,
+mixed, loop-containing, saved-workflow, and legacy shapes use the dedicated `_IfActivationController` fallback.
+Legacy skipped-state projection remains only 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 these dependency 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
@@ -253,9 +254,10 @@ port against the producing invocation's declared activation fields and persists
rehydration, every activation token is bound to a currently prepared owner and its derived execution reference; its
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` graph with one ordinary-node `If`, `GraphExecutionState` compiles opaque, frame-local
-activation-dependency records privately on each branch-local plan node; nested, mixed, loop-containing,
-saved-workflow, and legacy shapes use `_IfActivationController` for the same records. The controller
+For a fresh generic `If` graph with one ordinary-node `If`, or the exact one-level nested shape described above,
+`GraphExecutionState` compiles opaque, frame-local activation-dependency records privately on each branch-local plan
+node. Sibling, deeper, fan-out, mixed, loop-containing, saved-workflow, and legacy shapes use `_IfActivationController`
+for the same records. The controller
remains the fallback runtime dependency owner, and the schedulers no longer call a 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
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index fd89b36ed7..7996572ef6 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -4729,33 +4729,81 @@ class GraphExecutionState(BaseModel):
self._source_graph_flat = self.graph.nx_graph_flat()
return self._source_graph_flat
+ def _get_fresh_if_nodes(self) -> tuple[IfInvocation, ...]:
+ source_graph = self._get_source_graph_flat()
+ source_order = {node_id: index for index, node_id in enumerate(nx.topological_sort(source_graph))}
+ return tuple(
+ sorted(
+ (node for node in self.graph.nodes.values() if isinstance(node, IfInvocation)),
+ key=lambda node: (source_order.get(node.id, len(source_order)), node.id),
+ )
+ )
+
def _can_use_fresh_flat_if_activation(self) -> bool:
- """Admit fresh single-If dependency compilation for ordinary graph nodes."""
+ """Admit fresh single-If or bounded nested-If dependency compilation."""
if self._legacy_snapshot_loaded:
return False
- if_nodes = [node for node in self.graph.nodes.values() if isinstance(node, IfInvocation)]
- if len(if_nodes) != 1:
+ forbidden_nodes = (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ )
+ if any(isinstance(node, forbidden_nodes) for node in self.graph.nodes.values()):
return False
- if_node = if_nodes[0]
- if any(
- isinstance(
- node,
- (
- IfInvocation,
- CallSavedWorkflowInvocation,
- ForInvocation,
- ForReturnInvocation,
- IterateInvocation,
- CollectInvocation,
- ),
- )
- for node in self.graph.nodes.values()
- if node is not if_node
- ):
+
+ try:
+ source_graph = self._get_source_graph_flat()
+ if not nx.is_directed_acyclic_graph(source_graph):
+ return False
+ if_nodes = self._get_fresh_if_nodes()
+ except nx.NetworkXUnfeasible:
return False
+ if len(if_nodes) != 1:
+ if len(if_nodes) != 2:
+ return False
+
+ if any(edge.type != "default" for edge in self.graph.edges):
+ return False
+
+ if_node_ids = {node.id for node in if_nodes}
+ nested_edges = [
+ edge
+ for edge in self.graph.edges
+ if edge.source.node_id in if_node_ids and edge.destination.node_id in if_node_ids
+ ]
+ if len(nested_edges) != 1:
+ return False
+
+ nested_edge = nested_edges[0]
+ if nested_edge.source.field != "value" or nested_edge.destination.field not in {
+ "true_input",
+ "false_input",
+ }:
+ return False
+
+ inner_if_id = nested_edge.source.node_id
+ if any(edge.source.node_id == inner_if_id and edge != nested_edge for edge in self.graph.edges):
+ return False
+
+ outer_if_id = nested_edge.destination.node_id
+ for if_node in if_nodes:
+ for field in ("condition", "true_input", "false_input"):
+ input_edges = self.graph._get_input_edges(if_node.id, field)
+ if len(input_edges) != 1:
+ return False
+ for edge in input_edges:
+ if edge.source.node_id in if_node_ids and edge != nested_edge:
+ return False
+ if edge == nested_edge and (
+ if_node.id != outer_if_id or field != nested_edge.destination.field
+ ):
+ return False
+
return True
def _get_fresh_if_branch_sources(self, if_node_id: str, branch_field: str) -> set[str]:
@@ -4795,9 +4843,9 @@ class GraphExecutionState(BaseModel):
if not self._can_use_fresh_flat_if_activation():
return self._if_activation_controller().get_source_dependencies(source_node_id, iteration_path)
- if_node = next(node for node in self.graph.nodes.values() if isinstance(node, IfInvocation))
dependencies = tuple(
ActivationDependency(owner_id=if_node.id, branch=branch_field, frame=iteration_path)
+ for if_node in self._get_fresh_if_nodes()
for branch_field in ("true_input", "false_input")
if source_node_id in self._get_fresh_if_branch_sources(if_node.id, branch_field)
)
@@ -4809,7 +4857,12 @@ class GraphExecutionState(BaseModel):
if dependencies is not None:
return dependencies
source_node_id = self._prepared_registry().get_source_node_id(exec_node_id)
- dependencies = self._get_source_activation_dependencies(source_node_id, self._get_iteration_path(exec_node_id))
+ if any(isinstance(node, IfInvocation) for node in self.graph.nodes.values()):
+ dependencies = self._get_source_activation_dependencies(
+ source_node_id, self._get_iteration_path(exec_node_id)
+ )
+ else:
+ dependencies = ()
self._tx_set_mapping(self._if_activation_dependencies_by_exec, exec_node_id, dependencies)
return dependencies
@@ -4838,7 +4891,7 @@ class GraphExecutionState(BaseModel):
return False
return all(
self._get_source_activation_dependencies(source_node_id, frame)
- and all(
+ and any(
self._is_activation_dependency_rejected(frame_dependency)
for frame_dependency in self._get_source_activation_dependencies(source_node_id, frame)
)
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 11e48cb562..8bbdcdd4bf 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -9,7 +9,7 @@ import pytest
from pydantic import ValidationError
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
-from invokeai.app.invocations.collections import CollectionConcatInvocation
+from invokeai.app.invocations.collections import CollectionConcatInvocation, RangeInvocation
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.loops import (
ForInvocation,
@@ -116,6 +116,14 @@ def _nested_if_graph() -> Graph:
return graph
+def _nested_if_graph_with_shared_ancestor() -> Graph:
+ graph = _nested_if_graph()
+ graph.add_node(AddInvocation(id="shared", a=1, b=1))
+ graph.add_edge(create_edge("shared", "value", "inner_true", "a"))
+ graph.add_edge(create_edge("shared", "value", "inner_false", "a"))
+ return graph
+
+
def _flat_if_graph(*, condition: bool = True) -> Graph:
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=condition))
@@ -3756,6 +3764,92 @@ def test_fresh_flat_if_records_dependencies_without_author_graph_branch_analysis
assert state.is_complete()
[email protected]("force_compatibility_scheduler", [False, True])
+ ("outer_condition", "inner_condition", "expected_trace"),
+ [
+ (
+ True,
+ True,
+ ["outer_condition", "inner_condition", "inner_true", "inner_if", "outer_if", "sink"],
+ ),
+ (
+ True,
+ False,
+ ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"],
+ ),
+ (False, True, ["outer_condition", "outer_false", "outer_if", "sink"]),
+ (False, False, ["outer_condition", "outer_false", "outer_if", "sink"]),
+ ],
+)
+def test_fresh_nested_if_records_graph_state_dependencies_without_controller_analysis(
+ force_compatibility_scheduler: bool,
+ outer_condition: bool,
+ inner_condition: bool,
+ expected_trace: list[str],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh nested If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+
+ graph = _nested_if_graph()
+ graph.get_node("outer_condition").value = outer_condition
+ graph.get_node("inner_condition").value = inner_condition
+ state = GraphExecutionState(graph=graph)
+ dependencies_by_source = {
+ source_id: {
+ (dependency.owner_id, dependency.branch, dependency.frame)
+ for dependency in state._get_source_activation_dependencies(source_id)
+ }
+ for source_id in {"inner_condition", "inner_true", "inner_false", "inner_if"}
+ }
+
+ trace, state = _run_graph(
+ state,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+
+ assert trace == expected_trace
+ assert dependencies_by_source == {
+ "inner_condition": {("outer_if", "true_input", ())},
+ "inner_true": {("outer_if", "true_input", ()), ("inner_if", "true_input", ())},
+ "inner_false": {("outer_if", "true_input", ()), ("inner_if", "false_input", ())},
+ "inner_if": {("outer_if", "true_input", ())},
+ }
+ assert state.is_complete()
+
+
+ ("outer_condition", "inner_condition", "expected_value"),
+ [(True, True, 5), (True, False, 6), (False, True, 11), (False, False, 11)],
+)
+def test_fresh_nested_if_preserves_shared_ancestor_isolation(
+ outer_condition: bool,
+ inner_condition: bool,
+ expected_value: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh nested If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _nested_if_graph_with_shared_ancestor()
+ graph.get_node("outer_condition").value = outer_condition
+ graph.get_node("inner_condition").value = inner_condition
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ assert trace.count("shared") == int(outer_condition)
+ assert ("inner_true" in trace) is (outer_condition and inner_condition)
+ assert ("inner_false" in trace) is (outer_condition and not inner_condition)
+ assert trace.count("outer_false") == int(not outer_condition)
+ sink_id = next(iter(state.source_prepared_mapping["sink"]))
+ assert state.results[sink_id].value == expected_value
+ assert state.is_complete()
+
+
@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])
def test_fresh_noncanonical_if_compiles_branch_membership_without_controller_analysis(
force_compatibility_scheduler: bool,
@@ -3838,6 +3932,43 @@ def test_fresh_flat_if_with_saved_workflow_uses_controller_fallback(
assert branch_analysis_calls
[email protected]("unsupported_shape", ["extra_if", "mixed_iterate", "inner_fanout"])
+def test_nested_if_unsupported_shapes_use_controller_fallback(
+ unsupported_shape: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ graph = _nested_if_graph()
+ if unsupported_shape == "extra_if":
+ graph.add_node(IfInvocation(id="extra_if"))
+ elif unsupported_shape == "mixed_iterate":
+ graph.add_node(RangeInvocation(id="extra_range", start=0, stop=1, step=1))
+ graph.add_node(IterateInvocation(id="extra_iterate"))
+ graph.add_edge(create_edge("extra_range", "collection", "extra_iterate", "collection"))
+ else:
+ graph.add_node(AddInvocation(id="inner_side_consumer", b=1))
+ graph.add_edge(create_edge("inner_if", "value", "inner_side_consumer", "a"))
+
+ state = GraphExecutionState(graph=graph)
+ branch_analysis_calls: list[tuple[str, str]] = []
+ original_branch_sources = graph_module._IfActivationController._branch_sources
+
+ def record_branch_analysis(
+ controller: graph_module._IfActivationController,
+ if_node_id: str,
+ branch_field: str,
+ source_graph: Any,
+ ) -> set[str]:
+ branch_analysis_calls.append((if_node_id, branch_field))
+ return original_branch_sources(controller, if_node_id, branch_field, source_graph)
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)
+
+ assert not state._can_use_fresh_flat_if_activation()
+ dependencies = state._get_source_activation_dependencies("inner_true")
+ assert {dependency.owner_id for dependency in dependencies} >= {"inner_if"}
+ assert branch_analysis_calls
+
+
@pytest.mark.parametrize(
("outer_condition", "inner_condition", "expected_trace", "expected_history", "expected_value"),
[