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
feat(execution): route If readiness through opaque scheduler
JPPhoto0d45b8cbf318
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex 737fbfe130..20b173f259 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -90,13 +90,17 @@ explicit empty close. `Collect` consumes that buffer when available and retainscompatibility adapter. `loop_linkage` remains association metadata and never becomes a data token.`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the-selected branch, and the graph state validates and persists it after invocation. The legacy branch scheduler still-resolves `If` readiness and writes a compatibility token before invocation; `apply()` replaces that token by stable-identity, and activation effects are excluded from stream handling. Loop and saved-workflow control flow remain on-their compatibility paths until differential coverage proves their generic replacements.+selected branch, and the graph state validates and persists it after invocation. The generic opaque scheduler receives+an activation readiness predicate and skip projection for `If`; the private branch adapter still computes legacy+topology, resolves the gate, prunes the unselected edge, and writes the compatibility token before invocation.+`apply()` replaces that token by stable identity, and activation effects are excluded from stream handling. This is a+partial routing migration: author-time activation ports and literal successor IDs remain absent, while loop and+saved-workflow control flow remain on their compatibility paths until differential coverage proves their generic+replacements.The engine still owns runtime node materialization and queue readiness for loop-containing graphs and existing snapshots.-Ordinary static DAGs now use the generic opaque plan/scheduler through a compatibility projection. This is intentional:+Ordinary static DAGs and legacy-shaped `If` graphs now use the generic opaque plan/scheduler through a compatibility+projection. This is intentional:the generic records preserve tested loop semantics first, while the old execution graph remains the fallback for controllowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-timegraph JSON.diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex bfb4af2ebe..81a3803fdb 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -7,8 +7,9 @@ High-level design for the graph module. Focuses on responsibilities, data flow,Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**GraphExecutionState**) that expandsiterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), andexecutes 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 use the opaque `ExecutionPlan` and deterministic-`ExecutionScheduler` in `execution_engine/scheduler.py`; control-flow lowering remains behind the legacy graph adapter.+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.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@@ -49,8 +50,9 @@ external interface remains frozen; generated schemas may change only for additiv- `ChildExecutionCapability`, `ChildExecutionRecord`, and `ChildDependencyRecord` validate authorized parent/childrelationships, 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, deterministic ordering, completion, and durable plan rehydration.- It does not import invocation classes and cannot alter author-time graph or frontend contracts.+ 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 newfrontend node, input handle, or public workflow contract.@@ -122,9 +124,10 @@ Checks a single prospective edge before insertion:Holds the state for a single run. Keeps the source graph intact and materializes a separate execution graph.`GraphExecutionState` is still the public runtime entry point, but most execution behavior is now delegated to a small-set of internal helper classes. For ordinary static DAGs, readiness and completion are projected through the generic-`ExecutionPlan`/`ExecutionScheduler` adapter. `If`, `Iterate`, `Collect`, `For`, `ForReturn`, and saved-workflow call-lowering continue to use the legacy compatibility scheduler until their differential coverage is complete.+set of internal helper classes. For ordinary static DAGs and legacy-shaped `If` graphs, readiness and completion are+projected through the generic `ExecutionPlan`/`ExecutionScheduler` adapter. `Iterate`, `Collect`, `For`, `ForReturn`,+and saved-workflow call lowering continue to use the legacy compatibility scheduler until their differential coverage+is complete.The source graph is treated as stable during normal execution, but the runtime object still exposes guarded graphmutation helpers. Those helpers reject changes once the affected nodes have already been prepared or executed.@@ -158,9 +161,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre- `execution_tokens: dict[str, ExecutionToken]` - output tokens produced by applied execution results.- `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 derive readiness from the generic scheduler; control-flow- graphs retain the legacy scheduler. Optional `ready_order: list[str]` prioritizes classes. Queues are rebuilt from- persisted execution state when a session is deserialized.+ `_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.### 4.2 Core methods@@ -188,18 +191,20 @@ 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 oneframe-scoped activation token for the selected `true_input` or `false_input` port; `GraphExecutionState` validates thatport against the producing invocation's declared activation fields and persists it without creating a data stream.-The legacy `_IfBranchScheduler` still resolves readiness and writes a compatibility token before invocation; `apply()`-validates and persists the invocation-emitted effect afterward, replacing that token by stable identity. Activation-effects are excluded from data-stream handling. This is an additive effect declaration, not yet the generic-successor-routing migration. Other control-flow invocations remain on their legacy paths until differential coverage-proves each replacement.+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.`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, tokenkind, and optional sequence. `loop_linkage` remains association metadata and never becomes a data token. This ledger is-currently additive. Ordinary static-DAG readiness comes from the generic scheduler through a compatibility projection;-materialization and type-specific control paths remain authoritative for loop, branch, and workflow-call graphs. A-future migration may make tokens authoritative only after compatibility is proven.+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.The generic scheduler is an in-memory graph-state component only. It does notcreate, update, retry, cancel, delete, or recover `SessionQueueItem` rows and@@ -251,14 +256,16 @@ Workflow-call note:edges. When matching prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannotbe selected as live inputs.- `_GenericGraphSchedulerAdapter` Projects the generic `ExecutionPlan`/`ExecutionScheduler` into the existing state- fields for ordinary static DAGs; the generic scheduler owns readiness, indegree transitions, deterministic ordering,- claimed work, and completion.+ 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.- `_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` Applies lazy `If` semantics by deferring branch-local work until the condition is known, then- lowering the decision to a frame-scoped `ActivationGate` and persisted internal activation token, releasing the- selected branch, and skipping the unselected branch. Its topology analysis remains a compatibility adapter.+- `_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+ 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 adiff --git a/invokeai/app/services/shared/execution_engine/scheduler.py b/invokeai/app/services/shared/execution_engine/scheduler.pyindex 73acc7affc..fc37667ae2 100644--- a/invokeai/app/services/shared/execution_engine/scheduler.py+++ b/invokeai/app/services/shared/execution_engine/scheduler.py@@ -147,6 +147,7 @@ class ExecutionScheduler:self.plan = planself.ready_order = tuple(ready_order)self.executed: set[NodeId] = set(executed)+ self.skipped: set[NodeId] = set()self._ready_predicate = ready_predicateself._claimed: set[NodeId] = set()self.indegree: dict[NodeId, int] = {}@@ -172,6 +173,8 @@ class ExecutionScheduler:raise KeyError(f"unknown node: {node_id}")if node_id in self.executed:raise ValueError(f"node already completed: {node_id}")+ if node_id in self.skipped:+ return Falseif node_id in self._claimed:return Falseif node_id not in self.indegree:@@ -192,6 +195,23 @@ class ExecutionScheduler:self._enqueue_if_ready(node_id)+ def skip(self, node_id: NodeId) -> None:+ """Mark a node as intentionally inactive without executing its prerequisites."""++ if node_id not in self.plan.nodes:+ raise KeyError(f"unknown node: {node_id}")+ if node_id in self.executed:+ raise ValueError(f"node already completed: {node_id}")+ if node_id in self.skipped:+ return+ if node_id in self._claimed:+ raise ValueError(f"node already claimed: {node_id}")+ self._enqueued.discard(node_id)+ self._ready.discard(node_id)+ self._arrival_order.pop(node_id, None)+ self.skipped.add(node_id)+ self.rebuild_ready()+def _next_class(self) -> str | None:classes = {self.plan.nodes[node_id].class_name for node_id in self._enqueued}for class_name in self.ready_order:@@ -249,8 +269,13 @@ class ExecutionScheduler:if node.node_id not in self.plan.nodes:self.plan.add_node(node.node_id, node.class_name, node.frame, node.dependencies)- self.indegree[node.node_id] = sum(dependency not in self.executed for dependency in node.dependencies)- if self.indegree[node.node_id] == 0 and node.node_id not in self.executed and node.node_id not in self._claimed:+ satisfied = self.executed | self.skipped+ self.indegree[node.node_id] = sum(dependency not in satisfied for dependency in node.dependencies)+ if (+ self.indegree[node.node_id] == 0+ and node.node_id not in satisfied+ and node.node_id not in self._claimed+ ):self.enqueue(node.node_id)def discard(self, node_id: NodeId) -> None:@@ -273,6 +298,8 @@ class ExecutionScheduler:raise KeyError(f"unknown node: {node_id}")if node_id in self.executed:raise ValueError(f"node already completed: {node_id}")+ if node_id in self.skipped:+ raise ValueError(f"node was skipped: {node_id}")if node_id not in self.indegree:raise KeyError(f"indegree missing for node: {node_id}")if self.indegree[node_id] != 0:@@ -291,7 +318,7 @@ class ExecutionScheduler:newly_ready: list[NodeId] = []for dependent in dependents:self.indegree[dependent] -= 1- if self.indegree[dependent] == 0 and dependent not in self.executed:+ if self.indegree[dependent] == 0 and dependent not in self.executed and dependent not in self.skipped:if self._enqueue_if_ready(dependent):newly_ready.append(dependent)return tuple(newly_ready)@@ -299,17 +326,18 @@ class ExecutionScheduler:def rebuild_ready(self) -> None:"""Recompute indegrees and ready queue from plan and executed IDs."""- unknown = self.executed.difference(self.plan.nodes)+ unknown = (self.executed | self.skipped).difference(self.plan.nodes)if unknown:raise KeyError(f"unknown executed node: {next(iter(unknown))}")+ satisfied = self.executed | self.skippedfor node_id in self.executed:missing = [- dependency for dependency in self.plan.nodes[node_id].dependencies if dependency not in self.executed+ dependency for dependency in self.plan.nodes[node_id].dependencies if dependency not in satisfied]if missing:raise ValueError(f"executed node {node_id} is missing prerequisite: {missing[0]}")self.indegree = {- node_id: sum(dependency not in self.executed for dependency in node.dependencies)+ node_id: sum(dependency not in satisfied for dependency in node.dependencies)for node_id, node in self.plan.nodes.items()}previous_arrival = self._arrival_order@@ -320,6 +348,7 @@ class ExecutionScheduler:for node_id in self.plan.nodes:if (node_id not in self.executed+ and node_id not in self.skippedand node_id not in self._claimedand self.indegree[node_id] == 0and self._passes_ready_predicate(node_id)diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex befb9accf9..7e927bfd81 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -2178,8 +2178,14 @@ class _GenericGraphSchedulerAdapter:ready_predicate=self._is_node_activation_ready,)self._register_existing_nodes()- prepared_ids = set(state.prepared_source_mapping).intersection(state.executed)+ prepared_ids = set(state.prepared_source_mapping).intersection(state.results)+ skipped_ids = {+ exec_node_id+ for exec_node_id in state.prepared_source_mapping+ if state._get_prepared_exec_metadata(exec_node_id).state == "skipped"+ }self._scheduler.executed = prepared_ids+ self._scheduler.skipped = skipped_idsself._scheduler.rebuild_ready()self._initializing = Falseself._sync_indegree()@@ -2194,7 +2200,7 @@ class _GenericGraphSchedulerAdapter:excluded_ids = set(excluded)self._scheduler.executed.update(exec_node_id- for exec_node_id in self._state.executed+ for exec_node_id in self._state.resultsif exec_node_id not in excluded_ids and exec_node_id in self._scheduler.plan.nodes)self._scheduler.rebuild_ready()@@ -2282,9 +2288,7 @@ class _GenericGraphSchedulerAdapter:def mark_skipped(self, exec_node_id: str) -> None:"""Mirror a compatibility skip in the opaque scheduler projection."""- self._scheduler.discard(exec_node_id)- self._scheduler.executed.add(exec_node_id)- self._scheduler.rebuild_ready()+ self._scheduler.skip(exec_node_id)self._sync_indegree()self._project_ready_nodes()diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.pyindex 6aba836001..e1daea29cf 100644--- a/tests/app/services/shared/test_execution_engine_scheduler.py+++ b/tests/app/services/shared/test_execution_engine_scheduler.py@@ -61,6 +61,22 @@ def test_generic_scheduler_honors_opaque_readiness_predicate() -> None:assert scheduler.pop_next() == "blocked"+def test_generic_scheduler_tracks_skipped_nodes_without_prerequisites() -> None:+ plan = ExecutionPlan()+ plan.add_node("dependency", "Dependency")+ plan.add_node("skipped", "Work", dependencies=("dependency",))+ plan.add_node("after", "After", dependencies=("skipped",))+ scheduler = ExecutionScheduler(plan)++ scheduler.skip("skipped")++ assert scheduler.pop_next() == "after"+ scheduler.complete("after")+ assert scheduler.pop_next() == "dependency"+ with pytest.raises(ValueError, match="skipped"):+ scheduler.complete("skipped")++def test_generic_scheduler_preserves_legacy_class_drain_and_fifo_order() -> None:plan = ExecutionPlan()plan.add_node("late", "ZNode", frame=(1,))@@ -321,16 +337,61 @@ def test_graph_state_if_uses_generic_activation_routing() -> None:state.complete(node.id, node.invoke(Mock()))assert type(state._scheduler()).__name__ == "_GenericGraphSchedulerAdapter"- executed_sources = {- source_id for exec_node_id, source_id in state.prepared_source_mapping.items() if exec_node_id in state.executed+ completed_sources = {+ source_id for exec_node_id, source_id in state.prepared_source_mapping.items() if exec_node_id in state.results}- assert executed_sources == {+ assert completed_sources == {"condition","true_value","if",}+def test_graph_state_if_generic_and_legacy_paths_have_matching_completion() -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=False))+ 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"),+ )+ )++ def run(force_legacy: bool) -> tuple[list[str], set[str]]:+ state = GraphExecutionState(graph=graph.model_copy(deep=True))+ if force_legacy:+ object.__setattr__(state, "_execution_scheduler", _ExecutionScheduler(state))+ 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()))+ completed_sources = {+ source_id for exec_node_id, source_id in state.prepared_source_mapping.items() if exec_node_id in state.results+ }+ return trace, completed_sources++ legacy_trace, legacy_completed = run(force_legacy=True)+ generic_trace, generic_completed = run(force_legacy=False)++ assert generic_trace == legacy_trace+ assert generic_completed == legacy_completed == {"condition", "false_value", "if"}++def test_graph_state_static_dag_rehydrates_generic_scheduler_after_partial_run() -> None:graph = Graph()graph.add_node(AddInvocation(id="first", a=1, b=2))