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): admit four sibling If activations

JPPhotob4952cffa5ce
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index ca95289940..0800c04822 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -11,13 +11,13 @@ instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If
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, the exact bounded three-`If` chain where inner `value` feeds a middle branch and middle `value` feeds an outer
-branch, or exactly two or exactly three independent ordinary-node sibling `If`s compile opaque, frame-local activation
+branch, or exactly two, exactly three, or exactly four 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
+Current fresh sibling support includes exactly four independent `If`s with no nesting, fan-out, or other control-flow
nodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`, `true_input`,
and `false_input` inputs, and inner/middle `If`s to have no output except their direct nested branch edge. Four or more
-nested `If`s, fan-out, mixed, loop-containing, saved-workflow, legacy, and four-or-more sibling shapes remain on the
+nested `If`s, fan-out, mixed, loop-containing, saved-workflow, legacy, and five-or-more sibling 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.
@@ -262,9 +262,9 @@ 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, the exact
-bounded three-`If` inner/middle/outer chain, or exactly two or exactly three independent sibling `If`s,
+bounded three-`If` inner/middle/outer chain, or exactly two, exactly three, or exactly four independent sibling `If`s,
`GraphExecutionState` compiles opaque, frame-local activation-dependency records privately on each branch-local plan
-node. Four-or-more nesting, four-or-more sibling `If`s, fan-out, mixed, loop-containing, and saved-workflow shapes use
+node. Four-or-more nesting, five-or-more sibling `If`s, 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,
@@ -456,7 +456,7 @@ Workflow-call note:
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, the bounded
- nested pair, the exact bounded three-`If` inner/middle/outer chain, and exactly two or three independent sibling `If`s
+ nested pair, the exact bounded three-`If` inner/middle/outer chain, and exactly two, exactly three, or exactly four independent sibling `If`s
compile those dependencies in graph state. The bounded three-`If` chain also admits one middle-`If` value fan-out to
one ordinary leaf consumer; that leaf inherits only the outer branch dependency, not middle-`If` polarity. Other
fan-out remains fallback. Fresh admission leaves rejected
diff --git a/invokeai/app/services/shared/graph_if_dependencies.py b/invokeai/app/services/shared/graph_if_dependencies.py
index f7d91e815d..ef77682396 100644
--- a/invokeai/app/services/shared/graph_if_dependencies.py
+++ b/invokeai/app/services/shared/graph_if_dependencies.py
@@ -24,7 +24,7 @@ def _get_fresh_if_nodes(state: "GraphExecutionState") -> tuple[IfInvocation, ...
def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:
- """Admit fresh single-If or bounded nested-If dependency compilation."""
+ """Admit fresh bounded independent-sibling or nested-If dependency compilation."""
if state._legacy_snapshot_loaded:
return False
@@ -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) not in {2, 3}:
+ if len(if_nodes) not in {2, 3, 4}:
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) == len(if_nodes) - 1:
+ elif len(if_nodes) in {2, 3} and len(nested_edges) == len(if_nodes) - 1:
if any(
edge.source.field != "value" or edge.destination.field not in {"true_input", "false_input"}
for edge in nested_edges
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index e35b370194..8870ae4321 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -319,6 +319,7 @@ class _GenericGraphSchedulerAdapter:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
self._initializing = True
+ self._if_exec_ids: dict[str, None] = {}
self._scheduler = ExecutionScheduler(
ExecutionPlan(),
state.ready_order,
@@ -441,6 +442,8 @@ class _GenericGraphSchedulerAdapter:
node = self._state.execution_graph.nodes.get(exec_node_id)
if node is None:
raise KeyError(f"exec node {exec_node_id} missing from execution_graph")
+ if isinstance(node, IfInvocation):
+ self._if_exec_ids[exec_node_id] = None
dependencies = tuple(edge.source.node_id for edge in self._state.execution_graph._get_input_edges(exec_node_id))
activation_dependencies = self._state._get_activation_dependencies(exec_node_id)
for dependency in dependencies:
@@ -495,6 +498,17 @@ class _GenericGraphSchedulerAdapter:
for exec_node_id in self._scheduler.ready_ids:
self._project_ready_node(exec_node_id)
+ def _enqueue_activation_ready_nodes(self) -> None:
+ """Recheck prepared nodes whose activation input arrived after plan registration."""
+
+ for exec_node_id in tuple(self._if_exec_ids):
+ if exec_node_id not in self._state.indegree or exec_node_id in self._state.executed:
+ continue
+ self._state._tx_set_mapping(
+ self._state.indegree, exec_node_id, self._scheduler.indegree.get(exec_node_id, 0)
+ )
+ self.enqueue_if_ready(exec_node_id)
+
def _remove_projected(self, exec_node_id: str) -> None:
for queue in self._state._ready_queues.values():
try:
@@ -590,6 +604,11 @@ class _GenericGraphSchedulerAdapter:
self._state._tx_set_mapping(self._state.indegree, dependent, self._scheduler.indegree[dependent])
for ready_node_id in newly_ready:
self._project_ready_node(ready_node_id)
+ # Fresh If branch inputs may be materialized after the If dependency was
+ # registered, so no ordinary plan edge exists to re-enqueue the If when
+ # its selected branch completes. Recheck activation readiness here.
+ if any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):
+ self._enqueue_activation_ready_nodes()
_ExecutionScheduler._try_materialize_deferred_nested_for_body(self, exec_node_id)
if finalized_for_exec_node_id is None:
return []
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 2c78141e89..5243edf6ed 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -322,6 +322,43 @@ def _three_sibling_if_graph(
return graph
+def _four_sibling_if_graph(
+ *,
+ first_condition: bool = True,
+ second_condition: bool = True,
+ third_condition: bool = True,
+ fourth_condition: bool = True,
+ with_shared_ancestor: bool = False,
+) -> Graph:
+ graph = _three_sibling_if_graph(
+ first_condition=first_condition,
+ second_condition=second_condition,
+ third_condition=third_condition,
+ with_shared_ancestor=with_shared_ancestor,
+ )
+ graph.add_node(BooleanInvocation(id="fourth_condition", value=fourth_condition))
+ graph.add_node(AddInvocation(id="fourth_true", b=6))
+ graph.add_node(AddInvocation(id="fourth_false", a=40, b=1))
+ graph.add_node(IfInvocation(id="fourth_if"))
+ graph.add_node(AddInvocation(id="fourth_sink", b=400))
+
+ 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", "fourth_true", "a")
+ connect("fourth_condition", "value", "fourth_if", "condition")
+ connect("fourth_true", "value", "fourth_if", "true_input")
+ connect("fourth_false", "value", "fourth_if", "false_input")
+ connect("fourth_if", "value", "fourth_sink", "a")
+ return graph
+
+
def _indirectly_connected_sibling_if_graph() -> Graph:
graph = _sibling_if_graph()
graph.delete_node("second_true")
@@ -4205,6 +4242,115 @@ def test_fresh_three_sibling_ifs_shared_ancestor_executes_once_without_cross_own
assert _activation_projection(runs[0][1]) == _activation_projection(runs[1][1])
[email protected]("first_condition", [False, True])
[email protected]("second_condition", [False, True])
[email protected]("third_condition", [False, True])
[email protected]("fourth_condition", [False, True])
+def test_fresh_four_sibling_ifs_match_compatibility_for_all_polarities(
+ first_condition: bool,
+ second_condition: bool,
+ third_condition: bool,
+ fourth_condition: bool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh four-sibling If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _four_sibling_if_graph(
+ first_condition=first_condition,
+ second_condition=second_condition,
+ third_condition=third_condition,
+ fourth_condition=fourth_condition,
+ )
+ runs: list[tuple[list[str], GraphExecutionState]] = []
+ for force_compatibility_scheduler in (False, True):
+ state = GraphExecutionState(graph=graph.model_copy(deep=True))
+ 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",
+ "fourth_true" if fourth_condition else "fourth_false",
+ }
+ 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",
+ "fourth_false" if fourth_condition else "fourth_true",
+ }
+ assert state.is_complete()
+ assert selected.issubset(trace)
+ assert not unselected.intersection(trace)
+ assert not unselected.intersection(state.prepared_source_mapping.values())
+
+ _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])
[email protected]("stop_after", [1, 4, 5, 8, 9, 12])
+def test_fresh_four_sibling_ifs_checkpoint_resume_matches_fresh_execution(
+ force_compatibility_scheduler: bool,
+ stop_after: int,
+) -> None:
+ graph = _four_sibling_if_graph(
+ first_condition=True,
+ second_condition=False,
+ third_condition=True,
+ fourth_condition=False,
+ )
+ 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_fresh_four_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 four-sibling If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _four_sibling_if_graph(with_shared_ancestor=True)
+ runs: list[tuple[list[str], GraphExecutionState]] = []
+ for force_compatibility_scheduler in (False, True):
+ state = GraphExecutionState(graph=graph.model_copy(deep=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.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])
+
+
@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])
@pytest.mark.parametrize(
("first_condition", "second_condition", "third_condition"),
diff --git a/tests/app/services/shared/test_graph_if_dependencies.py b/tests/app/services/shared/test_graph_if_dependencies.py
index ccf6164bb7..0e1cfef4b4 100644
--- a/tests/app/services/shared/test_graph_if_dependencies.py
+++ b/tests/app/services/shared/test_graph_if_dependencies.py
@@ -86,7 +86,7 @@ def _sibling_if_graph(*, first_condition: bool = True, second_condition: bool =
def _sibling_if_graph_with_count(count: int) -> Graph:
graph = _sibling_if_graph()
- names = ("first", "second", "third", "fourth")
+ names = ("first", "second", "third", "fourth", "fifth")
assert 2 <= count <= len(names)
for index in range(3, count + 1):
name = names[index - 1]
@@ -379,10 +379,25 @@ def test_three_independent_sibling_ifs_admit_owner_local_frame_local_dependencie
assert state._get_source_activation_dependencies("shared") == ()
+def test_four_independent_sibling_ifs_admit_owner_local_frame_local_dependencies() -> None:
+ state = GraphExecutionState(graph=_sibling_if_graph_with_count(4))
+
+ assert state._can_use_fresh_flat_if_activation()
+ for index, name in enumerate(("first", "second", "third", "fourth"), 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 + 4,)) == (
+ ActivationDependency(owner_id=f"{name}_if", branch="false_input", frame=(index + 4,)),
+ )
+
+ assert state._get_source_activation_dependencies("shared") == ()
+
+
@pytest.mark.parametrize(
("graph_factory", "source_node_id"),
[
- pytest.param(lambda: _sibling_if_graph_with_count(4), "first_true", id="four-sibling-ifs"),
+ pytest.param(lambda: _sibling_if_graph_with_count(5), "first_true", id="five-sibling-ifs"),
pytest.param(_indirectly_connected_if_graph, "first_true", id="indirect-chain"),
pytest.param(_four_nested_if_graph, "inner_true", id="four-nested-ifs"),
pytest.param(_three_nested_if_extra_fanout_graph, "inner_true", id="three-nested-if-extra-fanout"),