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): support three sibling If activations

JPPhoto09b396f5b979
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 495621ae1a..1d3ce64b1b 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -170,8 +170,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`, the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no
-other consumer, or exactly two independent ordinary-node sibling `If`s compile opaque, frame-local activation
-dependencies in graph state. Deeper, fan-out, mixed, loop-containing, and saved-workflow shapes use the compatibility
+other consumer, or exactly two or exactly three independent ordinary-node sibling `If`s compile opaque, frame-local
+activation dependencies in graph state. Four or more sibling `If`s, deeper nesting, fan-out, mixed, loop-containing,
+and saved-workflow shapes use the compatibility
scheduler with the dedicated `_IfActivationController` fallback. Legacy snapshots retain their generic compatibility
projection. Legacy
skipped-state projection remains only for old snapshots. Fresh materialization prepares the condition boundary,
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index a9cdabf602..e82bf2301e 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -10,9 +10,12 @@ executes nodes from class-grouped ready queues. In normal execution, runtime exp
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`, the
exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no other
-consumer, or exactly two independent ordinary-node sibling `If`s compile opaque, frame-local activation dependencies in
-`GraphExecutionState`; unsupported fresh shapes use the compatibility scheduler with the dedicated
+consumer, or exactly two or exactly three independent ordinary-node sibling `If`s compile opaque, frame-local
+activation dependencies in `GraphExecutionState`; unsupported fresh shapes use the compatibility scheduler with the dedicated
`_IfActivationController` fallback, while legacy snapshots retain their generic compatibility projection.
+Current fresh sibling support includes exactly three independent `If`s with no nesting, fan-out, or other control-flow
+nodes. Four or more sibling `If`s, deeper nesting, fan-out, mixed, and saved-workflow shapes remain on the compatibility
+fallback. Legacy snapshots retain their generic compatibility projection and legacy skipped-state metadata.
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
@@ -256,10 +259,10 @@ 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` graph with one ordinary-node `If`, the exact one-level nested shape described above, or exactly
-two independent sibling `If`s, `GraphExecutionState` compiles opaque, frame-local activation-dependency records privately
-on each branch-local plan node. Deeper, fan-out, mixed, loop-containing, and saved-workflow shapes use the compatibility
-scheduler and `_IfActivationController` for the same records; legacy snapshots retain the generic compatibility
-projection. The controller
+two or exactly three independent sibling `If`s, `GraphExecutionState` compiles opaque, frame-local activation-dependency
+records privately on each branch-local plan node. Four or more sibling `If`s, deeper nesting, fan-out, mixed,
+loop-containing, and saved-workflow shapes use the compatibility scheduler and `_IfActivationController` for the same
+records; legacy snapshots retain the generic compatibility projection and legacy skipped-state metadata. 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
@@ -440,9 +443,9 @@ Workflow-call note:
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
- projections remain loadable.
+ records for unsupported fresh shapes and legacy prepared nodes. Fresh ordinary-node single-`If` graphs, the bounded
+ nested pair, and exactly two or three independent sibling `If`s compile those dependencies in graph state. Fresh admission leaves rejected
+ branch sources unprepared; legacy skipped-state projections remain loadable.
- Private `graph_if_dependencies.py` compiles fresh activation dependencies, and
`graph_if_runtime.py` records dependencies and evaluates admission against gates and tokens.
`GraphExecutionState` retains the method entry points, durable token/reference/effect storage,
diff --git a/invokeai/app/services/shared/graph_if_dependencies.py b/invokeai/app/services/shared/graph_if_dependencies.py
index 4415deb758..a717297dbe 100644
--- a/invokeai/app/services/shared/graph_if_dependencies.py
+++ b/invokeai/app/services/shared/graph_if_dependencies.py
@@ -48,7 +48,7 @@ def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:
return False
if len(if_nodes) != 1:
- if len(if_nodes) != 2:
+ if len(if_nodes) not in {2, 3}:
return False
if any(edge.type != "default" for edge in state.graph.edges):
@@ -77,7 +77,7 @@ def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:
return False
if any(edge.source.node_id in if_node_ids for edge in input_edges):
return False
- elif len(nested_edges) == 1:
+ elif len(if_nodes) == 2 and len(nested_edges) == 1:
nested_edge = nested_edges[0]
if nested_edge.source.field != "value" or nested_edge.destination.field not in {
"true_input",
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 31ae4aca1b..1698e54cb4 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -195,6 +195,41 @@ def _sibling_if_graph(
return graph
+def _three_sibling_if_graph(
+ *,
+ first_condition: bool = True,
+ second_condition: bool = True,
+ third_condition: bool = True,
+ with_shared_ancestor: bool = False,
+) -> Graph:
+ graph = _sibling_if_graph(
+ first_condition=first_condition,
+ second_condition=second_condition,
+ with_shared_ancestor=with_shared_ancestor,
+ )
+ graph.add_node(BooleanInvocation(id="third_condition", value=third_condition))
+ graph.add_node(AddInvocation(id="third_true", b=5))
+ graph.add_node(AddInvocation(id="third_false", a=30, b=1))
+ graph.add_node(IfInvocation(id="third_if"))
+ graph.add_node(AddInvocation(id="third_sink", b=300))
+
+ 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),
+ )
+ )
+
+ if with_shared_ancestor:
+ connect("shared", "value", "third_true", "a")
+ connect("third_condition", "value", "third_if", "condition")
+ connect("third_true", "value", "third_if", "true_input")
+ connect("third_false", "value", "third_if", "false_input")
+ connect("third_if", "value", "third_sink", "a")
+ return graph
+
+
def _indirectly_connected_sibling_if_graph() -> Graph:
graph = _sibling_if_graph()
graph.delete_node("second_true")
@@ -3939,6 +3974,196 @@ def test_fresh_sibling_ifs_shared_ancestor_executes_once(
assert state.is_complete()
+ ("first_condition", "second_condition", "third_condition"),
+ [
+ (True, True, True),
+ (True, True, False),
+ (True, False, True),
+ (True, False, False),
+ (False, True, True),
+ (False, True, False),
+ (False, False, True),
+ (False, False, False),
+ ],
+)
+def test_fresh_three_sibling_ifs_select_only_owner_local_branches_and_match_compatibility(
+ first_condition: bool,
+ second_condition: bool,
+ third_condition: bool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh three-sibling If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ runs: list[tuple[list[str], GraphExecutionState]] = []
+
+ for force_compatibility_scheduler in (False, True):
+ state = GraphExecutionState(
+ graph=_three_sibling_if_graph(
+ first_condition=first_condition,
+ second_condition=second_condition,
+ third_condition=third_condition,
+ )
+ )
+ assert state._can_use_fresh_flat_if_activation()
+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)
+ runs.append((trace, state))
+
+ selected = {
+ "first_true" if first_condition else "first_false",
+ "second_true" if second_condition else "second_false",
+ "third_true" if third_condition else "third_false",
+ }
+ expected_sources = {
+ "first_condition",
+ "second_condition",
+ "third_condition",
+ "first_if",
+ "second_if",
+ "third_if",
+ "first_sink",
+ "second_sink",
+ "third_sink",
+ *selected,
+ }
+ unselected = {
+ "first_false" if first_condition else "first_true",
+ "second_false" if second_condition else "second_true",
+ "third_false" if third_condition else "third_true",
+ }
+ assert set(state.source_prepared_mapping) == expected_sources
+ assert set(trace) == expected_sources
+ assert not unselected.intersection(trace)
+
+ dependencies_by_source = {
+ source_id: {
+ (dependency.owner_id, dependency.branch, dependency.frame)
+ for execution_id, source_id_value in state.prepared_source_mapping.items()
+ if source_id_value == source_id
+ for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())
+ }
+ for source_id in selected
+ }
+ assert dependencies_by_source == {
+ "first_true" if first_condition else "first_false": {
+ ("first_if", "true_input" if first_condition else "false_input", ())
+ },
+ "second_true" if second_condition else "second_false": {
+ ("second_if", "true_input" if second_condition else "false_input", ())
+ },
+ "third_true" if third_condition else "third_false": {
+ ("third_if", "true_input" if third_condition else "false_input", ())
+ },
+ }
+ first_sink_id = next(iter(state.source_prepared_mapping["first_sink"]))
+ second_sink_id = next(iter(state.source_prepared_mapping["second_sink"]))
+ third_sink_id = next(iter(state.source_prepared_mapping["third_sink"]))
+ assert state.results[first_sink_id].value == (103 if first_condition else 111)
+ assert state.results[second_sink_id].value == (204 if second_condition else 221)
+ assert state.results[third_sink_id].value == (305 if third_condition else 331)
+ assert state.is_complete()
+
+ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])
+ assert runs[0][0] == runs[1][0]
+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])
+ assert _activation_projection(runs[0][1]) == _activation_projection(runs[1][1])
+
+
+def test_fresh_three_sibling_ifs_shared_ancestor_executes_once_without_cross_owner_dependencies(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh three-sibling If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ runs: list[tuple[list[str], GraphExecutionState]] = []
+
+ for force_compatibility_scheduler in (False, True):
+ state = GraphExecutionState(graph=_three_sibling_if_graph(with_shared_ancestor=True))
+ assert state._can_use_fresh_flat_if_activation()
+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)
+ runs.append((trace, state))
+
+ assert trace.count("shared") == 1
+ assert state.results[next(iter(state.source_prepared_mapping["first_sink"]))].value == 105
+ assert state.results[next(iter(state.source_prepared_mapping["second_sink"]))].value == 206
+ assert state.results[next(iter(state.source_prepared_mapping["third_sink"]))].value == 307
+ assert state.is_complete()
+
+ for source_id, if_id, branch in (
+ ("first_true", "first_if", "true_input"),
+ ("second_true", "second_if", "true_input"),
+ ("third_true", "third_if", "true_input"),
+ ):
+ execution_id = next(
+ execution_id
+ for execution_id, prepared_source_id in state.prepared_source_mapping.items()
+ if prepared_source_id == source_id
+ )
+ assert {
+ (dependency.owner_id, dependency.branch, dependency.frame)
+ for dependency in state._if_activation_dependencies_by_exec[execution_id]
+ } == {(if_id, branch, ())}
+
+ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])
+ assert runs[0][0] == runs[1][0]
+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])
+ assert _activation_projection(runs[0][1]) == _activation_projection(runs[1][1])
+
+
[email protected]("force_compatibility_scheduler", [False, True])
+ ("first_condition", "second_condition", "third_condition"),
+ [
+ (True, True, True),
+ (True, True, False),
+ (True, False, True),
+ (True, False, False),
+ (False, True, True),
+ (False, True, False),
+ (False, False, True),
+ (False, False, False),
+ ],
+)
[email protected]("stop_after", range(1, 12))
+def test_fresh_three_sibling_ifs_checkpoint_resume_matches_fresh_execution(
+ force_compatibility_scheduler: bool,
+ first_condition: bool,
+ second_condition: bool,
+ third_condition: bool,
+ stop_after: int,
+) -> None:
+ graph = _three_sibling_if_graph(
+ first_condition=first_condition,
+ second_condition=second_condition,
+ third_condition=third_condition,
+ )
+ expected_trace, expected_state = _run_graph(
+ GraphExecutionState(graph=graph.model_copy(deep=True)),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+ checkpoint_trace, checkpoint_state = _run_graph(
+ GraphExecutionState(graph=graph.model_copy(deep=True)),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ stop_after=stop_after,
+ )
+
+ restored = load_execution_state(dump_execution_state(checkpoint_state))
+ if force_compatibility_scheduler:
+ _restore_compatibility_scheduler(restored)
+ resumed_trace, resumed_state = _run_graph(
+ restored,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+
+ assert checkpoint_trace + resumed_trace == expected_trace
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)
+ assert resumed_state.is_complete()
+
+
def test_sibling_if_unsupported_saved_workflow_keeps_controller_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/app/services/shared/test_graph_if_dependencies.py b/tests/app/services/shared/test_graph_if_dependencies.py
index 35b816908b..18f86a32ff 100644
--- a/tests/app/services/shared/test_graph_if_dependencies.py
+++ b/tests/app/services/shared/test_graph_if_dependencies.py
@@ -84,6 +84,51 @@ def _sibling_if_graph(*, first_condition: bool = True, second_condition: bool =
return graph
+def _sibling_if_graph_with_count(count: int) -> Graph:
+ graph = _sibling_if_graph()
+ names = ("first", "second", "third", "fourth")
+ assert 2 <= count <= len(names)
+ for index in range(3, count + 1):
+ name = names[index - 1]
+ graph.add_node(BooleanInvocation(id=f"{name}_condition", value=index % 2 == 1))
+ graph.add_node(AddInvocation(id=f"{name}_true", b=index + 2))
+ graph.add_node(AddInvocation(id=f"{name}_false", a=index * 10, b=1))
+ graph.add_node(IfInvocation(id=f"{name}_if"))
+ graph.add_node(AddInvocation(id=f"{name}_sink", b=index * 100))
+ graph.add_edge(_edge("shared", "value", f"{name}_true", "a"))
+ graph.add_edge(_edge(f"{name}_condition", "value", f"{name}_if", "condition"))
+ graph.add_edge(_edge(f"{name}_true", "value", f"{name}_if", "true_input"))
+ graph.add_edge(_edge(f"{name}_false", "value", f"{name}_if", "false_input"))
+ graph.add_edge(_edge(f"{name}_if", "value", f"{name}_sink", "a"))
+ return graph
+
+
+def _three_nested_if_graph() -> Graph:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="outer_condition", value=True))
+ graph.add_node(BooleanInvocation(id="middle_condition", value=False))
+ graph.add_node(BooleanInvocation(id="inner_condition", value=True))
+ graph.add_node(AddInvocation(id="inner_true", a=2, b=2))
+ graph.add_node(AddInvocation(id="inner_false", a=3, b=3))
+ graph.add_node(AddInvocation(id="middle_false", a=10, b=0))
+ graph.add_node(AddInvocation(id="outer_false", a=20, b=0))
+ graph.add_node(IfInvocation(id="inner_if"))
+ graph.add_node(IfInvocation(id="middle_if"))
+ graph.add_node(IfInvocation(id="outer_if"))
+ graph.add_node(AddInvocation(id="sink", b=1))
+ graph.add_edge(_edge("inner_condition", "value", "inner_if", "condition"))
+ graph.add_edge(_edge("inner_true", "value", "inner_if", "true_input"))
+ graph.add_edge(_edge("inner_false", "value", "inner_if", "false_input"))
+ graph.add_edge(_edge("middle_condition", "value", "middle_if", "condition"))
+ graph.add_edge(_edge("inner_if", "value", "middle_if", "true_input"))
+ graph.add_edge(_edge("middle_false", "value", "middle_if", "false_input"))
+ graph.add_edge(_edge("outer_condition", "value", "outer_if", "condition"))
+ graph.add_edge(_edge("middle_if", "value", "outer_if", "true_input"))
+ graph.add_edge(_edge("outer_false", "value", "outer_if", "false_input"))
+ graph.add_edge(_edge("outer_if", "value", "sink", "a"))
+ return graph
+
+
def _indirectly_connected_if_graph() -> Graph:
graph = Graph()
graph.add_node(BooleanInvocation(id="first_condition", value=True))
@@ -271,6 +316,50 @@ def test_sibling_if_dependencies_are_owner_local_and_frame_local() -> None:
)
+def test_three_independent_sibling_ifs_admit_owner_local_frame_local_dependencies() -> None:
+ state = GraphExecutionState(graph=_sibling_if_graph_with_count(3))
+
+ assert state._can_use_fresh_flat_if_activation()
+ for index, name in enumerate(("first", "second", "third"), start=1):
+ assert state._get_source_activation_dependencies(f"{name}_true", (index,)) == (
+ ActivationDependency(owner_id=f"{name}_if", branch="true_input", frame=(index,)),
+ )
+ assert state._get_source_activation_dependencies(f"{name}_false", (index + 3,)) == (
+ ActivationDependency(owner_id=f"{name}_if", branch="false_input", frame=(index + 3,)),
+ )
+
+ assert state._get_source_activation_dependencies("shared") == ()
+
+
+ ("graph_factory", "source_node_id"),
+ [
+ pytest.param(lambda: _sibling_if_graph_with_count(4), "first_true", id="four-sibling-ifs"),
+ pytest.param(_three_nested_if_graph, "inner_true", id="three-nested-ifs"),
+ ],
+)
+def test_unsupported_if_shapes_use_controller_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+ graph_factory: Any,
+ source_node_id: str,
+) -> None:
+ expected = (ActivationDependency(owner_id="fallback", branch="true_input", frame=(9,)),)
+ calls: list[tuple[str, tuple[int, ...]]] = []
+
+ def get_source_dependencies(
+ _controller: Any, actual_source_node_id: str, iteration_path: tuple[int, ...]
+ ) -> tuple[ActivationDependency, ...]:
+ calls.append((actual_source_node_id, iteration_path))
+ return expected
+
+ monkeypatch.setattr(graph_module._IfActivationController, "get_source_dependencies", get_source_dependencies)
+ state = GraphExecutionState(graph=graph_factory())
+
+ assert not state._can_use_fresh_flat_if_activation()
+ assert state._get_source_activation_dependencies(source_node_id, (9,)) == expected
+ assert calls == [(source_node_id, (9,))]
+
+
def test_indirectly_connected_ifs_retain_controller_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
state = GraphExecutionState(graph=_indirectly_connected_if_graph())
calls: list[tuple[str, str]] = []