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): make If activation dependencies authoritative

JPPhoto9122e47df0e5
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 22d7d9a1fc..0ee21c8e14 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -8,8 +8,10 @@ Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**
iterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), and
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`; a private graph adapter supplies the `If`
-activation predicate and projects compatibility skips. Control-flow topology lowering remains behind the legacy graph adapter.
+and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`; a private graph adapter derives opaque,
+frame-local `If` activation dependencies, checks their private gate state plus persisted activation tokens, and projects
+compatibility skips.
+Control-flow topology lowering remains behind the legacy graph adapter.
The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and
authorized child-dependency records are stored in
`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while
@@ -49,10 +51,10 @@ external interface remains frozen; generated schemas may change only for additiv
results, tokens, and workflow-call state after rehydration.
- `ChildExecutionCapability`, `ChildExecutionRecord`, and `ChildDependencyRecord` validate authorized parent/child
relationships, resource limits, ordered all-of aggregation, failure, cancellation, and idempotent completion.
-- `ExecutionPlan` stores opaque execution-node IDs, class names, prerequisite IDs, frame values, and stable insertion
- order. `ExecutionScheduler` owns generic readiness, opaque readiness predicates, intentional skips, deterministic
- ordering, completion, and durable plan rehydration. It does not import invocation classes and cannot alter author-time
- graph or frontend contracts.
+- `ExecutionPlan` stores opaque execution-node IDs, class names, prerequisite IDs, frame values, activation-dependency
+ records, and stable insertion order. `ExecutionScheduler` owns generic readiness, opaque readiness predicates,
+ intentional skips, deterministic ordering, completion, and durable plan rehydration. It does not import invocation
+ classes and cannot alter author-time graph or frontend contracts.
- `ExecutionEngineRuntime` owns these records for one graph state. It is private runtime machinery; it is not a new
frontend node, input handle, or public workflow contract.
@@ -162,8 +164,10 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
- `execution_effects: dict[str, list[Any]]` - JSON-safe effects accepted for each execution reference.
- **Ready queues grouped by class** (private projection): `_ready_queues: dict[class_name, deque[str]]` and
`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the generic
- scheduler; loop and saved-workflow graphs retain the legacy scheduler. Optional `ready_order: list[str]` prioritizes
- classes. Queues are rebuilt from persisted execution state when a session is deserialized.
+ scheduler; the `If` adapter stores frame-local activation dependencies whose private gate state plus persisted token
+ checks control generic branch readiness. Loop and saved-workflow graphs retain the legacy scheduler. Optional
+ `ready_order: list[str]` prioritizes classes. Queues are rebuilt from persisted execution state when a session is
+ deserialized.
### 4.2 Core methods
@@ -191,20 +195,24 @@ suppresses effects: effect-enabled invocations bypass the ordinary output cache
`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 generic scheduler receives an opaque readiness predicate for `If` branch-local nodes and an explicit skip projection
-for the unselected branch. The private `_IfBranchScheduler` still computes legacy branch topology, resolves the gate,
-prunes the unselected input edge, and records compatibility skip metadata. `apply()` validates and persists the
-invocation-emitted effect afterward, replacing the compatibility token by stable identity. Activation effects are
-excluded from data-stream handling. This is a routing seam, not yet the token-authoritative downstream topology
-migration: no author-time activation ports or literal successor IDs are introduced, and other control-flow
-invocations remain on their legacy paths until differential coverage proves each replacement.
+The generic plan stores opaque, frame-local activation-dependency records for `If` branch-local nodes. 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; the activation token is therefore authoritative for generic
+successor readiness. The private `_IfBranchScheduler` still computes legacy branch topology, derives those records,
+resolves the gate, prunes the unselected input edge, and
+records compatibility skip metadata. `apply()` validates and persists the invocation-emitted effect afterward,
+replacing the compatibility token by stable identity. Activation effects are excluded from data-stream handling. This
+is not yet the token-authoritative downstream topology migration: compatibility topology still identifies branch-local
+nodes and skips the unselected branch, no author-time activation ports or literal successor IDs are introduced, and
+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
currently additive. Ordinary static-DAG and legacy-shaped `If` readiness comes from the generic scheduler through a
-compatibility projection; materialization and type-specific control paths remain authoritative for branch topology,
-loops, and workflow-call graphs. A future migration may make tokens authoritative only after compatibility is proven.
+compatibility projection; the activation token is authoritative for generic `If` branch readiness, while materialization
+and type-specific control paths remain authoritative for branch topology, loops, and workflow-call graphs. A future
+migration may make token-built topology and the remaining control-flow paths authoritative only after compatibility is proven.
The generic scheduler is an in-memory graph-state component only. It does not
create, update, retry, cancel, delete, or recover `SessionQueueItem` rows and
@@ -218,15 +226,16 @@ and terminal effects. The generic scheduler selects nodes from required
effects for the current frame; it never receives a literal successor-node ID.
Current implementation is narrower: `IfInvocation` is the only control-flow
invocation using the effect recorder, while `Iterate`, `Collect`, `For`,
-`ForReturn`, and workflow-call invocations remain on compatibility paths. The
-generic scheduler currently consumes opaque plan dependencies, not token-built
-successor topology. The current `If` adapter still owns branch topology and
-compatibility skips, while loop and workflow-call adapters still own
-materialization and durable queue lifecycle. Those owners may be removed only
-after differential tests cover fresh, partially completed, rehydrated, failed,
-canceled, and retried sessions. The frontend boundary remains frozen: this
-refactoring does not modify `invokeai/frontend/...` or existing web/webv2
-interactions.
+`ForReturn`, and workflow-call invocations remain on compatibility paths. For
+`If`, generic readiness consumes opaque plan dependencies and requires both
+matching private `ActivationGate` runtime state and a persisted activation token;
+compatibility topology still derives those dependency records and handles unselected-branch skips.
+This is not token-built successor topology. Loop and workflow-call adapters
+still own materialization and durable queue lifecycle. Those owners may be
+removed only after differential tests cover fresh, partially completed,
+rehydrated, failed, canceled, and retried sessions. The frontend boundary
+remains frozen: this refactoring does not modify `invokeai/frontend/...` or
+existing web/webv2 interactions.
The test-only differential harness at
`tests/app/services/shared/test_execution_engine_differential.py` compares
@@ -287,24 +296,28 @@ Workflow-call note:
be selected as live inputs.
- `_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 skips, indegree transitions, deterministic ordering, claimed work, and completion. The adapter supplies
- the private activation predicate and maps legacy branch skips into the generic projection.
+ intentional skips, indegree transitions, deterministic ordering, claimed work, and completion. The adapter records
+ frame-local activation dependencies, checks private gate state plus persisted activation tokens, and maps legacy
+ branch skips into the generic projection.
- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,
and control-flow continuation scheduling for graphs that still require lowering.
- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.
- `_IfBranchScheduler` Computes legacy `If` topology, defers branch-local work until the condition is known, then
- lowers the decision to a frame-scoped `ActivationGate` and persisted internal activation token, releases the
+ lowers the decision to private frame-scoped `ActivationGate` runtime state and a persisted internal activation token,
+ releases the
selected branch, and maps the unselected branch to generic scheduler skips. Its topology analysis remains a
compatibility adapter; the opaque scheduler has no `If`-specific branch.
- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters.
`GraphExecutionState.model_post_init()` rehydrates private runtime helpers and caches after normal construction or a
-JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached iteration paths, resolved `If` gate
-state from condition results or activation tokens, closed iteration streams from durable Iterate results or completed
-empty-source state, For continuation identity, and ready queues from `execution_graph`, `indegree`, `executed`, and
-`results`. Persisted execution references, tokens, and effects remain part of the serialized state; private helper objects
-do not. Queue snapshots carry an additive execution-state version marker and use the version-aware loader; legacy unmarked snapshots
-are treated as version 0, while unreadable snapshots are quarantined by the queue service.
+JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached iteration paths, private resolved `If`
+gate state from condition results or persisted activation tokens, closed iteration streams from durable Iterate results
+or completed empty-source state, For continuation identity, and ready queues from `execution_graph`, `indegree`,
+`executed`, and `results`. Activation tokens persist; private `ActivationGate` runtime state does not and is
+reconstructed from condition results or persisted activation tokens. Persisted execution references, tokens, and effects
+remain part of serialized state; private helper objects do not. Queue snapshots carry an additive execution-state version
+marker and use version-aware loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are
+quarantined by queue service.
### 4.4 Preparation (`_prepare()`)
@@ -339,11 +352,14 @@ are treated as version 0, while unreadable snapshots are quarantined by the queu
### 4.5 Readiness and class ordering
-- `_enqueue_if_ready(nid)` applies the same readiness predicate to both adapters. The generic scheduler additionally
- tracks claimed (returned-but-not-completed) work so re-registration cannot duplicate a node.
+- `_enqueue_if_ready(nid)` applies generic readiness: `indegree == 0`, not executed or claimed, and, for an `If`
+ branch-local node, both matching private `ActivationGate` runtime state and a persisted activation token are present
+ for its frame. The compatibility adapter uses the same result while deriving dependency records and handling
+ compatibility skips.
- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and legacy-shaped `If` graphs, projecting its
- deterministic class/frame order into the compatibility queues. Loop and saved-workflow control-flow graphs use
- `_active_class` and the legacy class queues. No batch-size or fairness cap is currently implemented.
+ deterministic class/frame order into the compatibility queues. The compatibility `If` topology remains responsible
+ for deriving branch-local records and mapping unselected branches to skips. Loop and saved-workflow control-flow
+ graphs use `_active_class` and the legacy class queues. No batch-size or fairness cap is currently implemented.
#### 4.5.1 Indegree (what it is and how it's used)
@@ -410,7 +426,9 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac
- Source **Graph** remains a DAG and type-consistent.
- `execution_graph` remains a DAG.
-- Nodes are enqueued only when `indegree == 0` and they are not deferred by an unresolved `If`.
+- Nodes are enqueued only when `indegree == 0` and they are not deferred by an unresolved `If`; generic `If`
+ branch-local readiness additionally requires matching private `ActivationGate` runtime state and a persisted
+ activation token.
- `results` and `errors` are keyed by **exec node id**.
- Applied execution references are unique to one prepared node and frame; their output/effect records are JSON-safe.
- Output and `emit` effects produce frame-aware tokens. `close_stream` produces a `stream_end` token. Association fields
diff --git a/invokeai/app/services/shared/execution_engine/__init__.py b/invokeai/app/services/shared/execution_engine/__init__.py
index 6d4619a81a..1a303bba2d 100644
--- a/invokeai/app/services/shared/execution_engine/__init__.py
+++ b/invokeai/app/services/shared/execution_engine/__init__.py
@@ -26,7 +26,12 @@ from invokeai.app.services.shared.execution_engine.primitives import (
StreamEvent,
)
from invokeai.app.services.shared.execution_engine.runtime import ExecutionEngineRuntime
-from invokeai.app.services.shared.execution_engine.scheduler import ExecutionPlan, ExecutionScheduler, PlanNode
+from invokeai.app.services.shared.execution_engine.scheduler import (
+ ActivationDependency,
+ ExecutionPlan,
+ ExecutionScheduler,
+ PlanNode,
+)
__all__ = [
"ChildCompletion",
@@ -51,6 +56,7 @@ __all__ = [
"StreamEnd",
"StreamEvent",
"ExecutionEngineRuntime",
+ "ActivationDependency",
"ExecutionPlan",
"ExecutionScheduler",
"PlanNode",
diff --git a/invokeai/app/services/shared/execution_engine/scheduler.py b/invokeai/app/services/shared/execution_engine/scheduler.py
index 5f98fd6d68..b708232c29 100644
--- a/invokeai/app/services/shared/execution_engine/scheduler.py
+++ b/invokeai/app/services/shared/execution_engine/scheduler.py
@@ -20,14 +20,39 @@ def _frame_key(frame: Frame) -> tuple[tuple[str, str], ...]:
return tuple((type(part).__name__, repr(part)) for part in frame)
+@dataclass(frozen=True, slots=True)
+class ActivationDependency:
+ """Opaque requirement for one branch activation in one frame."""
+
+ owner_id: NodeId
+ branch: str
+ frame: Frame = ()
+
+ def __post_init__(self) -> None:
+ if not isinstance(self.owner_id, str) or not self.owner_id.strip():
+ raise ValueError("activation dependency owner must not be blank")
+ if not isinstance(self.branch, str) or not self.branch.strip():
+ raise ValueError("activation dependency branch must not be blank")
+ if not isinstance(self.frame, tuple):
+ raise TypeError("activation dependency frame must be a tuple")
+ for part in self.frame:
+ if isinstance(part, bool) or not isinstance(part, (int, str)):
+ raise ValueError("activation dependency frame values must be integers or strings")
+ if isinstance(part, int) and part < 0:
+ raise ValueError("activation dependency frame integers must be non-negative")
+ if isinstance(part, str) and not part.strip():
+ raise ValueError("activation dependency frame strings must not be blank")
+
+
@dataclass(frozen=True, slots=True)
class PlanNode:
- """An opaque executable node and its direct prerequisites."""
+ """An opaque executable node, prerequisites, and frame-local requirements."""
node_id: NodeId
class_name: str
frame: Frame
dependencies: tuple[NodeId, ...]
+ activation_dependencies: tuple[ActivationDependency, ...]
order: int
@@ -45,6 +70,7 @@ class ExecutionPlan:
class_name: str,
frame: Frame = (),
dependencies: Iterable[NodeId] = (),
+ activation_dependencies: Iterable[ActivationDependency] = (),
) -> PlanNode:
"""Add one node, rejecting duplicate IDs and unknown prerequisites."""
@@ -60,7 +86,20 @@ class ExecutionPlan:
missing = [dependency for dependency in dependency_ids if dependency not in self.nodes]
if missing:
raise KeyError(f"unknown dependency for {node_id}: {missing[0]}")
- node = PlanNode(node_id, class_name, tuple(frame), dependency_ids, self._next_order)
+ activation_dependency_values = tuple(activation_dependencies)
+ for activation_dependency in activation_dependency_values:
+ if not isinstance(activation_dependency, ActivationDependency):
+ raise TypeError("activation dependencies must be ActivationDependency values")
+ if not activation_dependency.owner_id.strip() or not activation_dependency.branch.strip():
+ raise ValueError("activation dependency owner and branch must not be blank")
+ node = PlanNode(
+ node_id,
+ class_name,
+ tuple(frame),
+ dependency_ids,
+ activation_dependency_values,
+ self._next_order,
+ )
self._next_order += 1
self.nodes[node_id] = node
self._dependents[node_id] = []
@@ -85,6 +124,14 @@ class ExecutionPlan:
"class_name": node.class_name,
"frame": list(node.frame),
"dependencies": list(node.dependencies),
+ "activation_dependencies": [
+ {
+ "owner_id": dependency.owner_id,
+ "branch": dependency.branch,
+ "frame": list(dependency.frame),
+ }
+ for dependency in node.activation_dependencies
+ ],
"order": node.order,
}
for node_id, node in self.nodes.items()
@@ -115,17 +162,37 @@ class ExecutionPlan:
raise ValueError("execution plan node order is invalid")
frame = raw.get("frame", ())
dependencies = raw.get("dependencies", ())
- if not isinstance(frame, (list, tuple)) or not isinstance(dependencies, (list, tuple)):
- raise ValueError("execution plan frame and dependencies must be sequences")
+ activation_dependencies = raw.get("activation_dependencies", ())
+ if (
+ not isinstance(frame, (list, tuple))
+ or not isinstance(dependencies, (list, tuple))
+ or not isinstance(activation_dependencies, (list, tuple))
+ ):
+ raise ValueError("execution plan frame, dependencies, and activation dependencies must be sequences")
if not all(isinstance(dependency, str) for dependency in dependencies):
raise ValueError("execution plan dependencies must be node ids")
- entries.append((order, raw))
+ parsed_activation_dependencies: list[ActivationDependency] = []
+ for activation_dependency in activation_dependencies:
+ if not isinstance(activation_dependency, Mapping):
+ raise ValueError("execution plan activation dependency must be a mapping")
+ owner_id = activation_dependency.get("owner_id")
+ branch = activation_dependency.get("branch")
+ dependency_frame = activation_dependency.get("frame", ())
+ if not isinstance(owner_id, str) or not isinstance(branch, str):
+ raise ValueError("execution plan activation dependency owner and branch must be strings")
+ if not isinstance(dependency_frame, (list, tuple)):
+ raise ValueError("execution plan activation dependency frame must be a sequence")
+ parsed_activation_dependencies.append(
+ ActivationDependency(owner_id=owner_id, branch=branch, frame=tuple(dependency_frame))
+ )
+ entries.append((order, {**raw, "_parsed_activation_dependencies": tuple(parsed_activation_dependencies)}))
for _, raw in sorted(entries, key=lambda entry: entry[0]):
plan.add_node(
raw["node_id"],
raw["class_name"],
tuple(raw.get("frame", ())),
tuple(raw.get("dependencies", ())),
+ activation_dependencies=raw.get("_parsed_activation_dependencies", ()),
)
next_order = snapshot.get("next_order", plan._next_order)
if not isinstance(next_order, int) or next_order < plan._next_order:
@@ -252,7 +319,13 @@ class ExecutionScheduler:
"""Add a plan node without disturbing already-claimed work."""
if node.node_id not in self.plan.nodes:
- self.plan.add_node(node.node_id, node.class_name, node.frame, node.dependencies)
+ self.plan.add_node(
+ node.node_id,
+ node.class_name,
+ node.frame,
+ node.dependencies,
+ node.activation_dependencies,
+ )
self.indegree[node.node_id] = sum(
dependency not in self.executed and dependency not in self.discarded for dependency in node.dependencies
)
@@ -384,4 +457,4 @@ class ExecutionScheduler:
self._arrival_order[node_id] = arrival
-__all__ = ["ExecutionPlan", "ExecutionScheduler", "PlanNode", "ReadyPredicate"]
+__all__ = ["ActivationDependency", "ExecutionPlan", "ExecutionScheduler", "PlanNode", "ReadyPredicate"]
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 793e57e196..ec7965af20 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -75,7 +75,11 @@ from invokeai.app.services.shared.execution_engine.primitives import (
ExecutionFrame as EngineExecutionFrame,
)
from invokeai.app.services.shared.execution_engine.runtime import ExecutionEngineRuntime
-from invokeai.app.services.shared.execution_engine.scheduler import ExecutionPlan, ExecutionScheduler
+from invokeai.app.services.shared.execution_engine.scheduler import (
+ ActivationDependency,
+ ExecutionPlan,
+ ExecutionScheduler,
+)
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.misc import uuid_string
@@ -427,6 +431,32 @@ class _IfBranchScheduler:
self._state._tx_set_mapping(self._state._if_branch_exclusive_sources, if_node_id, branch_sources)
return branch_sources
+ def get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
+ """Describe branch gates for one prepared node without exposing successor IDs."""
+ source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
+ 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
+ branches = self.get_branch_exclusive_sources(source_if_id)
+ matching_fields = tuple(
+ branch_field
+ for branch_field in ("true_input", "false_input")
+ if source_node_id in branches[branch_field]
+ )
+ # A shared ancestor is live regardless of branch selection.
+ 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 is_deferred_by_unresolved_if(self, exec_node_id: str) -> bool:
source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
@@ -477,21 +507,7 @@ class _IfBranchScheduler:
# Compatibility cache for old snapshots and callers. The typed gate is
# the authority for new runtime decisions.
self._state._tx_set_mapping(self._state._resolved_if_exec_branches, exec_node_id, selected_field)
- execution_ref = self._state._expected_execution_ref(exec_node_id)
- activation_token_id = f"{execution_ref.reference_id}:activation:{selected_field}"
- self._state._tx_set_mapping(
- self._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",
- ),
- )
+ self._state._record_compatibility_activation_token(exec_node_id, selected_field)
source_if_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
exclusive_sources = self.get_branch_exclusive_sources(source_if_node_id)
@@ -2201,9 +2217,12 @@ class _GenericGraphSchedulerAdapter:
self._project_ready_nodes()
def _is_node_activation_ready(self, exec_node_id: str) -> bool:
- """Keep legacy branch gates as an opaque readiness predicate for the scheduler."""
+ """Require every frame-local activation dependency to be satisfied."""
- return not self._state._is_deferred_by_unresolved_if(exec_node_id)
+ return all(
+ self._state._is_activation_dependency_satisfied(dependency)
+ for dependency in self._scheduler.plan.nodes[exec_node_id].activation_dependencies
+ )
def _sync_executed_state(self, excluded: Iterable[str] = ()) -> None:
excluded_ids = set(excluded)
@@ -2227,6 +2246,7 @@ class _GenericGraphSchedulerAdapter:
if node is None:
raise KeyError(f"exec node {exec_node_id} missing from execution_graph")
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:
if dependency not in self._scheduler.plan.nodes:
self.register_node(dependency)
@@ -2236,6 +2256,7 @@ class _GenericGraphSchedulerAdapter:
type(node).__name__,
self._state._get_iteration_path(exec_node_id),
dependencies,
+ activation_dependencies,
)
)
self._state._tx_set_mapping(self._state.indegree, exec_node_id, self._scheduler.indegree[exec_node_id])
@@ -4632,6 +4653,62 @@ class GraphExecutionState(BaseModel):
branches=("true_input", "false_input"),
)
+ 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",
+ ),
+ )
+
+ 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
+
def _resolve_activation_gate(self, exec_node_id: str, branch: str) -> bool:
runtime = self._generic_runtime()
gate = self._activation_gate(exec_node_id)
@@ -5528,6 +5605,9 @@ class GraphExecutionState(BaseModel):
def _is_deferred_by_unresolved_if(self, exec_node_id: str) -> bool:
return self._if_scheduler().is_deferred_by_unresolved_if(exec_node_id)
+ def _get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
+ return self._if_scheduler().get_activation_dependencies(exec_node_id)
+
def _remove_from_ready_queues(self, exec_node_id: str) -> None:
self._scheduler().remove_from_ready_queues(exec_node_id)
@@ -5646,6 +5726,7 @@ class GraphExecutionState(BaseModel):
selected_field = "true_input" if node.condition else "false_input"
self._resolve_activation_gate(exec_node_id, selected_field)
self._resolved_if_exec_branches[exec_node_id] = selected_field
+ self._record_compatibility_activation_token(exec_node_id, selected_field)
def _rehydrate_execution_refs(self) -> None:
for exec_node_id in self.prepared_source_mapping:
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
index 2dc6aa79f2..a7a1ba1d47 100644
--- a/tests/app/services/shared/test_execution_engine_scheduler.py
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -8,6 +8,7 @@ from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.math import AddInvocation, MultiplyInvocation
from invokeai.app.invocations.primitives import BooleanInvocation
from invokeai.app.services.shared.execution_engine.scheduler import (
+ ActivationDependency,
ExecutionPlan,
ExecutionScheduler,
)
@@ -74,6 +75,167 @@ def test_generic_scheduler_discards_node_with_unmet_prerequisites() -> None:
assert scheduler.pop_next() == "dependent"
+def test_generic_plan_round_trips_frame_local_activation_dependencies() -> None:
+ plan = ExecutionPlan()
+ plan.add_node("if", "If")
+ dependency = ActivationDependency(owner_id="if", branch="true_input", frame=(0, "inner"))
+ plan.add_node("branch", "Work", dependencies=("if",), activation_dependencies=(dependency,))
+
+ restored = ExecutionPlan.from_snapshot(plan.snapshot())
+
+ assert restored.nodes["branch"].activation_dependencies == (dependency,)
+
+
+def test_generic_plan_rejects_malformed_activation_dependency_snapshot() -> None:
+ plan = ExecutionPlan()
+ plan.add_node("if", "If")
+ plan.add_node(
+ "branch",
+ "Work",
+ dependencies=("if",),
+ activation_dependencies=(ActivationDependency(owner_id="if", branch="true_input"),),
+ )
+ snapshot = plan.snapshot()
+ snapshot["nodes"]["branch"]["activation_dependencies"][0]["frame"] = "not-a-frame"
+
+ with pytest.raises(ValueError, match="activation dependency frame must be a sequence"):
+ ExecutionPlan.from_snapshot(snapshot)
+
+
+def test_graph_state_generic_if_readiness_uses_activation_dependency_records(monkeypatch: pytest.MonkeyPatch) -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=True))
+ graph.add_node(AddInvocation(id="true_value", a=2, b=2))
+ graph.add_node(AddInvocation(id="false_value", a=3, b=3))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="condition", field="value"),
+ destination=EdgeConnection(node_id="if", field="condition"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="true_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="false_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="false_input"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ condition = state.next()
+ assert condition is not None
+ state.complete(condition.id, condition.invoke(Mock()))
+
+ true_exec_id = next(
+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "true_value"
+ )
+ plan_node = state._generic_graph_scheduler._scheduler.plan.nodes[true_exec_id]
+ assert plan_node.activation_dependencies == (ActivationDependency(owner_id="if", branch="true_input", frame=()),)
+ false_exec_id = next(
+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "false_value"
+ )
+ assert state._generic_graph_scheduler._scheduler.plan.nodes[false_exec_id].activation_dependencies == (
+ ActivationDependency(owner_id="if", branch="false_input", frame=()),
+ )
+
+ if_exec_id = next(
+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "if"
+ )
+ assert state._activation_gate(if_exec_id).selected_branch == "true_input"
+ assert any(
+ token.owner_node_id == if_exec_id
+ and token.port == "true_input"
+ and token.value == "true_input"
+ and token.token_kind == "activation"
+ for token in state.execution_tokens.values()
+ )
+ activation_dependency = plan_node.activation_dependencies[0]
+ assert state._is_activation_dependency_satisfied(activation_dependency)
+ activation_token_id, activation_token = next(
+ (token_id, token)
+ for token_id, token in state.execution_tokens.items()
+ if token.owner_node_id == if_exec_id and token.token_kind == "activation"
+ )
+ state.execution_tokens.pop(activation_token_id)
+ assert not state._is_activation_dependency_satisfied(activation_dependency)
+ assert not state._is_activation_dependency_satisfied(
+ ActivationDependency(owner_id="if", branch="true_input", frame=(1,))
+ )
+
+ def fail_if_topology_is_consulted(*_: object, **__: object) -> bool:
+ raise AssertionError("generic readiness consulted the If topology helper")
+
+ monkeypatch.setattr(GraphExecutionState, "_is_deferred_by_unresolved_if", fail_if_topology_is_consulted)
+ state._generic_graph_scheduler._scheduler.rebuild_ready()
+ assert state.next() is None
+
+ stale_token = activation_token.model_copy(update={"reference_id": "stale-reference"})
+ state.execution_tokens[activation_token_id] = stale_token
+ assert not state._is_activation_dependency_satisfied(activation_dependency)
+ state.execution_tokens[activation_token_id] = activation_token
+ stale_token_id = activation_token.model_copy(update={"token_id": "stale-token-id"})
+ state.execution_tokens[activation_token_id] = stale_token_id
+ assert not state._is_activation_dependency_satisfied(activation_dependency)
+ state.execution_tokens[activation_token_id] = activation_token
+ state._generic_graph_scheduler._scheduler.rebuild_ready()
+ next_node = state.next()
+ assert next_node is not None
+ assert state.prepared_source_mapping[next_node.id] == "true_value"
+
+
+def test_graph_state_rehydrates_legacy_if_without_activation_token() -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=True))
+ graph.add_node(AddInvocation(id="true_value", a=2, b=2))
+ graph.add_node(AddInvocation(id="false_value", a=3, b=3))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="condition", field="value"),
+ destination=EdgeConnection(node_id="if", field="condition"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="true_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="false_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="false_input"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ condition = state.next()
+ assert condition is not None
+ state.complete(condition.id, condition.invoke(Mock()))
+ snapshot = state.model_dump(mode="python")
+ snapshot["execution_tokens"] = {}
+
+ restored = GraphExecutionState.model_validate(snapshot, strict=False)
+
+ restored_if_id = next(
+ execution_id for execution_id, source_id in restored.prepared_source_mapping.items() if source_id == "if"
+ )
+ assert restored._activation_gate(restored_if_id).selected_branch == "true_input"
+ assert any(
+ token.owner_node_id == restored_if_id and token.token_kind == "activation" and token.port == "true_input"
+ for token in restored.execution_tokens.values()
+ )
+ next_node = restored.next()
+ assert next_node is not None
+ assert restored.prepared_source_mapping[next_node.id] == "true_value"
+
+
def test_generic_scheduler_discarded_claim_is_not_requeued() -> None:
plan = ExecutionPlan()
plan.add_node("source", "Source")