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): isolate fresh If activation admission

JPPhotoc2e43f7b32b9
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 9fd147d1e0..32283613a7 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -140,13 +140,15 @@ 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
-`_IfActivationCompiler` produces opaque, frame-local activation dependencies. `_GenericGraphSchedulerAdapter` consumes
+`_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 compiler-derived branch analysis or skipped-state projection. Author-time activation
+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
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.
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 4d13cc1ade..e949765b58 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -9,7 +9,8 @@ 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
-`_IfActivationCompiler` produces opaque, frame-local activation dependencies; `_GenericGraphSchedulerAdapter` registers
+`_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
@@ -225,8 +226,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`, `_IfActivationCompiler` puts opaque, frame-local activation-dependency records on each
-branch-local plan node. `_GenericGraphSchedulerAdapter` consumes those records through the opaque plan: its readiness
+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`
+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.
@@ -383,12 +386,14 @@ Workflow-call note:
ready work. It owns iterator expansion, collector grouping, prepared-parent selection, and creation of execution-graph
edges. When matching prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannot
be selected as live inputs.
-- `_IfActivationCompiler` Compiles legacy-shaped `If` branch membership into opaque, frame-local activation dependency
- records for the generic plan. It is separate from both schedulers and does not own execution-graph topology changes.
+- `_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.
- `_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 compiler's activation dependencies, checks private gate state plus persisted activation tokens, and rejects
+ 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.
- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,
@@ -491,7 +496,7 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.
- 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 compiler and both scheduler adapters use append-only execution edges; no
+ 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
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index e49f91d7ad..e0b1d5df58 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -409,6 +409,67 @@ class _IfActivationCompiler:
return tuple(dependencies)
+class _IfActivationController:
+ """Own activation admission for concrete execution nodes.
+
+ Unlike the legacy compiler, this controller does not lower or cache a
+ branch projection. It answers one readiness question for one prepared
+ execution node from the current source graph and durable execution frame.
+ """
+
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+
+ def _branch_sources(self, if_node_id: str, branch_field: str, source_graph: "nx.DiGraph") -> set[str]:
+ 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:
+ branch_sources.update(nx.ancestors(source_graph, source_node_id))
+
+ changed = True
+ while changed:
+ changed = False
+ for source_node_id in tuple(branch_sources):
+ if all(
+ edge.destination.node_id in branch_sources
+ or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)
+ for edge in self._state.graph._get_output_edges(source_node_id)
+ ):
+ continue
+ branch_sources.remove(source_node_id)
+ changed = True
+ 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 ()
+ 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):
+ continue
+
+ matching_fields = tuple(
+ branch_field
+ for branch_field in ("true_input", "false_input")
+ if source_node_id in self._branch_sources(source_if_id, branch_field, source_graph)
+ )
+ if len(matching_fields) != 1:
+ continue
+ dependencies.append(
+ ActivationDependency(
+ owner_id=source_if_id,
+ branch=matching_fields[0],
+ frame=iteration_path,
+ )
+ )
+ return tuple(dependencies)
+
+
def _get_if_branch_exclusive_sources(state: "GraphExecutionState", if_node_id: str) -> dict[str, set[str]]:
"""Compatibility entry point for legacy ``If`` topology lowering."""
@@ -4309,6 +4370,7 @@ class GraphExecutionState(BaseModel):
_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)
+ _if_activation_controller_instance: Optional[_IfActivationController] = PrivateAttr(default=None)
_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
_execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
_execution_runtime: Optional[_ExecutionRuntime] = PrivateAttr(default=None)
@@ -4424,6 +4486,7 @@ class GraphExecutionState(BaseModel):
self._execution_scheduler = None
self._generic_graph_scheduler = None
self._if_activation_compiler_instance = None
+ self._if_activation_controller_instance = None
self._execution_runtime = None
self._if_branch_exclusive_sources = {}
self._source_graph_flat = None
@@ -4456,6 +4519,11 @@ class GraphExecutionState(BaseModel):
self._if_activation_compiler_instance = _IfActivationCompiler(self)
return self._if_activation_compiler_instance
+ def _if_activation_controller(self) -> _IfActivationController:
+ if self._if_activation_controller_instance is None:
+ self._if_activation_controller_instance = _IfActivationController(self)
+ return self._if_activation_controller_instance
+
def _get_source_graph_flat(self) -> Any:
if self._source_graph_flat is None:
self._source_graph_flat = self.graph.nx_graph_flat()
@@ -6154,7 +6222,7 @@ class GraphExecutionState(BaseModel):
)
def _get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
- return self._if_activation_compiler().get_activation_dependencies(exec_node_id)
+ return self._if_activation_controller().get_dependencies(exec_node_id)
def _remove_from_ready_queues(self, exec_node_id: str) -> None:
self._scheduler().remove_from_ready_queues(exec_node_id)
@@ -6216,6 +6284,7 @@ class GraphExecutionState(BaseModel):
self._execution_scheduler = None
self._generic_graph_scheduler = None
self._execution_runtime = None
+ self._if_activation_controller_instance = None
self._source_graph_flat = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index ca16dc843b..c7c50b3c0c 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -26,6 +26,7 @@ from invokeai.app.services.shared.graph import (
GraphExecutionState,
_ExecutionScheduler,
_GenericGraphSchedulerAdapter,
+ _IfActivationCompiler,
)
from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context
from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocation
@@ -1537,6 +1538,22 @@ def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(
assert deleted_edges == []
+def test_if_readiness_does_not_delegate_to_legacy_activation_compiler(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ graph = _nested_if_graph()
+
+ def fail_compiler(*_: object, **__: object) -> tuple[object, ...]:
+ raise AssertionError("If readiness used compiler-derived branch topology")
+
+ monkeypatch.setattr(_IfActivationCompiler, "get_activation_dependencies", fail_compiler)
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ assert trace == ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"]
+ assert state.is_complete()
+
+
@pytest.mark.parametrize(
("outer_condition", "inner_condition", "expected_trace", "expected_history", "expected_value"),
[