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): share If activation routing

JPPhoto9998f9354da8
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index fe790994a9..189d5446f5 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -132,25 +132,24 @@ the compatibility continuation/materialization owner for unsupported shapes.
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
those dependencies through the opaque `ExecutionPlan` for readiness and rejects unselected prepared nodes through
-generic scheduler discard. It does not consult `_IfBranchScheduler` topology, call
-`_IfBranchScheduler._prune_unselected_if_inputs` or `_IfBranchScheduler.mark_exec_node_skipped`, or delete execution
-edges. Forced `_ExecutionScheduler` still retains
-`_IfBranchScheduler` legacy topology, input-edge pruning, and skip behavior for compatibility snapshots. `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 legacy topology. 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.
+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
+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.
The engine still owns runtime node materialization and queue readiness for loop-containing graphs that require empty or
input-driven `For`, nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs,
direct `Iterate`/`Collect`-only graphs, and supported fresh static flat `For` graphs now use the generic opaque
-plan/scheduler through a compatibility projection; a fresh
-generic `If` uses the compiler/adapter seam described above. This is intentional:
+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
lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-time
graph JSON.
This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing
-frontend/backend external interface remains frozen. The ownership seam does not remove all legacy topology yet.
+frontend/backend external interface remains frozen. The ownership seam does not remove all compiler-derived branch
+analysis or skipped-state projection yet.
The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and the
direct linkage edge. The current invocation templates provide output-scope metadata when a workflow is loaded. The
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 1da630621c..6d79ef24bc 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -11,10 +11,10 @@ instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If
and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. For a fresh generic `If`, the dedicated
`_IfActivationCompiler` produces opaque, frame-local activation dependencies; `_GenericGraphSchedulerAdapter` registers
and consumes those dependencies through the opaque plan, then rejects unselected prepared nodes through generic scheduler
-discard. It does not consult `_IfBranchScheduler` topology or call its prune/skip methods, and it does not delete
-execution edges. The forced compatibility `_ExecutionScheduler` path retains legacy `If` topology lowering, input-edge
-pruning, and skip behavior for compatibility snapshots. This is an ownership seam, not final removal of all legacy
-topology.
+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
+metadata remains a compatibility projection for runtime snapshots and completion accounting. This removes the
+branch-scheduler owner but does not yet remove all compiler-derived branch analysis or skipped-state projection.
Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow also use
the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and generic
completion mirrors each Iterate result into that ledger before releasing `Collect`; materialization still owns copy
@@ -160,10 +160,8 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
- `graph: Graph` - source graph for the run; treated as stable during normal execution.
- `execution_graph: Graph` - materialized runtime nodes/edges. This is mutable runtime state, not an immutable audit
- log. Forced compatibility `_ExecutionScheduler` lazy `If` pruning may remove unselected input edges during execution,
- so persisted failed/completed session snapshots can contain a structurally pruned execution graph. Generic
- legacy-shaped `If` scheduling retires unselected prepared nodes without deleting execution edges. Retry paths rebuild
- from `graph`, not from a previously persisted `execution_graph`.
+ log. `If` retirement is append-only: rejected prepared nodes are discarded through scheduler state without deleting
+ input edges. Retry paths rebuild from `graph`, not from a previously persisted `execution_graph`.
- `executed: set[str]`, `executed_history: list[str]`.
- `results: dict[str, AnyInvocationOutput]`, `errors: dict[str, str]`.
- `prepared_source_mapping: dict[str, str]` - exec id -> source id.
@@ -226,11 +224,10 @@ 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
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 generic scheduler discard. This
-path does not consult `_IfBranchScheduler` topology, call `_IfBranchScheduler._prune_unselected_if_inputs` or
-`_IfBranchScheduler.mark_exec_node_skipped`, or delete execution edges. The forced compatibility `_ExecutionScheduler`
-path still uses `_IfBranchScheduler` for legacy branch topology, input-edge pruning, and skip behavior. This is an
-ownership seam, not final removal of all legacy topology. `apply()`
+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.
+The compatibility path still projects discarded prepared nodes into legacy skipped metadata for rehydration and
+completion accounting. This is an ownership seam, not final removal of all compiler-derived branch analysis. `apply()`
validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.
Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing
control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration
@@ -307,7 +304,8 @@ generic adapter. For
`If`, generic readiness consumes opaque frame-local plan dependencies and requires
both matching private `ActivationGate` runtime state and a persisted activation token;
generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility
-`_ExecutionScheduler` path retains `_IfBranchScheduler` topology, edge-prune, and skip behavior.
+`_ExecutionScheduler` path uses the same append-only discard projection; legacy skipped metadata remains until the
+no-skipped-state migration gate is complete.
This is not token-built successor topology. Loop and workflow-call adapters
still own materialization for unsupported shapes and durable queue lifecycle.
Those owners may be removed only after differential tests cover fresh, partially completed,
@@ -386,16 +384,11 @@ Workflow-call note:
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
- unselected prepared nodes through generic scheduler discard. Fresh generic `If` scheduling does not call
- `_IfBranchScheduler` topology, prune, or skip methods and does not delete execution edges.
+ 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,
- control-flow continuation scheduling, and forced-compatibility `If` topology for graphs that still require lowering.
+ control-flow continuation scheduling, and the shared opaque activation-dependency projection for compatibility graphs.
- `_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 private frame-scoped `ActivationGate` runtime state and a persisted internal activation token,
- releases the selected branch, prunes unselected input edges, and marks unselected branch-local nodes skipped. Used
- only by forced compatibility `_ExecutionScheduler`; it remains available for compatibility snapshots. Its retained
- topology/pruning/skip ownership is an intentional seam, not a final removal of legacy topology.
- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters. The
canonical stream for a prepared `IterateInvocation` is keyed by the source iterator and its parent iteration path;
its item/close effects and legacy output mirroring update the same idempotent buffer. Direct `CollectInvocation.item`
@@ -451,11 +444,11 @@ legacy unmarked snapshots are treated as version 0, while unreadable snapshots a
- `_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 generic adapter derives opaque dependencies and retires rejected nodes through generic scheduler
- discard. For direct `Collect` nodes, the adapter also requires available Iterate streams to be closed. Forced
- compatibility uses `_IfBranchScheduler` topology and skip handling.
+ discard. For direct `Collect` nodes, the adapter also requires available Iterate streams to be closed. Compatibility
+ uses the same opaque activation dependencies and scheduler discard projection; legacy skipped metadata remains for
+ snapshot compatibility.
- `_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. Forced compatibility `If` topology remains responsible
- for branch-local lowering, input-edge pruning, and skips. Loop and saved-workflow control-flow graphs use `_active_class`
+ 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.
#### 4.5.1 Indegree (what it is and how it's used)
@@ -491,13 +484,13 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.
- The `condition` input must resolve first.
- Nodes that are exclusive to the true or false branch can remain deferred even when their indegree is zero.
-- In generic legacy-shaped `If` scheduling, once the prepared `If` node resolves its condition, the selected branch is
- released, unselected prepared nodes are retired through generic scheduler discard, and branch-exclusive ancestors of
- the unselected branch are never executed. This path does not call `_IfBranchScheduler._prune_unselected_if_inputs`,
- `_IfBranchScheduler.mark_exec_node_skipped`, or delete execution edges.
-- In forced compatibility `_ExecutionScheduler` scheduling, `_IfBranchScheduler` retains legacy behavior: selected work
- is released, unselected work is marked skipped, unselected input edges on the prepared `If` exec node are pruned, and
- branch-exclusive ancestors of the unselected branch are never executed.
+- 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
+ 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
+ compatibility; removing that projection remains a later gate.
- The SQLite queue/processor path has evidence for cancellation before and after `If` resolution and retry from each
boundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry starts
a fresh state and must emit a fresh matching activation token before selected-only completion.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index fa6a3900cb..3523afb03c 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -379,6 +379,9 @@ class _IfActivationCompiler:
"""Compile opaque branch requirements for one prepared execution 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 ()
+
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():
@@ -417,126 +420,6 @@ def _get_if_activation_dependencies(
return state._if_activation_compiler().get_activation_dependencies(exec_node_id)
-class _IfBranchScheduler:
- """Applies lazy `If` semantics by deferring, releasing, and skipping branch-local exec nodes."""
-
- def __init__(self, state: "GraphExecutionState") -> None:
- self._state = state
-
- def _get_matching_prepared_if_ids(self, if_node_id: str, iteration_path: tuple[int, ...]) -> list[str]:
- prepared_if_ids = self._state._prepared_registry().get_prepared_ids(if_node_id)
- return [pid for pid in prepared_if_ids if self._state._get_iteration_path(pid) == iteration_path]
-
- def _has_unresolved_matching_if(self, if_node_id: str, iteration_path: tuple[int, ...]) -> bool:
- matching_prepared_if_ids = self._get_matching_prepared_if_ids(if_node_id, iteration_path)
- if not matching_prepared_if_ids:
- return True
- return not all(self._state._activation_gate(pid).resolved for pid in matching_prepared_if_ids)
-
- def _apply_condition_inputs(self, exec_node_id: str, node: IfInvocation) -> bool:
- return self._state._apply_if_condition_inputs(exec_node_id, node)
-
- def _get_selected_branch_fields(self, node: IfInvocation) -> tuple[str, str]:
- selected_field = "true_input" if node.condition else "false_input"
- unselected_field = "false_input" if node.condition else "true_input"
- return selected_field, unselected_field
-
- def _prune_unselected_if_inputs(self, exec_node_id: str, unselected_field: str) -> None:
- for edge in self._state.execution_graph._get_input_edges(exec_node_id, unselected_field):
- if edge.source.node_id not in self._state.executed:
- if self._state.indegree[exec_node_id] == 0:
- raise RuntimeError(f"indegree underflow for {exec_node_id} when pruning {unselected_field}")
- self._state._tx_set_mapping(self._state.indegree, exec_node_id, self._state.indegree[exec_node_id] - 1)
- self._state._tx_delete_execution_edge(edge)
- self._state._invalidate_execution_graph_flat()
-
- def _apply_branch_resolution(
- self,
- exec_node_id: str,
- iteration_path: tuple[int, ...],
- exclusive_sources: dict[str, set[str]],
- selected_field: str,
- unselected_field: str,
- ) -> None:
- # This iterates over the stable prepared-source mapping while mutating per-exec runtime state such as ready
- # queues, execution state, and prepared metadata. Branch resolution never adds or removes prepared exec nodes.
- for prepared_id, prepared_source in self._state.prepared_source_mapping.items():
- if prepared_id in self._state.executed:
- continue
- if self._state._get_iteration_path(prepared_id) != iteration_path:
- continue
- if prepared_source in exclusive_sources[selected_field]:
- self._state._enqueue_if_ready(prepared_id)
- elif prepared_source in exclusive_sources[unselected_field]:
- self.mark_exec_node_skipped(prepared_id)
-
- def get_branch_exclusive_sources(self, if_node_id: str) -> dict[str, set[str]]:
- return _get_if_branch_exclusive_sources(self._state, if_node_id)
-
- def get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
- return _get_if_activation_dependencies(self._state, exec_node_id)
-
- 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)
-
- 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)
- if source_node_id not in branches["true_input"] and source_node_id not in branches["false_input"]:
- continue
-
- iteration_path = self._state._get_iteration_path(exec_node_id)
- if self._has_unresolved_matching_if(source_if_id, iteration_path):
- return True
- return False
-
- def mark_exec_node_skipped(self, exec_node_id: str) -> None:
- state = self._state._get_prepared_exec_metadata(exec_node_id).state
- if state in ("executed", "skipped"):
- return
-
- self._state._remove_from_ready_queues(exec_node_id)
- self._state._set_prepared_exec_state(exec_node_id, "skipped")
- self._state._tx_add_set(self._state.executed, exec_node_id)
- scheduler = self._state._execution_scheduler
- if scheduler is not None:
- scheduler.mark_skipped(exec_node_id)
-
- registry = self._state._prepared_registry()
- source_node_id = registry.get_source_node_id(exec_node_id)
- prepared_nodes = registry.get_prepared_ids(source_node_id)
- if all(n in self._state.executed for n in prepared_nodes):
- if source_node_id not in self._state.executed:
- self._state._mark_source_executed(source_node_id)
-
- def try_resolve_if_node(self, exec_node_id: str) -> None:
- if exec_node_id in self._state._resolved_if_exec_branches:
- return
- node = self._state.execution_graph.get_node(exec_node_id)
- if not isinstance(node, IfInvocation):
- return
-
- if not self._apply_condition_inputs(exec_node_id, node):
- return
-
- selected_field, unselected_field = self._get_selected_branch_fields(node)
- self._state._resolve_activation_gate(exec_node_id, selected_field)
- # 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)
- 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)
-
- iteration_path = self._state._get_iteration_path(exec_node_id)
- self._prune_unselected_if_inputs(exec_node_id, unselected_field)
- self._apply_branch_resolution(exec_node_id, iteration_path, exclusive_sources, selected_field, unselected_field)
- self._state._enqueue_if_ready(exec_node_id)
-
-
class _ExecutionMaterializer:
"""Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
@@ -1853,6 +1736,38 @@ class _ExecutionScheduler:
node = self._state.execution_graph.nodes[exec_node_id]
return isinstance(node, CollectInvocation) and not self._state._collect_streams_ready(exec_node_id)
+ def _discard_rejected_activation_node(self, exec_node_id: str) -> bool:
+ if exec_node_id not in self._state.indegree:
+ return False
+ metadata = self._state._get_prepared_exec_metadata(exec_node_id)
+ if metadata.state in ("executed", "skipped"):
+ return False
+ if not self._state._has_rejected_activation_dependency(exec_node_id):
+ return False
+
+ self.remove_from_ready_queues(exec_node_id)
+ self._state._set_prepared_exec_state(exec_node_id, "skipped")
+ self._state._tx_add_set(self._state.executed, exec_node_id)
+
+ registry = self._state._prepared_registry()
+ source_node_id = registry.get_source_node_id(exec_node_id)
+ prepared_nodes = registry.get_prepared_ids(source_node_id)
+ if all(node_id in self._state.executed for node_id in prepared_nodes):
+ if source_node_id not in self._state.executed:
+ self._state._mark_source_executed(source_node_id)
+ self.mark_skipped(exec_node_id)
+ return True
+
+ def _discard_rejected_activation_nodes(self) -> None:
+ for exec_node_id in tuple(nx.topological_sort(self._state._get_execution_graph_flat())):
+ self._discard_rejected_activation_node(exec_node_id)
+
+ def _enqueue_activation_ready_nodes(self) -> None:
+ for exec_node_id in tuple(self._state.prepared_source_mapping):
+ if exec_node_id not in self._state.indegree or exec_node_id in self._state.executed:
+ continue
+ self.enqueue_if_ready(exec_node_id)
+
def _get_ready_queue(self, exec_node_id: str) -> Deque[str]:
node_obj = self._state.execution_graph.nodes[exec_node_id]
return self.queue_for(self._state._type_key(node_obj))
@@ -2000,6 +1915,8 @@ class _ExecutionScheduler:
def enqueue_if_ready(self, exec_node_id: str) -> None:
"""Push exec_node_id to its class queue if unmet inputs == 0."""
self._validate_exec_node_ready_state(exec_node_id)
+ if self._discard_rejected_activation_node(exec_node_id):
+ return
if self._should_skip_ready_enqueue(exec_node_id):
return
queue = self._get_ready_queue(exec_node_id)
@@ -4378,7 +4295,6 @@ class GraphExecutionState(BaseModel):
_resolved_if_exec_branches: dict[str, str] = PrivateAttr(default_factory=dict)
_prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
- _if_branch_scheduler: Optional[_IfBranchScheduler] = PrivateAttr(default=None)
_if_activation_compiler_instance: Optional[_IfActivationCompiler] = PrivateAttr(default=None)
_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
_execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
@@ -4490,7 +4406,6 @@ class GraphExecutionState(BaseModel):
def _reset_apply_derived_caches(self) -> None:
self._prepared_exec_registry = None
- self._if_branch_scheduler = None
self._execution_materializer = None
self._execution_scheduler = None
self._generic_graph_scheduler = None
@@ -4522,11 +4437,6 @@ class GraphExecutionState(BaseModel):
)
return self._prepared_exec_registry
- def _if_scheduler(self) -> _IfBranchScheduler:
- if self._if_branch_scheduler is None:
- self._if_branch_scheduler = _IfBranchScheduler(self)
- return self._if_branch_scheduler
-
def _if_activation_compiler(self) -> _IfActivationCompiler:
if self._if_activation_compiler_instance is None:
self._if_activation_compiler_instance = _IfActivationCompiler(self)
@@ -6133,7 +6043,16 @@ class GraphExecutionState(BaseModel):
return self._scheduler().queue_for(cls_name)
def _is_deferred_by_unresolved_if(self, exec_node_id: str) -> bool:
- return self._if_scheduler().is_deferred_by_unresolved_if(exec_node_id)
+ 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)
+
+ 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)
+ )
def _get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
return self._if_activation_compiler().get_activation_dependencies(exec_node_id)
@@ -6145,8 +6064,22 @@ class GraphExecutionState(BaseModel):
scheduler = self._execution_scheduler
if isinstance(scheduler, _GenericGraphSchedulerAdapter):
scheduler.resolve_if_node(exec_node_id)
- else:
- self._if_scheduler().try_resolve_if_node(exec_node_id)
+ return
+
+ if exec_node_id in self._resolved_if_exec_branches:
+ return
+ node = self.execution_graph.get_node(exec_node_id)
+ if not isinstance(node, IfInvocation) or not self._apply_if_condition_inputs(exec_node_id, node):
+ return
+
+ selected_field = "true_input" if node.condition else "false_input"
+ self._resolve_activation_gate(exec_node_id, selected_field)
+ self._tx_set_mapping(self._resolved_if_exec_branches, exec_node_id, selected_field)
+ self._record_compatibility_activation_token(exec_node_id, selected_field)
+ assert isinstance(scheduler, _ExecutionScheduler)
+ scheduler._discard_rejected_activation_nodes()
+ scheduler._enqueue_activation_ready_nodes()
+ self._enqueue_if_ready(exec_node_id)
def set_ready_order(self, order: Iterable[Type[BaseInvocation] | str]) -> None:
names: list[str] = []
@@ -6179,7 +6112,6 @@ class GraphExecutionState(BaseModel):
self._resolved_if_exec_branches = {}
self._prepared_exec_metadata = {}
self._prepared_exec_registry = None
- self._if_branch_scheduler = None
self._if_activation_compiler_instance = None
self._execution_materializer = None
self._execution_scheduler = None
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index b1b1cc04dd..28f8888d6c 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -26,7 +26,6 @@ from invokeai.app.services.shared.graph import (
GraphExecutionState,
_ExecutionScheduler,
_GenericGraphSchedulerAdapter,
- _IfBranchScheduler,
)
from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context
from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocation
@@ -548,33 +547,9 @@ def _expected_edge_projection(
outer_condition: bool,
inner_condition: bool,
) -> tuple[tuple[str, str, str, str, str], ...]:
- """Project the source graph using the explicit compatibility If lowering rules."""
- source_edges = _source_edge_projection(graph)
- if not force_compatibility_scheduler:
- return source_edges
-
- # The compatibility scheduler prunes only the inactive input edge at each If that it resolves. If the outer
- # branch is false, the inner If is never resolved, so its two branch edges remain in the compatibility graph.
- pruned_edges = {
- (
- "outer_false" if outer_condition else "inner_if",
- "value",
- "outer_if",
- "false_input" if outer_condition else "true_input",
- "default",
- ),
- }
- if outer_condition:
- pruned_edges.add(
- (
- "inner_false" if inner_condition else "inner_true",
- "value",
- "inner_if",
- "false_input" if inner_condition else "true_input",
- "default",
- )
- )
- return tuple(edge for edge in source_edges if edge not in pruned_edges)
+ """Project the append-only execution graph for both scheduler adapters."""
+ del force_compatibility_scheduler, outer_condition, inner_condition
+ return _source_edge_projection(graph)
def _normalized_indegree(state: GraphExecutionState) -> tuple[tuple[str, tuple[int, ...]], ...]:
@@ -1411,24 +1386,12 @@ def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(
state = GraphExecutionState(graph=graph)
deleted_edges: list[Edge] = []
- def fail_prune(*_: object, **__: object) -> None:
- raise AssertionError("generic If execution called _prune_unselected_if_inputs")
-
- def fail_skip(*_: object, **__: object) -> None:
- raise AssertionError("generic If execution called mark_exec_node_skipped")
-
def fail_topology(*_: object, **__: object) -> dict[str, set[str]]:
raise AssertionError("generic If execution consulted legacy branch topology")
- def fail_legacy_scheduler(*_: object, **__: object) -> None:
- raise AssertionError("generic If execution instantiated the legacy branch scheduler")
-
def record_deleted_edge(self: GraphExecutionState, edge: Edge) -> None:
deleted_edges.append(edge)
- monkeypatch.setattr(_IfBranchScheduler, "_prune_unselected_if_inputs", fail_prune)
- monkeypatch.setattr(_IfBranchScheduler, "mark_exec_node_skipped", fail_skip)
- monkeypatch.setattr(_IfBranchScheduler, "__init__", fail_legacy_scheduler)
monkeypatch.setattr(graph_module, "_get_if_branch_exclusive_sources", fail_topology)
monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)
@@ -1534,8 +1497,6 @@ def test_fresh_generic_nested_if_preserves_state_without_legacy_branch_projectio
monkeypatch.setattr(graph_module, "_get_if_branch_exclusive_sources", fail_legacy_path)
monkeypatch.setattr(_GenericGraphSchedulerAdapter, "_retire_unselected_node", record_generic_discard)
- monkeypatch.setattr(_IfBranchScheduler, "_prune_unselected_if_inputs", fail_legacy_path)
- monkeypatch.setattr(_IfBranchScheduler, "mark_exec_node_skipped", fail_legacy_path)
monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", fail_legacy_path)
trace, state = _run_graph(GraphExecutionState(graph=graph))
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
index f24f4c6ab2..c100127825 100644
--- a/tests/app/services/shared/test_execution_engine_scheduler.py
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -615,6 +615,54 @@ def test_graph_state_if_uses_generic_activation_routing() -> None:
}
[email protected]("condition", [False, True])
+def test_graph_state_compatibility_if_uses_opaque_activation_routing(
+ condition: bool, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=condition))
+ 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)
+ state._execution_scheduler = _ExecutionScheduler(state)
+ deleted_edges: list[Edge] = []
+
+ def record_deleted_edge(self: GraphExecutionState, edge: Edge) -> None:
+ deleted_edges.append(edge)
+
+ monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)
+
+ trace: list[str] = []
+ while (node := state.next()) is not None:
+ trace.append(state.prepared_source_mapping[node.id])
+ state.complete(node.id, node.invoke(Mock()))
+
+ selected_value = "true_value" if condition else "false_value"
+ assert trace == ["condition", selected_value, "if"]
+ assert state.is_complete()
+ assert deleted_edges == []
+
+
def test_graph_state_if_generic_and_legacy_paths_have_matching_completion() -> None:
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=False))
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 7a6c750a80..694cac08d5 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -66,7 +66,6 @@ from invokeai.app.services.shared.graph import (
# This import must happen before other invoke imports or test in other files(!!) break
from tests.test_nodes import (
AnyTypeTestInvocation,
- AnyTypeTestInvocationOutput,
PolymorphicStringTestInvocation,
PromptCollectionTestInvocation,
PromptTestInvocation,
@@ -3587,7 +3586,7 @@ def test_invocation_event_service_uses_compact_control_node_representation():
assert iterator.collection == [1, 2, 3]
-def test_if_scheduler_does_not_resolve_iteration_path_when_graph_has_no_if(monkeypatch: pytest.MonkeyPatch):
+def test_activation_dependencies_do_not_resolve_iteration_path_when_graph_has_no_if(monkeypatch: pytest.MonkeyPatch):
graph = Graph()
graph.add_node(PromptTestInvocation(id="source", prompt="test"))
state = GraphExecutionState(graph=graph)
@@ -3600,7 +3599,7 @@ def test_if_scheduler_does_not_resolve_iteration_path_when_graph_has_no_if(monke
monkeypatch.setattr(GraphExecutionState, "_get_iteration_path", fail_get_iteration_path)
- assert state._if_scheduler().is_deferred_by_unresolved_if(prepared_node.id) is False
+ assert state._is_deferred_by_unresolved_if(prepared_node.id) is False
def test_materializer_caches_iteration_paths_for_single_parent_chain(monkeypatch: pytest.MonkeyPatch):
@@ -5477,38 +5476,6 @@ def test_get_iteration_node_does_not_reuse_wrong_iterator_when_only_other_iterat
assert active_value_exec_id != skipped_value_exec_id
-def test_mark_exec_node_skipped_does_not_hide_already_executed_results():
- graph = Graph()
- graph.add_node(AnyTypeTestInvocation(id="value", value="value"))
-
- g = GraphExecutionState(graph=graph)
-
- exec_id = g._create_execution_node("value", [])[0]
- g.results[exec_id] = AnyTypeTestInvocationOutput(value="value")
- g.executed.add(exec_id)
- g._set_prepared_exec_state(exec_id, "executed")
-
- g._if_scheduler().mark_exec_node_skipped(exec_id)
-
- assert g._get_prepared_exec_metadata(exec_id).state == "executed"
- assert g.results[exec_id].value == "value"
-
-
-def test_mark_exec_node_skipped_is_idempotent_for_skipped_state():
- graph = Graph()
- graph.add_node(AnyTypeTestInvocation(id="value", value="value"))
-
- g = GraphExecutionState(graph=graph)
-
- exec_id = g._create_execution_node("value", [])[0]
-
- g._if_scheduler().mark_exec_node_skipped(exec_id)
- g._if_scheduler().mark_exec_node_skipped(exec_id)
-
- assert g._get_prepared_exec_metadata(exec_id).state == "skipped"
- assert g.executed_history.count("value") == 1
-
-
def test_are_connection_types_compatible_accepts_subclass_to_base():
"""A subclass output should be connectable to a base-class input.