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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(execution): retire generic If branches append-only
JPPhoto97724cb1fcb6
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 0ee21c8e14..1281635858 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -9,9 +9,9 @@ iterator patterns, tracks readiness via indegree (the number of incoming edges texecutes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution graphinstead 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 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.+frame-local `If` activation dependencies, checks their private gate state plus persisted activation tokens, and retires+unselected prepared nodes through generic scheduler discard. The forced compatibility `_ExecutionScheduler` path retains+legacy `If` topology lowering, input-edge pruning, and skip behavior.The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, andauthorized child-dependency records are stored in`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while@@ -138,9 +138,10 @@ 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. Lazy `If` pruning may remove unselected input edges during execution, so persisted failed/completed session- snapshots can contain a structurally pruned execution graph. Retry paths rebuild from `graph`, not from a previously- persisted `execution_graph`.+ 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`.- `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.@@ -198,13 +199,14 @@ port against the producing invocation's declared activation fields and persistsThe generic plan stores opaque, frame-local activation-dependency records for `If` branch-local nodes. Its readinesscallback accepts a node only when the required private `ActivationGate` runtime state is resolved and a matchingpersisted 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.+successor readiness. Generic legacy-shaped `If` resolution retires unselected prepared nodes through generic scheduler+discard. It does not call `_IfBranchScheduler._prune_unselected_if_inputs`,+`_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. `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: 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@@ -227,9 +229,10 @@ effects for the current frame; it never receives a literal successor-node ID.Current implementation is narrower: `IfInvocation` is the only control-flowinvocation using the effect recorder, while `Iterate`, `Collect`, `For`,`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.+`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.This is not token-built successor topology. Loop and workflow-call adaptersstill own materialization and durable queue lifecycle. Those owners may beremoved only after differential tests cover fresh, partially completed,@@ -296,17 +299,18 @@ Workflow-call note:be selected as live inputs.- `_GenericGraphSchedulerAdapter` Projects the generic `ExecutionPlan`/`ExecutionScheduler` into the existing statefields 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 records- frame-local activation dependencies, checks private gate state plus persisted activation tokens, and maps legacy- branch skips into the generic projection.+ intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter records+ frame-local activation dependencies, checks private gate state plus persisted activation tokens, and retires+ unselected prepared nodes through generic scheduler discard.- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,- and control-flow continuation scheduling for graphs that still require lowering.+ control-flow continuation scheduling, and forced-compatibility `If` topology 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, thenlowers 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.+ releases the selected branch, prunes unselected input edges, and marks unselected branch-local nodes skipped. Used+ only by forced compatibility `_ExecutionScheduler`; generic legacy-shaped `If` scheduling compiles opaque dependencies+ and retires unselected prepared nodes through generic scheduler discard. 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@@ -354,12 +358,12 @@ quarantined by queue service.- `_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.+ for its frame. The generic adapter derives opaque dependencies and retires rejected nodes through generic scheduler+ discard. Forced compatibility uses `_IfBranchScheduler` topology and skip handling.- `_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. 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.+ 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`+ 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)@@ -394,14 +398,15 @@ 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.-- Once the prepared `If` node resolves its condition:- - the selected branch is released- - the unselected branch is marked skipped- - unselected input edges on the prepared `If` exec node are pruned from the execution graph so they no longer- participate in downstream indegree accounting- - branch-exclusive ancestors of the unselected branch are never executed-- Skipped branch-local exec nodes may still be treated as executed for scheduling purposes, but they do not create- entries in `results`.+- 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.+- Retired or skipped branch-local exec nodes may still be treated as executed for scheduling purposes, but they do not+ create entries in `results`.- Shared ancestors still execute if they are required by the selected branch or by any other live path in the graph.This behavior is implemented in the runtime scheduler, not in the invocation body itself.diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex ec7965af20..aa9afa96cc 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -328,6 +328,74 @@ class _PreparedExecRegistry:self._on_iteration_path_change(exec_node_id)+def _get_if_branch_exclusive_sources(state: "GraphExecutionState", if_node_id: str) -> dict[str, set[str]]:+ """Compile legacy If inputs into frame-independent branch source sets.++ This is a graph-compilation helper, not a scheduler transition. The+ generic adapter uses the result to attach opaque activation dependencies+ and retire unselected prepared nodes without mutating execution edges.+ """++ cached = state._if_branch_exclusive_sources.get(if_node_id)+ if cached is not None:+ return cached++ source_graph = state._get_source_graph_flat()+ branch_sources: dict[str, set[str]] = {}+ for branch_field in ("true_input", "false_input"):+ direct_inputs = {edge.source.node_id for edge in state.graph._get_input_edges(if_node_id, branch_field)}+ expanded = set(direct_inputs)+ for node_id in list(expanded):+ expanded.update(nx.ancestors(source_graph, node_id))++ exclusive_sources = set(expanded)+ changed = True+ while changed:+ changed = False+ for node_id in list(exclusive_sources):+ output_edges = state.graph._get_output_edges(node_id)+ stays_in_branch = all(+ edge.destination.node_id in exclusive_sources+ or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)+ for edge in output_edges+ )+ if not stays_in_branch:+ exclusive_sources.remove(node_id)+ changed = True+ branch_sources[branch_field] = exclusive_sources++ state._tx_set_mapping(state._if_branch_exclusive_sources, if_node_id, branch_sources)+ return branch_sources+++def _get_if_activation_dependencies(+ state: "GraphExecutionState", exec_node_id: str+) -> tuple[ActivationDependency, ...]:+ """Compile opaque branch requirements for one prepared execution node."""++ source_node_id = state._prepared_registry().get_source_node_id(exec_node_id)+ iteration_path = state._get_iteration_path(exec_node_id)+ dependencies: list[ActivationDependency] = []+ for source_if_id, source_if_node in state.graph.nodes.items():+ if not isinstance(source_if_node, IfInvocation):+ continue+ branches = _get_if_branch_exclusive_sources(state, 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)++class _IfBranchScheduler:"""Applies lazy `If` semantics by deferring, releasing, and skipping branch-local exec nodes."""@@ -416,46 +484,10 @@ class _IfBranchScheduler:self.mark_exec_node_skipped(prepared_id)def get_branch_exclusive_sources(self, if_node_id: str) -> dict[str, set[str]]:- cached = self._state._if_branch_exclusive_sources.get(if_node_id)- if cached is not None:- return cached-- branch_sources: dict[str, set[str]] = {}- for branch_field in ("true_input", "false_input"):- direct_inputs = self._get_branch_input_sources(if_node_id, branch_field)- candidate_nodes = self._expand_with_ancestors(direct_inputs)- branch_sources[branch_field] = self._prune_nonexclusive_branch_nodes(- if_node_id, branch_field, candidate_nodes- )-- self._state._tx_set_mapping(self._state._if_branch_exclusive_sources, if_node_id, branch_sources)- return branch_sources+ return _get_if_branch_exclusive_sources(self._state, if_node_id)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)+ 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)@@ -1263,9 +1295,8 @@ class _ExecutionMaterializer:self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)scheduler = self._state._scheduler()# Resolve a known conditional before registering its generic plan node so- # the compatibility edge pruning is reflected in its initial dependencies.- # Unresolved conditionals remain registered with all input dependencies;- # their activation resolution later synchronizes skipped work.+ # generic retirement can release unselected prerequisites without+ # mutating the append-only execution graph.if isinstance(scheduler, _GenericGraphSchedulerAdapter):self._state._try_resolve_if_node(exec_node_id)scheduler.register_node(exec_node_id)@@ -2224,6 +2255,64 @@ class _GenericGraphSchedulerAdapter:for dependency in self._scheduler.plan.nodes[exec_node_id].activation_dependencies)+ def _retire_unselected_node(self, exec_node_id: str) -> None:+ """Retire one unselected prepared node through generic scheduler state."""++ if exec_node_id not in self._scheduler.plan.nodes or exec_node_id in self._state.executed:+ return+ if exec_node_id in self._scheduler.discarded:+ return+ self._remove_projected(exec_node_id)+ self._state._set_prepared_exec_state(exec_node_id, "skipped")+ self._state._tx_add_set(self._state.executed, exec_node_id)+ self._scheduler.discard(exec_node_id)+ source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)+ prepared_nodes = self._state._prepared_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)++ def _retire_unselected_nodes(self, if_exec_node_id: str) -> None:+ source_if_node_id = self._state._prepared_registry().get_source_node_id(if_exec_node_id)+ branches = _get_if_branch_exclusive_sources(self._state, source_if_node_id)+ unselected_field = (+ "false_input" if self._state._resolved_if_exec_branches[if_exec_node_id] == "true_input" else "true_input"+ )+ iteration_path = self._state._get_iteration_path(if_exec_node_id)+ for prepared_id, prepared_source in tuple(self._state.prepared_source_mapping.items()):+ if self._state._get_iteration_path(prepared_id) != iteration_path:+ continue+ if prepared_source in branches[unselected_field]:+ self._retire_unselected_node(prepared_id)++ def resolve_if_node(self, exec_node_id: str) -> None:+ """Resolve legacy If inputs without pruning graph edges or using type-specific skips."""++ 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._state._apply_if_condition_inputs(exec_node_id, node):+ return++ selected_field = "true_input" if node.condition else "false_input"+ self._state._resolve_activation_gate(exec_node_id, selected_field)+ 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)+ self._retire_unselected_nodes(exec_node_id)+ self._sync_indegree()+ self._project_ready_nodes()++ def _retire_if_rejected_node(self, exec_node_id: str) -> None:+ node = self._scheduler.plan.nodes.get(exec_node_id)+ if node is None or not node.activation_dependencies:+ return+ if any(+ self._state._is_activation_dependency_rejected(dependency) for dependency in node.activation_dependencies+ ):+ self._retire_unselected_node(exec_node_id)+def _sync_executed_state(self, excluded: Iterable[str] = ()) -> None:excluded_ids = set(excluded)self._scheduler.executed.update(@@ -2260,6 +2349,7 @@ class _GenericGraphSchedulerAdapter:))self._state._tx_set_mapping(self._state.indegree, exec_node_id, self._scheduler.indegree[exec_node_id])+ self._retire_if_rejected_node(exec_node_id)if not self._initializing:self._project_ready_node(exec_node_id)@@ -4709,6 +4799,22 @@ class GraphExecutionState(BaseModel):return Falsereturn True+ 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)+ if gate.frame != self._expected_execution_ref(gate_id).frame:+ return False+ if gate.resolved and gate.selected_branch != dependency.branch:+ return True+ return False+def _resolve_activation_gate(self, exec_node_id: str, branch: str) -> bool:runtime = self._generic_runtime()gate = self._activation_gate(exec_node_id)@@ -5606,13 +5712,17 @@ class GraphExecutionState(BaseModel):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)+ return _get_if_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)def _try_resolve_if_node(self, exec_node_id: str) -> None:- self._if_scheduler().try_resolve_if_node(exec_node_id)+ 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)def set_ready_order(self, order: Iterable[Type[BaseInvocation] | str]) -> None:names: list[str] = []diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex e901ffacd8..44ebc6a08d 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -16,7 +16,14 @@ from invokeai.app.services.shared.execution_state_migration import (dump_execution_state,load_execution_state,)-from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState, _ExecutionScheduler+from invokeai.app.services.shared.graph import (+ Edge,+ EdgeConnection,+ Graph,+ GraphExecutionState,+ _ExecutionScheduler,+ _IfBranchScheduler,+)FIXTURE_PATH = Path(__file__).parents[3] / "fixtures" / "execution_engine" / "static_dag_v1.json"@@ -430,3 +437,32 @@ def test_fixture_is_versioned_and_future_versions_are_explicitly_rejected() -> Nfuture_snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1with pytest.raises(UnsupportedExecutionStateVersionError, match="newer than supported"):load_execution_state(future_snapshot)+++def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graph = _nested_if_graph()+ 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 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(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)++ trace, state = _run_graph(state)++ assert trace == ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"]+ sink_id = next(iter(state.source_prepared_mapping["sink"]))+ assert state.results[sink_id].value == 7+ assert state.is_complete()+ assert deleted_edges == []