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.

feat(execution): declare If activation effects

JPPhotobe1af3ea3762
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 2bcdcb325c..737fbfe130 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -89,6 +89,12 @@ effects. Legacy `For`/`ForReturn` continuation scheduling is mirrored by a typed
explicit empty close. `Collect` consumes that buffer when available and retains the materializer/indegree path as its
compatibility adapter. `loop_linkage` remains association metadata and never becomes a data token.
+`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. The legacy branch scheduler still
+resolves `If` readiness and writes a compatibility token before invocation; `apply()` replaces that token by stable
+identity, and activation effects are excluded from stream handling. Loop and saved-workflow control flow remain on
+their compatibility paths until differential coverage proves their generic replacements.
+
The engine still owns runtime node materialization and queue readiness for loop-containing graphs and existing snapshots.
Ordinary static DAGs now use the generic opaque plan/scheduler through a compatibility projection. This is intentional:
the generic records preserve tested loop semantics first, while the old execution graph remains the fallback for control
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index ee6b34d2da..fe43716eed 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -331,6 +331,10 @@ class BaseInvocation(ABC, BaseModel):
bottleneck: ClassVar[Bottleneck]
execution_effects_enabled: ClassVar[bool] = False
+ """Whether this invocation may declare and emit execution effects."""
+
+ execution_activation_fields: ClassVar[frozenset[str]] = frozenset()
+ """Activation ports this invocation may emit as execution effects."""
idle_gpu_offloadable: ClassVar[bool] = False
"""Whether this node's entire execution may be temporarily re-pinned to an idle GPU when
diff --git a/invokeai/app/invocations/logic.py b/invokeai/app/invocations/logic.py
index 7cc98afbbc..dd5913b459 100644
--- a/invokeai/app/invocations/logic.py
+++ b/invokeai/app/invocations/logic.py
@@ -16,6 +16,9 @@ class IfInvocationOutput(BaseInvocationOutput):
class IfInvocation(BaseInvocation):
"""Selects between two optional inputs based on a boolean condition."""
+ execution_effects_enabled = True
+ execution_activation_fields = frozenset({"true_input", "false_input"})
+
condition: bool = InputField(default=False, description="The condition used to select an input", title="Condition")
true_input: Optional[Any] = InputField(
default=None,
@@ -31,4 +34,8 @@ class IfInvocation(BaseInvocation):
)
def invoke(self, context: InvocationContext) -> IfInvocationOutput:
+ selected_field = "true_input" if self.condition else "false_input"
+ execution = getattr(context, "execution", None)
+ if execution is not None:
+ execution.emit(selected_field, selected_field, token_kind="activation")
return IfInvocationOutput(value=self.true_input if self.condition else self.false_input)
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 6ea17e7544..bfb4af2ebe 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -185,6 +185,15 @@ and returns a capability-bound child handle. Calls without that capability remai
row creation remain owned by graph/queue adapters, so an invocation cannot mutate either directly. A cache hit never
suppresses effects: effect-enabled invocations bypass the ordinary output cache for that dispatch.
+`IfInvocation` is the first control-flow invocation to declare an activation-effect contract. It emits one
+frame-scoped activation token for the selected `true_input` or `false_input` port; `GraphExecutionState` validates that
+port against the producing invocation's declared activation fields and persists it without creating a data stream.
+The legacy `_IfBranchScheduler` still resolves readiness and writes a compatibility token before invocation; `apply()`
+validates and persists the invocation-emitted effect afterward, replacing that token by stable identity. Activation
+effects are excluded from data-stream handling. This is an additive effect declaration, not yet the generic
+successor-routing migration. Other control-flow invocations remain on their legacy paths until differential coverage
+proves each replacement.
+
`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`
identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token
kind, and optional sequence. `loop_linkage` remains association metadata and never becomes a data token. This ledger is
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 57ff412f0b..a08735b74b 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -4637,6 +4637,8 @@ class GraphExecutionState(BaseModel):
port = self._value_from_object(token, "field", "port", "output", "output_name")
if not isinstance(port, str):
continue
+ if self._value_from_object(token, "token_kind") == "activation":
+ continue
stream_id = f"{self.id}:effect:{execution_ref.reference_id}:{port}"
runtime = self._generic_runtime()
stream = runtime.streams.get(stream_id)
@@ -5125,7 +5127,31 @@ class GraphExecutionState(BaseModel):
raise ValueError("Execution effect output port must be a string")
if source_port in _RESERVED_EFFECT_PORTS:
raise ValueError(f"Execution effect references reserved output port '{source_port}'")
- if source_port not in output_fields:
+ is_activation = effect_kind == "emit" and self._value_from_object(token, "token_kind") == "activation"
+ if is_activation:
+ activation_fields = getattr(type(node), "execution_activation_fields", frozenset())
+ if source_port not in activation_fields:
+ raise ValueError(f"Execution effect references unknown activation port '{source_port}'")
+ activation_value = self._value_from_object(effect, "value")
+ if activation_value is None:
+ activation_value = self._value_from_object(token, "value")
+ if activation_value != source_port:
+ raise ValueError(
+ f"Execution effect activation value '{activation_value}' does not match port '{source_port}'"
+ )
+ if isinstance(node, IfInvocation):
+ resolved_branch = self._resolved_if_exec_branches.get(execution_ref.exec_node_id)
+ if resolved_branch is None:
+ raise ValueError(
+ f"Execution effect activation for If execution node {execution_ref.exec_node_id} "
+ "has no resolved branch"
+ )
+ if source_port != resolved_branch:
+ raise ValueError(
+ f"Execution effect activation port '{source_port}' does not match resolved If branch "
+ f"'{resolved_branch}'"
+ )
+ elif source_port not in output_fields:
raise ValueError(f"Execution effect references unknown output port '{source_port}'")
if is_loop_linkage:
if source_port != LOOP_LINKAGE_FIELD or destination_port != LOOP_LINKAGE_FIELD:
@@ -5212,6 +5238,10 @@ class GraphExecutionState(BaseModel):
token_id_base = (
f"{execution_ref.reference_id}:{port}:stream_end:{sequence if sequence is not None else 'effect'}"
)
+ elif token_kind == "activation":
+ # Compatibility If scheduling may already have lowered the same decision. Reuse its durable identity
+ # so the invocation-declared effect replaces, rather than duplicates, the activation token.
+ token_id_base = f"{execution_ref.reference_id}:activation:{port}"
else:
token_id_base = f"{execution_ref.reference_id}:{port}:{sequence if sequence is not None else 'effect'}"
token_id = token_id_base
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 2d17c0e998..a31f0340c0 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -11,6 +11,7 @@ from invokeai.app.invocations.baseinvocation import (
invocation_output,
)
from invokeai.app.invocations.fields import InputField, OutputField
+from invokeai.app.invocations.logic import IfInvocation, IfInvocationOutput
from invokeai.app.services.shared.execution_effects import (
AddEdgeEffect,
AwaitEffect,
@@ -28,8 +29,8 @@ from invokeai.app.services.shared.execution_effects import (
UnsupportedExecutionEffectError,
)
from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapability
-from invokeai.app.services.shared.execution_state_migration import dump_execution_state
-from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state
+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import (
InvocationContext,
InvocationContextData,
@@ -111,6 +112,184 @@ def test_context_default_recorder_preserves_execution_frame() -> None:
assert context.execution_effects.frame_path == (2, 1)
+ ("condition", "selected_field"),
+ [(True, "true_input"), (False, "false_input")],
+)
+def test_if_invocation_declares_selected_branch_activation_effect(condition: bool, selected_field: str) -> None:
+ context = _context()
+ context.execution_effects = ExecutionEffectsRecorder(source_node_id="if")
+ context.execution = ExecutionInterface(context.execution_effects)
+ invocation = IfInvocation(id="if", condition=condition, true_input="true", false_input="false")
+
+ result = invocation.invoke_internal_with_effects(context, _services())
+
+ assert result.output.value == ("true" if condition else "false")
+ assert len(result.effects) == 1
+ effect = result.effects[0]
+ assert isinstance(effect, EmitEffect)
+ assert effect.token.node_id == "if"
+ assert effect.token.field == selected_field
+ assert effect.token.value == selected_field
+ assert effect.token.token_kind == "activation"
+
+
[email protected]("condition", [True, False])
+def test_graph_state_applies_if_activation_and_releases_selected_branch(condition: bool) -> None:
+ graph = Graph()
+ graph.add_node(IfInvocation(id="if", condition=condition))
+ graph.add_node(ExecutionEffectsTestInvocation(id="true_branch", value=1))
+ graph.add_node(ExecutionEffectsTestInvocation(id="false_branch", value=2))
+ graph.add_node(ExecutionEffectsTestInvocation(id="successor"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="true_branch", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="false_branch", field="value"),
+ destination=EdgeConnection(node_id="if", field="false_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="if", field="value"),
+ destination=EdgeConnection(node_id="successor", field="value"),
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+ executed_source_ids: list[str] = []
+ while True:
+ invocation = state.next()
+ if invocation is None:
+ break
+ executed_source_ids.append(state.prepared_source_mapping[invocation.id])
+ execution_ref = state.get_execution_ref(invocation.id)
+ if isinstance(invocation, IfInvocation):
+ context = _context()
+ context.execution_effects = ExecutionEffectsRecorder(
+ source_node_id=invocation.id,
+ frame_path=execution_ref.frame.iteration_path,
+ )
+ context.execution = ExecutionInterface(context.execution_effects)
+ run_result = invocation.invoke_internal_with_effects(context, _services())
+ execution_ref = state.get_execution_ref(invocation.id, effect_count=len(run_result.effects))
+ state.apply(execution_ref, run_result)
+ else:
+ state.complete(invocation.id, invocation.invoke(context=MagicMock()))
+
+ selected_branch = "true_branch" if condition else "false_branch"
+ unselected_branch = "false_branch" if condition else "true_branch"
+ assert selected_branch in executed_source_ids
+ assert unselected_branch not in executed_source_ids
+ assert "successor" in executed_source_ids
+ 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" if condition else "false_input")
+ if_exec_id = next(iter(state.source_prepared_mapping["if"]))
+ if_execution_ref = state.get_execution_ref(if_exec_id)
+ persisted_effects = state.execution_effects[if_execution_ref.reference_id]
+ assert len(persisted_effects) == 1
+ assert isinstance(persisted_effects[0], EmitEffect)
+ assert persisted_effects[0].token.token_kind == "activation"
+ snapshot = dump_execution_state(state)
+ restored = load_execution_state(snapshot)
+ assert (
+ dump_execution_state(restored)["execution_effects"][if_execution_ref.reference_id]
+ == snapshot["execution_effects"][if_execution_ref.reference_id]
+ )
+ assert not any(stream.owner_id == if_exec_id for stream in state._generic_runtime().streams.values())
+
+
+def test_graph_state_rejects_unknown_if_activation_port() -> None:
+ graph = Graph()
+ graph.add_node(IfInvocation(id="if", condition=True, true_input="true", false_input="false"))
+ state = GraphExecutionState(graph=graph)
+ invocation = state.next()
+ assert invocation is not None
+ execution_ref = state.get_execution_ref(invocation.id)
+ tokens_before = state.execution_tokens.copy()
+ invalid_effect = EmitEffect(
+ token=ExecutionToken(
+ node_id=invocation.id,
+ field="bogus",
+ value="bogus",
+ token_kind="activation",
+ ),
+ value="bogus",
+ )
+
+ with pytest.raises(ValueError, match="unknown activation port"):
+ state.apply(
+ execution_ref,
+ IfInvocationOutput(value="true"),
+ effects=[invalid_effect],
+ )
+
+ assert state.execution_tokens == tokens_before
+ assert not state.execution_effects
+
+
+def test_graph_state_rejects_unselected_if_activation_port() -> None:
+ graph = Graph()
+ graph.add_node(IfInvocation(id="if", condition=True, true_input="true", false_input="false"))
+ state = GraphExecutionState(graph=graph)
+ invocation = state.next()
+ assert invocation is not None
+ execution_ref = state.get_execution_ref(invocation.id)
+ tokens_before = state.execution_tokens.copy()
+ invalid_effect = EmitEffect(
+ token=ExecutionToken(
+ node_id=invocation.id,
+ field="false_input",
+ value="false_input",
+ token_kind="activation",
+ ),
+ value="false_input",
+ )
+
+ with pytest.raises(ValueError, match="resolved If branch"):
+ state.apply(
+ execution_ref,
+ IfInvocationOutput(value="true"),
+ effects=[invalid_effect],
+ )
+
+ assert state.execution_tokens == tokens_before
+ assert not state.execution_effects
+
+
+def test_graph_state_rejects_if_activation_value_mismatch() -> None:
+ graph = Graph()
+ graph.add_node(IfInvocation(id="if", condition=True, true_input="true", false_input="false"))
+ state = GraphExecutionState(graph=graph)
+ invocation = state.next()
+ assert invocation is not None
+ execution_ref = state.get_execution_ref(invocation.id)
+ tokens_before = state.execution_tokens.copy()
+ invalid_effect = EmitEffect(
+ token=ExecutionToken(
+ node_id=invocation.id,
+ field="true_input",
+ value="false_input",
+ token_kind="activation",
+ ),
+ value="false_input",
+ )
+
+ with pytest.raises(ValueError, match="activation value"):
+ state.apply(
+ execution_ref,
+ IfInvocationOutput(value="true"),
+ effects=[invalid_effect],
+ )
+
+ assert state.execution_tokens == tokens_before
+ assert not state.execution_effects
+
+
def test_execution_token_and_ref_are_frame_aware() -> None:
token = ExecutionToken(invocation_id="node", port="value", iteration_path=(2, 4))
ref = ExecutionRef(token=token, scope="iteration")