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): extract If activation runtime

JPPhoto8b5c021be3a1
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index fc1010bd80..8e0fde63eb 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -437,6 +437,10 @@ Workflow-call note:
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.
+- 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,
+ derived caches, transaction journal, and fallback controller selection.
- `_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
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 82dbd938d0..d1c9bfc378 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -58,7 +58,7 @@ from invokeai.app.invocations.loops import (
ForReturnInvocationOutput,
LoopState,
)
-from invokeai.app.services.shared import graph_if_dependencies
+from invokeai.app.services.shared import graph_if_dependencies, graph_if_runtime
from invokeai.app.services.shared.execution_effects import ContinuationEffect
from invokeai.app.services.shared.execution_effects import ExecutionRef as EffectExecutionRef
from invokeai.app.services.shared.execution_engine.child import (
@@ -2464,50 +2464,13 @@ class GraphExecutionState(BaseModel):
return graph_if_dependencies._get_source_activation_dependencies(self, source_node_id, iteration_path)
def _record_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
- dependencies = self._if_activation_dependencies_by_exec.get(exec_node_id)
- if dependencies is not None:
- return dependencies
- source_node_id = self._prepared_registry().get_source_node_id(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
+ return graph_if_runtime._record_activation_dependencies(self, exec_node_id)
def _is_source_activation_admitted(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:
- dependencies = self._get_source_activation_dependencies(source_node_id, iteration_path)
- return not dependencies or all(
- self._is_activation_dependency_satisfied(dependency) for dependency in dependencies
- )
+ return graph_if_runtime._is_source_activation_admitted(self, source_node_id, iteration_path)
def _is_source_inactive(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:
- if not self._can_use_fresh_flat_if_activation():
- return self._if_activation_controller().is_source_inactive(source_node_id, iteration_path)
-
- dependencies = self._get_source_activation_dependencies(source_node_id, iteration_path)
- if not dependencies:
- return False
- if iteration_path:
- return any(self._is_activation_dependency_rejected(dependency) for dependency in dependencies)
-
- frames = {
- self._get_iteration_path(exec_node_id)
- for dependency in dependencies
- for exec_node_id in self._prepared_registry().get_prepared_ids(dependency.owner_id)
- }
- if not frames:
- return False
- return all(
- self._get_source_activation_dependencies(source_node_id, frame)
- and any(
- self._is_activation_dependency_rejected(frame_dependency)
- for frame_dependency in self._get_source_activation_dependencies(source_node_id, frame)
- )
- for frame in frames
- )
+ return graph_if_runtime._is_source_inactive(self, source_node_id, iteration_path)
def _get_execution_graph_flat(self) -> Any:
if self._execution_graph_flat is None:
@@ -2920,107 +2883,19 @@ class GraphExecutionState(BaseModel):
)
def _activation_gate(self, exec_node_id: str) -> ActivationGate:
- return self._generic_runtime().register_gate(
- gate_id=exec_node_id,
- owner_id=exec_node_id,
- frame=self._engine_frame(self._get_iteration_path(exec_node_id)),
- branches=("true_input", "false_input"),
- )
+ return graph_if_runtime._activation_gate(self, exec_node_id)
def _record_compatibility_activation_token(self, exec_node_id: str, selected_field: str) -> None:
- execution_ref = self._expected_execution_ref(exec_node_id)
- activation_token_id = f"{execution_ref.reference_id}:activation:{selected_field}"
- self._tx_set_mapping(
- self.execution_tokens,
- activation_token_id,
- ExecutionToken(
- token_id=activation_token_id,
- reference_id=execution_ref.reference_id,
- owner_node_id=exec_node_id,
- port=selected_field,
- frame=execution_ref.frame,
- value=selected_field,
- token_kind="activation",
- ),
- )
+ return graph_if_runtime._record_compatibility_activation_token(self, exec_node_id, selected_field)
def _is_activation_dependency_satisfied(self, dependency: ActivationDependency) -> bool:
- """Check one opaque plan requirement against durable gate and token state."""
- matching_gate_ids = [
- prepared_if_id
- for prepared_if_id in self._prepared_registry().get_prepared_ids(dependency.owner_id)
- if self._get_iteration_path(prepared_if_id) == dependency.frame
- ]
- if not matching_gate_ids:
- return False
-
- for gate_id in matching_gate_ids:
- expected_ref = self._expected_execution_ref(gate_id)
- gate = self._activation_gate(gate_id)
- if (
- gate.frame.state_id != expected_ref.frame.state_id
- or gate.frame.frame_id != expected_ref.frame.frame_id
- or gate.frame.iteration_path != expected_ref.frame.iteration_path
- or gate.frame.workflow_call_depth != expected_ref.frame.workflow_call_depth
- or gate.frame.iteration_path != dependency.frame
- ):
- return False
- if not gate.is_active(dependency.branch, owner_id=gate_id, frame=gate.frame):
- return False
- if not any(
- token.token_id == f"{expected_ref.reference_id}:activation:{dependency.branch}"
- and token.reference_id == expected_ref.reference_id
- and token.owner_node_id == gate_id
- and token.token_kind == "activation"
- and token.port == dependency.branch
- and token.value == dependency.branch
- and token.frame.state_id == expected_ref.frame.state_id
- and token.frame.frame_id == expected_ref.frame.frame_id
- and token.frame.iteration_path == expected_ref.frame.iteration_path
- and token.frame.workflow_call_depth == expected_ref.frame.workflow_call_depth
- for token in self.execution_tokens.values()
- ):
- return False
- return True
+ return graph_if_runtime._is_activation_dependency_satisfied(self, dependency)
def _is_activation_dependency_rejected(self, dependency: ActivationDependency) -> bool:
- """Return whether a resolved gate explicitly selected another branch."""
-
- matching_gate_ids = [
- prepared_if_id
- for prepared_if_id in self._prepared_registry().get_prepared_ids(dependency.owner_id)
- if self._get_iteration_path(prepared_if_id) == dependency.frame
- ]
- for gate_id in matching_gate_ids:
- gate = self._activation_gate(gate_id)
- expected_frame = self._expected_execution_ref(gate_id).frame
- if (
- gate.frame.state_id != expected_frame.state_id
- or gate.frame.frame_id != expected_frame.frame_id
- or gate.frame.iteration_path != expected_frame.iteration_path
- or gate.frame.workflow_call_depth != expected_frame.workflow_call_depth
- ):
- return False
- if gate.resolved and gate.selected_branch != dependency.branch:
- return True
- return False
+ return graph_if_runtime._is_activation_dependency_rejected(self, dependency)
def _resolve_activation_gate(self, exec_node_id: str, branch: str) -> bool:
- runtime = self._generic_runtime()
- gate = self._activation_gate(exec_node_id)
- if gate.resolved and gate.selected_branch == branch:
- return False
- previous = ActivationGate.model_validate(gate.model_dump(mode="python"))
- changed = runtime.resolve_gate(
- exec_node_id,
- exec_node_id,
- gate.frame,
- branch,
- )
- if changed:
- self._completed_source_ids_cache = None
- self._tx_record(lambda: runtime.replace_gate(previous))
- return changed
+ return graph_if_runtime._resolve_activation_gate(self, exec_node_id, branch)
def _iteration_stream_id(self, source_node_id: str, parent_path: tuple[int, ...]) -> str:
path = ",".join(str(index) for index in parent_path)
@@ -4333,19 +4208,13 @@ class GraphExecutionState(BaseModel):
return self._scheduler().queue_for(cls_name)
def _is_deferred_by_unresolved_if(self, exec_node_id: str) -> bool:
- dependencies = self._get_activation_dependencies(exec_node_id)
- if not dependencies or any(self._is_activation_dependency_rejected(dependency) for dependency in dependencies):
- return False
- return not all(self._is_activation_dependency_satisfied(dependency) for dependency in dependencies)
+ return graph_if_runtime._is_deferred_by_unresolved_if(self, exec_node_id)
def _has_rejected_activation_dependency(self, exec_node_id: str) -> bool:
- return any(
- self._is_activation_dependency_rejected(dependency)
- for dependency in self._get_activation_dependencies(exec_node_id)
- )
+ return graph_if_runtime._has_rejected_activation_dependency(self, exec_node_id)
def _get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
- return self._record_activation_dependencies(exec_node_id)
+ return graph_if_runtime._get_activation_dependencies(self, exec_node_id)
def _remove_from_ready_queues(self, exec_node_id: str) -> None:
self._scheduler().remove_from_ready_queues(exec_node_id)
diff --git a/invokeai/app/services/shared/graph_if_runtime.py b/invokeai/app/services/shared/graph_if_runtime.py
new file mode 100644
index 0000000000..40785edec7
--- /dev/null
+++ b/invokeai/app/services/shared/graph_if_runtime.py
@@ -0,0 +1,192 @@
+"""Activation admission helpers operating on state-owned runtime and durable records."""
+
+from typing import TYPE_CHECKING
+
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.services.shared.execution_engine.primitives import ActivationGate
+from invokeai.app.services.shared.execution_engine.scheduler import ActivationDependency
+from invokeai.app.services.shared.graph_models import ExecutionToken
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+def _record_activation_dependencies(
+ state: "GraphExecutionState", exec_node_id: str
+) -> tuple[ActivationDependency, ...]:
+ dependencies = state._if_activation_dependencies_by_exec.get(exec_node_id)
+ if dependencies is not None:
+ return dependencies
+ source_node_id = state._prepared_registry().get_source_node_id(exec_node_id)
+ if any(isinstance(node, IfInvocation) for node in state.graph.nodes.values()):
+ dependencies = state._get_source_activation_dependencies(
+ source_node_id, state._get_iteration_path(exec_node_id)
+ )
+ else:
+ dependencies = ()
+ state._tx_set_mapping(state._if_activation_dependencies_by_exec, exec_node_id, dependencies)
+ return dependencies
+
+
+def _is_source_activation_admitted(
+ state: "GraphExecutionState", source_node_id: str, iteration_path: tuple[int, ...] = ()
+) -> bool:
+ dependencies = state._get_source_activation_dependencies(source_node_id, iteration_path)
+ return not dependencies or all(state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)
+
+
+def _is_source_inactive(
+ state: "GraphExecutionState", source_node_id: str, iteration_path: tuple[int, ...] = ()
+) -> bool:
+ if not state._can_use_fresh_flat_if_activation():
+ return state._if_activation_controller().is_source_inactive(source_node_id, iteration_path)
+
+ dependencies = state._get_source_activation_dependencies(source_node_id, iteration_path)
+ if not dependencies:
+ return False
+ if iteration_path:
+ return any(state._is_activation_dependency_rejected(dependency) for dependency in dependencies)
+
+ frames = {
+ state._get_iteration_path(exec_node_id)
+ for dependency in dependencies
+ for exec_node_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
+ }
+ if not frames:
+ return False
+ return all(
+ state._get_source_activation_dependencies(source_node_id, frame)
+ and any(
+ state._is_activation_dependency_rejected(frame_dependency)
+ for frame_dependency in state._get_source_activation_dependencies(source_node_id, frame)
+ )
+ for frame in frames
+ )
+
+
+def _activation_gate(state: "GraphExecutionState", exec_node_id: str) -> ActivationGate:
+ return state._generic_runtime().register_gate(
+ gate_id=exec_node_id,
+ owner_id=exec_node_id,
+ frame=state._engine_frame(state._get_iteration_path(exec_node_id)),
+ branches=("true_input", "false_input"),
+ )
+
+
+def _record_compatibility_activation_token(
+ state: "GraphExecutionState", exec_node_id: str, selected_field: str
+) -> None:
+ execution_ref = state._expected_execution_ref(exec_node_id)
+ activation_token_id = f"{execution_ref.reference_id}:activation:{selected_field}"
+ state._tx_set_mapping(
+ state.execution_tokens,
+ activation_token_id,
+ ExecutionToken(
+ token_id=activation_token_id,
+ reference_id=execution_ref.reference_id,
+ owner_node_id=exec_node_id,
+ port=selected_field,
+ frame=execution_ref.frame,
+ value=selected_field,
+ token_kind="activation",
+ ),
+ )
+
+
+def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:
+ """Check one opaque plan requirement against durable gate and token state."""
+ matching_gate_ids = [
+ prepared_if_id
+ for prepared_if_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
+ if state._get_iteration_path(prepared_if_id) == dependency.frame
+ ]
+ if not matching_gate_ids:
+ return False
+
+ for gate_id in matching_gate_ids:
+ expected_ref = state._expected_execution_ref(gate_id)
+ gate = state._activation_gate(gate_id)
+ if (
+ gate.frame.state_id != expected_ref.frame.state_id
+ or gate.frame.frame_id != expected_ref.frame.frame_id
+ or gate.frame.iteration_path != expected_ref.frame.iteration_path
+ or gate.frame.workflow_call_depth != expected_ref.frame.workflow_call_depth
+ or gate.frame.iteration_path != dependency.frame
+ ):
+ return False
+ if not gate.is_active(dependency.branch, owner_id=gate_id, frame=gate.frame):
+ return False
+ if not any(
+ token.token_id == f"{expected_ref.reference_id}:activation:{dependency.branch}"
+ and token.reference_id == expected_ref.reference_id
+ and token.owner_node_id == gate_id
+ and token.token_kind == "activation"
+ and token.port == dependency.branch
+ and token.value == dependency.branch
+ and token.frame.state_id == expected_ref.frame.state_id
+ and token.frame.frame_id == expected_ref.frame.frame_id
+ and token.frame.iteration_path == expected_ref.frame.iteration_path
+ and token.frame.workflow_call_depth == expected_ref.frame.workflow_call_depth
+ for token in state.execution_tokens.values()
+ ):
+ return False
+ return True
+
+
+def _is_activation_dependency_rejected(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:
+ """Return whether a resolved gate explicitly selected another branch."""
+
+ matching_gate_ids = [
+ prepared_if_id
+ for prepared_if_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
+ if state._get_iteration_path(prepared_if_id) == dependency.frame
+ ]
+ for gate_id in matching_gate_ids:
+ gate = state._activation_gate(gate_id)
+ expected_frame = state._expected_execution_ref(gate_id).frame
+ if (
+ gate.frame.state_id != expected_frame.state_id
+ or gate.frame.frame_id != expected_frame.frame_id
+ or gate.frame.iteration_path != expected_frame.iteration_path
+ or gate.frame.workflow_call_depth != expected_frame.workflow_call_depth
+ ):
+ return False
+ if gate.resolved and gate.selected_branch != dependency.branch:
+ return True
+ return False
+
+
+def _resolve_activation_gate(state: "GraphExecutionState", exec_node_id: str, branch: str) -> bool:
+ runtime = state._generic_runtime()
+ gate = state._activation_gate(exec_node_id)
+ if gate.resolved and gate.selected_branch == branch:
+ return False
+ previous = ActivationGate.model_validate(gate.model_dump(mode="python"))
+ changed = runtime.resolve_gate(
+ exec_node_id,
+ exec_node_id,
+ gate.frame,
+ branch,
+ )
+ if changed:
+ state._completed_source_ids_cache = None
+ state._tx_record(lambda: runtime.replace_gate(previous))
+ return changed
+
+
+def _is_deferred_by_unresolved_if(state: "GraphExecutionState", exec_node_id: str) -> bool:
+ dependencies = state._get_activation_dependencies(exec_node_id)
+ if not dependencies or any(state._is_activation_dependency_rejected(dependency) for dependency in dependencies):
+ return False
+ return not all(state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)
+
+
+def _has_rejected_activation_dependency(state: "GraphExecutionState", exec_node_id: str) -> bool:
+ return any(
+ state._is_activation_dependency_rejected(dependency)
+ for dependency in state._get_activation_dependencies(exec_node_id)
+ )
+
+
+def _get_activation_dependencies(state: "GraphExecutionState", exec_node_id: str) -> tuple[ActivationDependency, ...]:
+ return state._record_activation_dependencies(exec_node_id)
diff --git a/tests/app/services/shared/test_graph_if_runtime.py b/tests/app/services/shared/test_graph_if_runtime.py
new file mode 100644
index 0000000000..f998c71204
--- /dev/null
+++ b/tests/app/services/shared/test_graph_if_runtime.py
@@ -0,0 +1,110 @@
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.services.shared.execution_engine.scheduler import ActivationDependency
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.graph_runtime_records import _ApplyTransaction
+
+
+def state() -> GraphExecutionState:
+ state = GraphExecutionState(graph=Graph(nodes={"if": IfInvocation(id="if")}))
+ state.execution_graph.add_node(IfInvocation(id="if-exec"))
+ state._prepared_registry().register("if-exec", "if")
+ state._prepared_registry().set_iteration_path("if-exec", (2,))
+ return state
+
+
+def test_runtime_import_without_graph() -> None:
+ script = textwrap.dedent(
+ """
+ import builtins
+ import sys
+
+ real_import = builtins.__import__
+
+ def blocked_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "invokeai.app.services.shared.graph":
+ raise AssertionError("runtime imported graph")
+ return real_import(name, globals, locals, fromlist, level)
+
+ builtins.__import__ = blocked_import
+ import invokeai.app.services.shared.graph_if_runtime
+ assert "invokeai.app.services.shared.graph" not in sys.modules
+ """
+ )
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=300)
+ assert result.returncode == 0, result.stderr
+
+
+ "field,value",
+ [("state_id", "foreign"), ("frame_id", "foreign"), ("iteration_path", (3,)), ("workflow_call_depth", 1)],
+)
[email protected]("target", ["gate", "token"])
+def test_live_activation_frame_mismatch(state: GraphExecutionState, field: str, value: object, target: str) -> None:
+ dependency = ActivationDependency(owner_id="if", branch="true_input", frame=(2,))
+ state._resolve_activation_gate("if-exec", "true_input")
+ state._record_compatibility_activation_token("if-exec", "true_input")
+ assert state._is_activation_dependency_satisfied(dependency)
+
+ if target == "gate":
+ gate = state._activation_gate("if-exec")
+ state._generic_runtime().replace_gate(
+ gate.model_copy(update={"frame": gate.frame.model_copy(update={field: value})})
+ )
+ else:
+ token_id, token = next(iter(state.execution_tokens.items()))
+ state.execution_tokens[token_id] = token.model_copy(
+ update={"frame": token.frame.model_copy(update={field: value})}
+ )
+
+ if target == "gate":
+ with pytest.raises(ValueError, match="activation gate identity conflict"):
+ state._is_activation_dependency_satisfied(dependency)
+ with pytest.raises(ValueError, match="activation gate identity conflict"):
+ state._is_activation_dependency_rejected(
+ ActivationDependency(owner_id="if", branch="false_input", frame=(2,))
+ )
+ else:
+ assert not state._is_activation_dependency_satisfied(dependency)
+
+
+def test_unresolved_dependency_is_deferred_but_rejected_is_not(state: GraphExecutionState) -> None:
+ dependency = ActivationDependency(owner_id="if", branch="false_input", frame=(2,))
+ state._if_activation_dependencies_by_exec["consumer"] = (dependency,)
+ assert state._is_deferred_by_unresolved_if("consumer")
+ assert not state._has_rejected_activation_dependency("consumer")
+
+ state._resolve_activation_gate("if-exec", "true_input")
+ assert not state._is_deferred_by_unresolved_if("consumer")
+ assert state._has_rejected_activation_dependency("consumer")
+ assert not state._is_activation_dependency_satisfied(dependency)
+
+
+def test_activation_resolution_and_token_are_idempotent_and_rollback(state: GraphExecutionState) -> None:
+ gate_before = state._activation_gate("if-exec").model_dump()
+ state._completed_source_ids_cache = {"cached"}
+ transaction = _ApplyTransaction()
+ state._apply_transaction = transaction
+ assert state._resolve_activation_gate("if-exec", "true_input")
+ assert state._completed_source_ids_cache is None
+ state._record_compatibility_activation_token("if-exec", "true_input")
+ tokens_before = dict(state.execution_tokens)
+ state._completed_source_ids_cache = {"cached-again"}
+ assert not state._resolve_activation_gate("if-exec", "true_input")
+ assert state._completed_source_ids_cache == {"cached-again"}
+ state._record_compatibility_activation_token("if-exec", "true_input")
+ assert state.execution_tokens == tokens_before
+ assert state._record_activation_dependencies("if-exec") == ()
+ assert "if-exec" in state._if_activation_dependencies_by_exec
+
+ transaction.rollback()
+ state._apply_transaction = None
+ assert state._activation_gate("if-exec").model_dump() == gate_before
+ assert state.execution_tokens == {}
+ assert "if-exec" not in state._if_activation_dependencies_by_exec